SQL 2008 Essentials

Page 248

7.6

THE DIFFERENCE OPERATION

233

Now, if we want to find all the departments that do not have instructors, we could type the following query: SELECT * FROM Department to major d WHERE d.dcode NOT IN (SELECT dcode FROM Department to major d, Instructor i WHERE d.dcode=i.teaches) This produces the following output (six rows): DCODE ----ACCT ART CHEM ENGL POLY UNKN

DNAME -------------------Accounting Art Chemistry English Political Science NULL

(6 row(s) affected) Note that in this case, the NOT .. IN predicate “behaved” correctly and reported the NULL value for dname because the query is looking for department codes in the Instructor table; the null is part of the Department to major table and not involved in the subquery link.

7.6 The Difference Operation Because SQL Server 2008 does not support the MINUS predicate, we will show the set difference operation using a NOT.. IN predicate with two examples. Example 7.1

Suppose set A is the set of students in classes 2, 3, or 4 and set B is the set of students in class = 2. We could use the NOT .. IN predicate to remove the students in set B from set A (a difference operation) by typing the following query: SELECT sname, class FROM Student WHERE class IN (2, 3, 4) AND NOT class IN (2)


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.