Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does order of items in an SQL: WHERE IN () matter?

Does the order of the values in a WHERE IN clause matter? (this is on Firebird SQL if that is important)

Such as does:

where field1 in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

offer a performance increase over

where field1 in (3, 5, 10, 2, 1, 8, 6, 9, 4, 7)
like image 879
Chris Valentine Avatar asked Apr 29 '13 01:04

Chris Valentine


People also ask

Does order matter in WHERE clause SQL?

No, that order doesn't matter (or at least: shouldn't matter). Any decent query optimizer will look at all the parts of the WHERE clause and figure out the most efficient way to satisfy that query.

Does the order of the WHERE clause make a difference?

No. The order of columns in the WHERE clause does not matter at all.

Can we use WHERE after ORDER BY in SQL?

ORDER BY Characteristics: The ORDER BY clause is used to get the sorted records on one or more columns in ascending or descending order. The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query. Use ASC or DESC to specify the sorting order after the column name.

Does order of WHERE clause matter for index?

Yes, order matters.


1 Answers

Yes it will, but possibly in an implementation dependent manner. The IN is processed as sequential OR's, and one might assume that the most likely processing order is as written.

That said, I would start by assuming that the optimizer will process the elements in the order given, because that is easiest, and rank them in the set from most- to least-likely. It can't hurt, and will most probably help. Whether the difference is measurable or significant is another matter; measure it and let us know.

like image 91
Pieter Geerkens Avatar answered Oct 20 '22 21:10

Pieter Geerkens