473,804 Members | 3,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Index not being used properly

Hi,

I have a *huge* problem. I have a table with indexes on but the moment
I have an OR in my SELECT query it seems to not use the appropriate
index.

oasis=> \d purchases
Table "public.purchas es"
Column | Type |
Modifiers
-----------------+-----------------------
+-----------------------------------------------------------------
purch_id | integer | not null default
nextval('public .purchases_purc h_id_seq'::text )
purch_period | date | not null
purch_ven_code | integer | not null
purch_st_code | smallint | not null
purch_co_code | smallint | not null
purch_art_id | integer |
purch_gr_number | character varying(20) |
purch_qty | integer |
purch_amt | numeric(14,2) | not null
Indexes:
"pk_purchas es" primary key, btree (purch_id)
"idx_purch_art_ id" btree (purch_art_id)
"idx_purch_co_c ode" btree (purch_co_code)
"idx_purch_co_v en" btree (purch_co_code, purch_ven_code)
"idx_purch_per_ co_ven" btree (purch_period, purch_co_code,
purch_ven_code)
"idx_purch_peri od" btree (purch_period)
"idx_purch_st_c ode" btree (purch_st_code)
"idx_purch_ven_ code" btree (purch_ven_code )
Foreign-key constraints:
"fk_pur_ref_art icle" FOREIGN KEY (purch_art_id) REFERENCES
article(art_id) ON UPDATE RESTRICT ON DELETE RESTRICT
"fk_pur_ref_ven " FOREIGN KEY (purch_ven_code , purch_co_code)
REFERENCES vendor(ven_code , ven_co_code) ON UPDATE RESTRICT ON DELETE
RESTRICT
"fk_pur_ref_sto re" FOREIGN KEY (purch_st_code, purch_co_code)
REFERENCES store(st_code, st_co_code) ON UPDATE RESTRICT ON DELETE
RESTRICT

Look at these SQL queries:

oasis=> explain analyze select sum(purch_amt) as total from purchases
where purch_period between '2002-05-01 00:00:00' and '2003-12-31
00:00:00' and purch_co_code = 1::smallint and purch_ven_code =
2::integer;
QUERY
PLAN
------------------------------------------------------------------------
-------------------------------------------------------------------
Aggregate (cost=9350.57.. 9350.57 rows=1 width=11) (actual
time=1.699..1.6 99 rows=1 loops=1)
-> Index Scan using idx_purch_co_ve n on purchases
(cost=0.00..934 2.99 rows=3032 width=11) (actual time=0.033..1.1 73
rows=381 loops=1)
Index Cond: ((purch_co_code = 1::smallint) AND (purch_ven_code
= 2))
Filter: ((purch_period >= '2002-05-01'::date) AND
(purch_period <= '2003-12-31'::date))
Total runtime: 1.755 ms
(5 rows)

Firstly, why is there a filter? Why is the whole index not used?
However, the moment I add more entries to the purch_ven_code field,
look what happens:

oasis=> explain analyze select sum(purch_amt) as total from purchases
where purch_period between '2002-05-01 00:00:00' and '2003-12-31
00:00:00' and purch_co_code = 1::smallint and purch_ven_code in
(2::integer,3:: integer);

QUERY PLAN
------------------------------------------------------------------------
------------------------------------------------------------------------
----
Aggregate (cost=108705.81 ..108705.81 rows=1 width=11) (actual
time=14375.470. .14375.471 rows=1 loops=1)
-> Index Scan using idx_purch_co_co de on purchases
(cost=0.00..108 690.66 rows=6060 width=11) (actual
time=298.853..1 4372.228 rows=381 loops=1)
Index Cond: (purch_co_code = 1::smallint)
Filter: ((purch_period >= '2002-05-01'::date) AND
(purch_period <= '2003-12-31'::date) AND ((purch_ven_cod e = 2) OR
(purch_ven_code = 3)))
Total runtime: 14375.572 ms
(5 rows)

Now only the purch_co_code is in the index condition, not the rest.
Sometimes this takes up to 10 minutes to execute. There are many
records in the DB - and yes I have run VACUUM ANALYZE before running
these queries.

Lastly, look at this query (which uses the index correctly):

oasis=> explain analyze select sum(purch_amt) as total from purchases
where purch_period = '2002-05-01 00:00:00' and purch_co_code =
1::smallint and purch_ven_code in (2);
QUERY PLAN
------------------------------------------------------------------------
---------------------------------------------------------------------
Aggregate (cost=244.79..2 44.79 rows=1 width=11) (actual
time=76.592..76 .593 rows=1 loops=1)
-> Index Scan using idx_purch_per_c o_ven on purchases
(cost=0.00..244 .62 rows=65 width=11) (actual time=76.508..76 .549
rows=14 loops=1)
Index Cond: ((purch_period = '2002-05-01'::date) AND
(purch_co_code = 1::smallint) AND (purch_ven_code = 2))
Total runtime: 76.653 ms
(4 rows)

