SQL Server Performance Tip

Possible duplicate:
Is a WHERE SQL clause shorted?

I have the following question regarding this request:

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

If the first condition is true ( 1=1), is SQL Server still making internal choices? Or it stops when the first condition is true (e.g. C)

+3
source share
4 answers

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

Consider this request

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

In the execution plan, only scanning in master..spt_valuesand no activity in is displayed sysobjects.

C, , LEFTMOST , , . 1 vs 1 .

+7

, . .

, , SQL Server , , ...

+5

In general, SQL Server does not guarantee a short circuit of the boolean statement . Do not write queries that rely on a logical short circuit for performance or correctness.

+1
source

I will indicate that you can get different results if you say where 1 = 1 or id = 10, I know that I added 1 = 1 to the query and got different results. I would not use 1 = 1 with the OR clause under any circumstances.

0
source

Source: https://habr.com/ru/post/1792876/


All Articles