Professional Documents
Culture Documents
Summary: in this tutorial, you will learn how to use SQL EXISTS to test if a subquery return one or more rows. This tutorial requires a good knowledge of subquery concept. If you do not know anything about the subquery, you can follow the SQL subquery tutorial before going forward with this tutorial. SQL EXISTS operator syntax SQL provides EXISTS operator to test if a subquery return one or more rows. The syntax of the EXISTS operator is as follows:
?
1SELECT customerid, companyName 2 3FROM customers 4WHERE EXISTS ( SELECT orderid 5 6 FROM orders 7 WHERE orders.customerid = customers.customerid)
SQL EXISTS with subquery returns NULL example If the subquery returns null, the expression EXIST NULL returns true. Lets take a look at the following example:
SQL NOT EXISTS example We can use NOT EXIST to find customer who has never purchased anything by checking if no order exist in the orders table:
?
1SELECT customerid, companyName 2 3FROM customers 4WHERE NOT EXISTS ( SELECT orderid 5 6 FROM orders 7 WHERE orders.customerid = customers.customerid)