loading

MySQL EXISTS

The MySQL EXISTS Operator

To check if a record exists in a subquery, use the EXISTS operator.

In the event that the subquery yields one or more records, the EXISTS operation returns TRUE.

EXISTS Syntax

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

Demo Database

A sample from the “Products” table in the Northwind sample database is shown below:

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

And a selection from the “Suppliers” table:

SupplierIDSupplierNameContactNameAddressCityPostalCodeCountry
1Exotic LiquidCharlotte Cooper49 Gilbert St.LondonEC1 4SDUK
2New Orleans Cajun DelightsShelley BurkeP.O. Box 78934New Orleans70117USA
3Grandma Kelly’s HomesteadRegina Murphy707 Oxford Rd.Ann Arbor48104USA
4Tokyo TradersYoshi Nagase9-8 Sekimai Musashino-shiTokyo100Japan

MySQL EXISTS Examples

The vendors whose product prices are less than 20 are listed in the following SQL statement, which returns TRUE:

Example

				
					SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);
				
			

The following SQL statement returns TRUE and lists the suppliers with a product price equal to 22:

Example

				
					SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price = 22);
				
			
Share this Doc

MySQL EXISTS

Or copy link

Explore Topic