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

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

DROP TABLE IF EXISTS

We can add an optional IF EXISTS command with the DROP TABLE clause. For example,

DROP TABLE IF EXISTS my_table;
CREATE TABLE IF NOT EXISTS

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)
);
Another SQL EXISTS Example

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
);

Table of Contents

Did you find this article helpful?