Friday, March 30, 2012

Order of conditions in a query

I have a query with many (approximately, 30) conditions, such as:

select ....... from table1 join table2 on ( (table1.field1 = table2.field1 OR table1.filed1 IS NULL) AND (table1.field2 = table2.field2 OR table1.filed2 IS NULL) )

My question is:

In C++ or C#, when I write a condition like this, say, in an IF or WHILE, I know that I would be better off specifying the IS NULL (well, == null, to be precise) first, and use | instead of ||. In that case, the first condition (equality to null) is checked first, it's fast, and if it's not satisfied, the control flow goes to the next statement.

The question is, is there the same rule in T-SQL?

I mean, if I put the "... IS NULL" first, and then "OR ... = ...", will the query run faster than if I write it the other way around (that is, "... = ... OR ... IS NULL")?

This is very important to me, because most of those fields are VARCHAR, and due to some business rules, I can't change them to numerics etc, which would be compared much faster than text. So, even if I use full text search, I still need to find a way to optimize the query for performance...

By the way, I know that I can put those conditions in the WHERE clause, but as far as I know it won't make much of a difference for performance. So, my question is primarily about the order of conditions, in which SQL Server constructs its query plan.

[Edited:] In other words, what runs faster: comparing varchar to null or comparing varchars? And does it make a difference if I switch their places in my sql script?

We are using SQL Server 2000 SP4, Standard Edition. [Dev edition on the dev machine.]

Could someone kindly advise me on this, please?

Thank you ever so much.

The way you have that written, can't you do a right join and omit the IS NULL condition?|||The order the WHERE clause is processed is "undefined" and "not guaranteed". So don't try to write something that is based on process order.

IS NULL is very fast compared to varchar equals. But the optimizer is going to "pick" how to best process the query and may not do it the same way every time.|||

The way you have that written, can't you do a right join and omit the IS NULL condition?

I'd love to, but it's an "either-or" from a business logic, and I'm not returning a set of rows, - this query is actually a part of the matching logic (a Notify function) for a Notification Services application. I'm sorry, I should have mentioned that.

Thank you.

sql

No comments:

Post a Comment