oasis=> select count(purch_per iod) from purchases;
count
----------
13956180
(1 row)

I am using this PostgreSQL for Linux:

postgres@waldop cl postgresql $ psql --version
psql (PostgreSQL) 7.4.1
contains support for command-line editing

Please can you help? This is for a mission critical system that is
close to its deadline, so I need help urgently please!

Regards,
Waldo Nell
Systems Engineer
PWN Consulting
---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 23 '05 #1
1 1459
Waldo Nell <pw****@telkoms a.net> writes:
I have a *huge* problem. I have a table with indexes on but the moment
I have an OR in my SELECT query it seems to not use the appropriate
index.


7.5 will be smarter about this, but in 7.4 and before you need to fool
with the column order of your indexes. The query structure is basically

WHERE col1 = const1 AND (col2 = const2 OR col2 = const3)

7.4 can turn this into a 2-column indexscan given an index on (col2,col1)
but not one on (col1,col2).

Your concern about the 3-column index can likewise be explained by
thinking about column order and how much of the index has to be scanned
for the given constraints. Generally you want equalities for the
leftmost index columns and ranges for only the rightmost columns in
order to keep the index scan range reasonable.

regards, tom lane

---------------------------(end of broadcast)---------------------------
TIP 7: don't forget to increase your free space map settings

Nov 23 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1562
by: Tim | last post by:
Hi all, Here is a brief description of a problem I encountered, and how I found a work around after 3 long days. I have a VB6 app that uses ADO and ODBC to get communicate with SQL server 2000 (sp3, running in win2003). Everything was running great for a few weeks, but one day an update statement that used to work just stopped working. It was a simple update of 1 field in a table (about 30 columns, about 20k records).
3
5824
by: charley | last post by:
Hello, The appearance of the page should be for the main image, lpmap.jpg, to be on the bottom, (z-index: 1), with pictures, (image0.jpg - image9.jpg), and accompaning notes to appear on top, (z-index: 2), minimized to 20px x 20px width & height, using the box model. These 10, (point0 to point9), are positioned on the map with the position style. These small images should then enlarge when the mouse hovers over them, (z-index: 3).
8
2130
by: John Baima | last post by:
I have an Access table that just consists of 2 columns: WordID (Autonumber, Primary key) and WordText (Text, Indexed, No dups). I've used this with a number of texts and languages without any problems. With my first Unicode Greek text, I've encountered a problem. The first 2 words of the text are "o(doi\ du/o". Now, those obviously are not the same words, but after I add the first, the second cannot be added because it thinks that I am...
5
17330
by: Bas Scheffers | last post by:
Hi, I have a table with about 100K rows, on which I have created a btree index of the type table_name(int, int, int, timestamp). At first postgres was using it for my AND query on all four columns, but after dropping it and creating different ones and testing, it suddenly stopped using it. Vaccuuming, reindexing, recreating the table and even recreating the database all didn't help.
3
2217
by: Eric Davies | last post by:
We've implemented a 5D box data type and have implemented both RTree and GiST access methods under PostgresSQL 7.4 and PostgresSQL 7.4.1. The 5D box internally looks like: struct Box5D{ float minBounds; float maxBounds; }; and so takes up 40 bytes and is of fixed length. The GiST access methods are basically a generalization of the 2D box indexing access methods from Refraction Research's PostGIS.
3
2170
by: Antanas | last post by:
Why is that even though I have added index with DESC sort order on primary key, records in Control Center are displayed by the sequence they were previously inserted, not by the value of primary key? If I perform REORG on table primary index, records get sorted by primary index properly. But when I enter new records afterwards, the new ones appear again sorted in sequence they were inserted into table. Why?
7
3177
by: ravidew | last post by:
Perhaps someone else can learn from my mistake. As many developers may have learned, the "z-index" CSS property can (generally) only be applied to an element that is positioned; in other words, an element that has "position: absolute" defined. What is not explicitly spelled out (perhaps because it's common sense to some... not me) is that when elements are nested, the inner elements cannot be z-index'ed above the parent.
3
2011
by: RogerInHawaii | last post by:
I've built a website and some of the pages are php pages (e.g. SomePage.php). It all works fine; both the html pages and the php pages come up and work just fine. I then made a change to the main index.html file and made it so that it's an index.php file instead, and it has some php code embedded in it, not much different than any of the other php pages on my site. But when I try to go to that index.php file, as the first file to bring up...
6
3943
by: Henry J. | last post by:
I have a composite index on two columns in a table. However, the index is not used in a query that restricts the 2nd column to a constant. If both columns are linked with columns in other join tables, the index will be used. To illustrate it with an example, I have a query like this: select s.ticker, p.quantity from stock s, positions p where s.type_id = 4
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9150
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7620
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5521
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4299
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.