The SQL EXISTS
operator executes the outer SQL query if the subquery is not NULL
(empty result-set). For example,
SELECT customer_id, first_name
FROM Customers
WHERE EXISTS (
SELECT order_id
FROM Orders
WHERE Orders.customer_id = Customers.customer_id
);
Here is how the SQL command works:

This process is repeated for each row of the outer query.

SQL NOT EXISTS
We can also use the NOT operator to inverse the working of the EXISTS
clause. The SQL command executes if the subquery returns an empty result-set. For example,
SELECT customer_id, first_name
FROM Customers
WHERE NOT EXISTS (
SELECT order_id
FROM Orders
WHERE Orders.customer_id = Customers.customer_id
);
Here, the SQL command returns a row from the Customers table if the related row is not in the Orders table.
SQL EXISTS Examples
We can add an optional IF EXISTS
command with the DROP TABLE clause. For example,
DROP TABLE IF EXISTS my_table;
We can add an optional IF NOT EXISTS
command with the CREATE TABLE clause. For example,
CREATE TABLE IF NOT EXISTS Companies (
id int,
name varchar(50),
address text,
email varchar(50),
phone varchar(10)
);
The below SQL query selects orders from the order table for customers who are older than 23 years.
SELECT *
FROM Orders
WHERE EXISTS (
SELECT customer_id
FROM Customers
WHERE Orders.customer_id = Customers.customer_id
AND Customers.age > 23
);