SQL - Does the order of WHERE conditions matter?

Sql

Sql Problem Overview


Assume that category_id is an index key (not primary key) of table books. Is there any difference between the following two SQL statements?

SELECT * FROM books WHERE author='Bill' AND category_id=1

SELECT * FROM books WHERE category_id=1 AND author='Bill'

I guess filtering records first by category_id and then by author is faster than filtering them in reverse order. Are SQL engines smart enough to do it this way?

Sql Solutions


Solution 1 - Sql

No, the order of the WHERE clauses does not matter.

The optimizer reviews the query & determines the best means of getting the data based on indexes and such. Even if there were a covering index on the category_id and author columns - either would satisfy the criteria to use it (assuming there isn't something better).

Solution 2 - Sql

SQL is declarative.

In your example, you have told the engine/optimizer what you want... it will now work out the best way to do that (within reason and "cost" which would be off topic).

Solution 3 - Sql

Whereas in general, no, that assumes you're using a modern database. Maybe ten years ago, it certainly mattered then.

Solution 4 - Sql

In short, no, they do not matter as the optimizer will determine the best means for fetching the data.

Solution 5 - Sql

Yes, SQL is a declarative language. But in SQL Server (not sure about other engines) a DBA can actually (kinda) do this, by forcing an execution plan in SQL Query Store.

enter image description here

But, yeah, you can't control it from your app, or from within the query text itself.

P.S. 2 more cents: you can control the order of JOIN's by using FORCE ORDER.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpowerboyView Question on Stackoverflow
Solution 1 - SqlOMG PoniesView Answer on Stackoverflow
Solution 2 - SqlgbnView Answer on Stackoverflow
Solution 3 - SqlDean JView Answer on Stackoverflow
Solution 4 - SqlajdamsView Answer on Stackoverflow
Solution 5 - SqlAlex from JitbitView Answer on Stackoverflow