Lessons › SQL › Deep Dive: Advanced Joins & Subqueries
SQL lesson
EXISTS and NOT EXISTS
EXISTS checks whether at least one matching row turns up somewhere else in your data - it's a yes-or-no test, not a count. NOT EXISTS flips that answer, keeping only the rows where nothing matched.
Try this lesson free →Example
Checking Related Retail Records with EXISTS and NOT EXISTS
SELECT c.customer_id, c.region
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
)| customer_id | region |
|---|---|
| C002 | South |
| C005 | North |
Step by step
- After SELECT, list the column names you want, separated by commas.
SELECT c.customer_id, c.region - FROM tells SQL which table to pull the data from.
SELECT c.customer_id, c.region FROM customers c - WHERE keeps only the rows that match your condition.
SELECT c.customer_id, c.region FROM customers c WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id );
Practice
1. Write a query to find rows in orders that do not have a matching row in order_details on order_id.
SELECT * FROM orders WHERE NOT EXISTS (SELECT 1 FROM order_details WHERE order_details.order_id = orders.order_id)Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →