tags:

views:

79

answers:

4

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?

A: 

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

ajdams
+4  A: 

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).

OMG Ponies
Although I do agree one thing I would add is that I would order your logic that will pass right away when using or statements or might fail right away when using and statements. No need to check other criteria if you can find out right away.
spinon
Can statistics that are not up to date affect this?
Abe Miessler
@Abe Miessler: Yes, statistics and indexes being out of date can negatively impact what the optimizer chooses. But the more data, the more costly it can be to keep these up to date.
OMG Ponies
+2  A: 

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).

gbn
+1 for the true statement. That said, Prolog is declarative and yet (at least with implementations I've used) the order of conditions matters.
Justin K
A: 

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

Dean J
Yes. It seems like the Oracle Rule Based Optimizer (RBO) would look at the order of predicates in a where clause when developing an execution plan.
Shannon Severance