Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "OR" in SQL Server short-circuiting?

Is the "OR" comparaison work like vb. I mean if he check each or if the first one is false

like

DECLARE @var1 bit;
SET @var1=1
DECLARE @var2 bit;
SET @var2=1

(@var1=1 or @var2=1)
AND ...

So, @var is equal to 1, we dont need to check var2, but did sql server will do the check?

Its about optimisation of a query (and memory of server)

tank you

like image 226
forX Avatar asked May 18 '26 17:05

forX


1 Answers

For the most part, yes, SQL Server does use short-circuiting for AND and OR statements, but sometimes the operations do not happen in the order you would expect. This is easy enough to test via the following:

SELECT '"Divide By Zero" error' AS [test] WHERE (1 / 0 = 1)

SELECT 'NO "Divide By Zero" error' AS [test] WHERE (1 = 1) OR (1 / 0 = 1)

You can find a more in-depth analysis here, by Gianluca Sartori: http://www.sqlservercentral.com/articles/T-SQL/71950/

like image 184
Solomon Rutzky Avatar answered May 20 '26 16:05

Solomon Rutzky



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!