简体   繁体   中英

Indexing 5 columns

I have the following query:

SELECT * 
FROM table 
WHERE active = 1 
  AND deleted = 0 
  AND blocked = 0 
  AND created_at <= NOW() 
  AND last_action_at <= NOW() 
LIMIT 5000;

I have an index set on (deleted, active) , so it reduces me some rows, but out of 2,5mln records it still traverses 1,5mln.

I also tried adding the following indexes:

(created_at, last_action_at)
(active,deleted,blocked,created_at,last_action_at)

But the query doesn't use them, and uses the first one I mentioned instead. I also tried changing range conditions to the first position in WHERE clause, but it also didn't change anything.

What's wrong?

Nothing is wrong, it's just more efficient to use one index over another. In this case I would bet the index used is the clustered one.

Unless you are selecting a really tiny proportion of rows, no index will help unless it's the clustered one in which case it's really only used because it is actually the data, ie it's a slightly more efficiently bounded table scan.

You might also find that an index on a column that allows nulls can be excluded from a search if null is not excluded.

What's your expected final row count and your query plan?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM