1

We have a query that retrieves some data from a master-detail simple schema. the WHERE clause looks like:

-- These are just random numbers
Where ticket.type_id in ( 2, 3, 4, 5, 7 ) and
      (
         ticket.color_id is null or
         ticket.color_id in ( 1, 2 , 8 )
      )

we already have indexes in the columns: ticket.type_id and ticket.color_id, anyway the QUERY EXPLAIN ANALYZE still show us that Postgresql is making a sequential scan to satisfy the query.

This query is really important and recurrent in the system, so we want to create an index specially for this case.

What index could solve this case?

12
  • 1
    If you just do Where ticket.type_id in ( 2, 3, 4, 5, 7 ) will it use the index? Commented Jun 5, 2012 at 21:43
  • It probably believes doing a sequential scan of the table is faster than re-scanning the index for each ID in the IN clause. Unless the table is very large and the specified type_ids are a small fraction of the data, it's probably right. Commented Jun 5, 2012 at 21:55
  • in this case, is a big table (millions of records), any extra ideas? Commented Jun 5, 2012 at 21:56
  • Can you paste in the EXPLAIN for Where ticket.type_id in ( 2, 3, 4, 5, 7 )? Commented Jun 5, 2012 at 22:03
  • 1
    Please provide the whole query. Is it only a simple WHERE? Does it have HAVING? ORDER BY? LIMIT? How many tables are joined? Commented Jun 5, 2012 at 23:44

2 Answers 2

3

First, check that an index will actually help you. Turn off sequence scans to force index usage before your query is called:

SET ENABLE_SEQSCAN TO OFF;

After your query runs:

SET ENABLE_SEQSCAN TO ON;

to re-enable sequence scans. If this shows no performance improvement Postgres is already choosing the correct execution plan (sequence scan). I'd run an explain analyze <query> for the entire query with sequence scan both on and off.

Have you run a vacuum analyze on the relevant tables? It's possible the planner doesn't have correct or current statistics for your query.

Sign up to request clarification or add additional context in comments.

Comments

1

not real sure - but i think the null is getting yuo..

maybe an oddball looking structure like this

Where ticket.type_id in ( 2, 3, 4, 5, 7 ) and
      (
         nvl(ticket.color_id,1) in ( 1, 2 , 8 )
      )

1 Comment

Nvl() is An Oracle function. Use coalesce(), but this can't use an index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.