Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server performance tip [duplicate]

Possible Duplicate:
Is the SQL WHERE clause short-circuit evaluated?

I have the following question regarding this query:

select * from sometable 
where 1=1 or (select count(*) from table2 > 0)

If the first condition is true (1=1), does SQL Server still do the inner select? Or does it stop when the first condition is true (like C)

like image 783
francisco Avatar asked Apr 25 '26 17:04

francisco


2 Answers

It stops when the (1=1) is true. You can check easily using Ctrl-M then Ctrl-E

Consider this query

select * from master..spt_values
where 1=1 or (select count(*) from master..sysobjects) > 0

The execution plan only shows a scan in master..spt_values and no activity in sysobjects.

Contrary to C, it does not stop when the LEFTMOST condition is true, instead the query optimizer works out independently of order presented which is the least cost to evaluate. In the case of the constants 1 vs 1 the winner is clear.

like image 119
RichardTheKiwi Avatar answered Apr 27 '26 08:04

RichardTheKiwi


It is short circuited only because you are comparing literals. The optimiser detects this trivial comparison.

But if you have forced parameterisation set then the literals are changed to parameters and SQL Server works on a general case that each side could be different. Subject to the long list of conditions for forced parameterisation...

like image 33
gbn Avatar answered Apr 27 '26 06:04

gbn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!