TOP

SQL EXISTS Statement

YouLibreCalc for Excel logo

SQL EXISTS Description

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.


EXISTS Syntax

SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition)

Demonstration database

The following is a sample from the "Products" ("Products") table of the Northwind database:

ProductIDProductNameSupplierIDCategoryIDUnitPrice
1Chais1110 boxes x 20 bags18.00
2Chang1124 - 12 oz bottles19.00
3Aniseed Syrup1212 - 550 ml bottles10.00
4Chef Anton's Cajun Seasoning2248 - 6 oz jars22.00
5Chef Anton's Gumbo Mix2236 boxes21.35

And the sample from the table "Suppliers" ("Suppliers"):

SupplierIDSupplierNameContactNameAddressCityPostalCodeCountryPhone
1Exotic LiquidCharlotte Cooper49 Gilbert St.LondonaEC1 4SDUK(171) 555-2222
2New Orleans Cajun DelightsShelley BurkeP.O. Box 78934New Orleans70117USA(100) 555-4822
3Grandma Kelly's HomesteadRegina Murphy707 Oxford Rd.Ann Arbor48104USA(313) 555-5735
4Tokyo TradersYoshi Nagase9-8 Sekimai Musashino-shiTokyo100Japan(03) 3555-5011
5Cooperativa de Quesos 'Las Cabras'Antonio del Valle SaavedraCalle del Rosal 4Oviedo33007Spain(98) 598 76 54

SQL EXISTS Examples

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)