SQL EXISTS

In this tutorial, we'll learn about the EXISTS operator in SQL and how to use them with examples.

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:

How EXISTS operator in SQL works
Working: EXISTS in SQL

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

How to use EXISTS operator in SQL
Example: EXISTS in SQL

Example 2: SQL EXISTS Operator

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
);
Did you find this article helpful?