Re: Order of execution in logical expressions
- From: Erland Sommarskog <esquel@xxxxxxxxxxxxx>
- Date: Mon, 4 Jun 2007 21:46:13 +0000 (UTC)
Wayne Erfling (wayne_erfling@xxxxxxxxxxxxxx) writes:
GlacierI'm a little confused about order of execution in logical
expressions.
In a statement like this:
SELECT * FROM myTable
WHERE PK_ID > 0 OR
(PK_ID <=0 AND 1/0 > 5)
apparently statement compilation jumps in and detects the divide by zero
error, even though that clause would never be executed, because all
PK_IDs in myTable are in fact > 0.
T-SQL is not like C and Perl that shortcut in a well-defined manner,
but is like Pascal and the optimizer is free to whichever it likes.
There is only one way to control evaluation order, and that is the CASE
expression:
SELECT *
FROM myTable
WHERE 1 = CASE WHEN PK_ID > 0 THEN 1
WHEN PK_ID <=0 AND 1/0 > 5 THEN 1
ELSE 0
END
But it's nice to know that if you have:
SELECT *
FROM myTable
WHERE NOT EXISTS (SELECT *
FROM tbl
WHERE ...)
AND @myparam = 1
SQL Server will most likely not even touch the table in the subquery if
@myparam is <> 1.
This question arose because of a sub-query in an UPDATE TRIGGER:
...
IF NOT UPDATE(fieldname) OR
(SELECT DISTINCT fieldname FROM INSERTED) IS NULL)
For a multiple-row update, at execution time this statement returned an
error about multiple rows being returned from a sub-query.
But this has nothing to do with execution order. The SELECT DISTINCT
query can never be right. Replace with
NOT EXISTS (SELECT * FROM inserted WHERE fieldname IS NOT NULL)
When UPDATE(fieldname) is TRUE there can only be one value for fieldname,
the value supplied in the UPDATE statement.
There can be many values. Keep in mind a trigger fires once per statement,
not once per row.
--
Erland Sommarskog, SQL Server MVP, esquel@xxxxxxxxxxxxx
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
.
- Follow-Ups:
- Re: Order of execution in logical expressions
- From: Wayne Erfling
- Re: Order of execution in logical expressions
- References:
- Order of execution in logical expressions
- From: Wayne Erfling
- Order of execution in logical expressions
- Prev by Date: Re: SQL server 2000 RS printing problem
- Next by Date: SQL Load Testing Tools
- Previous by thread: Re: Order of execution in logical expressions
- Next by thread: Re: Order of execution in logical expressions
- Index(es):
Relevant Pages
|