The EXISTS operator is used to check the existence of any record in the subquery.
The EXISTS operator returns TRUE if the subquery returns one or more records.
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition)
The following is a sample from the "Products" ("Products") table of the Northwind database:
ProductID | ProductName | SupplierID | CategoryID | Unit | Price |
---|---|---|---|---|---|
1 | Chais | 1 | 1 | 10 boxes x 20 bags | 18.00 |
2 | Chang | 1 | 1 | 24 - 12 oz bottles | 19.00 |
3 | Aniseed Syrup | 1 | 2 | 12 - 550 ml bottles | 10.00 |
4 | Chef Anton's Cajun Seasoning | 2 | 2 | 48 - 6 oz jars | 22.00 |
5 | Chef Anton's Gumbo Mix | 2 | 2 | 36 boxes | 21.35 |
And the sample from the table "Suppliers" ("Suppliers"):
SupplierID | SupplierName | ContactName | Address | City | PostalCode | Country | Phone |
---|---|---|---|---|---|---|---|
1 | Exotic Liquid | Charlotte Cooper | 49 Gilbert St. | Londona | EC1 4SD | UK | (171) 555-2222 |
2 | New Orleans Cajun Delights | Shelley Burke | P.O. Box 78934 | New Orleans | 70117 | USA | (100) 555-4822 |
3 | Grandma Kelly's Homestead | Regina Murphy | 707 Oxford Rd. | Ann Arbor | 48104 | USA | (313) 555-5735 |
4 | Tokyo Traders | Yoshi Nagase | 9-8 Sekimai Musashino-shi | Tokyo | 100 | Japan | (03) 3555-5011 |
5 | Cooperativa de Quesos 'Las Cabras' | Antonio del Valle Saavedra | Calle del Rosal 4 | Oviedo | 33007 | Spain | (98) 598 76 54 |
The following SQL query returns TRUE and contains a list of suppliers with a product price less than 20:
Run SQLSELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName
FROM Products
WHERE Products.SupplierID = Suppliers.supplierID
AND Price < 20)
Another SQL statement returns TRUE and contains a list of suppliers with a product price equal to 22:
Run SQLSELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName
FROM Products
WHERE Products.SupplierID = Suppliers.supplierID
AND Price = 22)