SQL Basics | DML: Data Manipulation Language | EXISTS

EXISTS returns rows when the condition executed in WHERE has a result.

EXISTS syntax

SELECT "field_name1"
FROM "table_name1"
WHERE EXISTS
(SELECT "field_name2" FROM "table_name2" WHERE "search_condition");

EXISTS example

Given the following two tables, suppose you want to retrieve information for stores in the East region.

store_information table

store_name sales txn_date
Los Angeles 1500 Jan-05-2018
San Diego 250 Jan-07-2018
Los Angeles 300 Jan-08-2018
Boston 700 Jan-08-2018

geography table

region_name store_name
East Boston
East New York
West Los Angeles
West San Diego

To retrieve information for stores in the East region, use the following.

SELECT *
FROM store_information A1
WHERE EXISTS
(SELECT * FROM geography WHERE region_name = 'East' AND store_name = A1.store_name);

The result is as follows.

store_name sales txn_date
Boston 700 Jan-08-2018