Microsoft® SQL Server® 2012 Bible

(Ben Green) #1

128


Part II: Building Databases and Working with Data


Although the two preceding queries are similar, in the fi rst query the natural order of
precedence for Boolean operators caused the AND to be evaluated before the OR. The OR
included the Chains in the results.

The second query used parentheses to explicitly dictate the order of the Boolean operators.
The OR collected the Chains and products with a ProductID of 952, 324, 322, 320, 321, or


  1. This list was then ANDed with products that included the letter g in their names. Only
    products 320 and 324 passed both of those tests.


Best Practice


When coding complex Boolean or mathematical expressions, explicitly stating your intentions with
parentheses and detailed comments reduces misunderstandings and errors based on false assumptions.

SELECT ... WHERE
Surprisingly, using the WHERE clause in a SELECT statement does not require the use of
a FROM clause or any data source reference. A SELECT statement without a FROM clause
returns a single row that includes any expressions in the SELECT’s column list.

A WHERE clause on a nontable SELECT statement serves as a restriction to the entire
SELECT statement. If the WHERE condition is true, the SELECT statement functions as
expected:

SELECT 'abc' AS col
WHERE 1>0;

Result:

col
----
abc
(1 row(s) affected)

If the WHERE condition is false, the SELECT statement still executes but it returns zero
rows:

SELECT 'abc' AS col WHERE 1<0;

Result:

col
----

c06.indd 128c06.indd 128 7/30/2012 4:16:04 PM7/30/2012 4:16:04 PM


http://www.it-ebooks.info
Free download pdf