Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an index improve performance when using modulo?

Imagine a MySQL table with one field id containing 1 billion rows from number 1 to a billion.

When I do a query like this

SELECT * FROM table WHERE id > 2000 AND id < 5000;

It is obvious that an index on id will improve the performance of that query.

However does such an index also help with modulo as in the following query

SELECT * FROM table WHERE (id % 4) = 0;

Does using an index help when using modulo?

like image 620
ectbxksp Avatar asked Mar 08 '26 15:03

ectbxksp


1 Answers

No.

Functions on columns used in an index (almost) always prevent the use of the index. Even if this weren't true, the optimizer might decide not to use an index anyway. Fetching just one out of four records may not be selective enough for the index to be worthwhile.

like image 182
Gordon Linoff Avatar answered Mar 10 '26 05:03

Gordon Linoff