You are on page 1of 2

SQL EXISTS

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:
?

1WHERE [NOT] EXISTS (subquery)


Lets examine the syntax above in a greater detail: WHERE [NOT] EXISTS: checks the subquery for existence of one or more rows. If the subquery returns at least one row, the expression in the WHERE clause returns a boolean value of TRUE. If you use NOT operator before the EXISTS operator, the expression will return a boolean value of TRUE if subquery returns no row. (subquery) : the subquery to test. You can use the EXISTS operator in any SQL statement that accepts WHERE clause such as SELECT, INSERT, UPDATEand DELETE. Examples of using SQL EXISTS operator We can use the EXISTS operator to find customer who has ordered products from us. For each customer in the customers table, we check if there is at least one order exists in the orders table.
?

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)

You might also like