0

I can't understand why my query is doing a sequential scan.

select columns
from table
where (column_1 ilike '%whatever%' or column_2 ilike '%whatever%')

I have an index on both column_1 and column_2.

The cardinality on both columns is very high.

My table is roughly 25 million rows.

What do you think I might be doing wrong? No matter what I do, it always does a sequential scan.

Edit #1: My index looks like this:

Create index xxx on table  (column_1, column_2);

Edit #2: Changing my sql query to

select columns
from table
where (column_1 ilike 'whatever%' and column_2 ilike 'whatever%')

still made my query use a sequential scan. I got the same result when I just used like instead of ilike. But this query:

select columns
from table
where (column_1 = 'whatever' and column_2 = whatever)

made my query use an index scan and my query went much faster :)

1

1 Answer 1

2

Two Reasons:

  • Your query does a OR condition in which index can't be used.
  • You are doing a ilike on "%xyz%". This can't use any help of sorted(i.e. indexed) data.

--

Edit: See if you can have like on "xyz%". Then index can be used if you do a separate condition on both columns (and separate index on both)

Edit2: By the query, the thing you are trying to do looks like Full Text Search. For that you would need search indexing techniques (Read Elasticsearch, Sphinx, Solr)

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

3 Comments

Can you edit your post and be more specific when you say do a separate condition on both columns?
Can you modify your where condition to do a 'like' condition as I mentioned above..
A trigram index can speed up ilike '%xyz%': dba.stackexchange.com/q/144899/1822

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.