Data Engineering

SQL EXISTS: Find Customers with an Order without Repeating Them

SoftwareJobs.io editorial29 November 20262 min read

Sometimes a report needs to know whether a related record exists, not display every related row. SQL EXISTS expresses that question directly. A small example is useful practice for Malta data analyst and engineering interviews.

Define the two tables

Imagine a customers table with Ada and Ben, each with a unique customer_id. An orders table has three orders for Ada and none for Ben. We want each customer who has at least one order. We do not need the order details.

SELECT c.customer_id, c.name
FROM customers AS c
WHERE EXISTS (
  SELECT 1 FROM orders AS o
  WHERE o.customer_id = c.customer_id
);

The expected result contains Ada once. EXISTS is true if its subquery returns at least one row. Ada’s extra orders do not create extra outer result rows. If the customers table itself contains repeated records, this query does not automatically clean them up. PostgreSQL explains EXISTS in its subquery reference.

Change the question carefully

To find customers with no matching orders, use NOT EXISTS with the same relationship. In this example, that returns Ben. To find customers with a completed order, add the agreed status condition inside the subquery. Write down which condition describes the related record before changing the query.

Practice checks

  • One customer with several orders.
  • One customer with no order.
  • One customer with only an order that fails the status condition.

Explain the intended result before discussing speed. EXISTS communicates a matching-record question clearly, but performance still depends on the database, data and actual query plan.

Sources and further reading

Explore current technology jobs in Malta →

PUT YOUR IDEAS INTO ACTION

What’s your next move?

Explore software, cloud and data roles that fit your skills and ambitions.

Explore opportunities
KEEP EXPLORING

More ideas for your next chapter