SQL
Find Records Lacking Related Entries with SQL NOT EXISTS
Discover how to efficiently identify records in one table that do not have a corresponding entry in another table using a `NOT EXISTS` subquery.
SELECT
c.customer_id,
c.customer_name
FROM
customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
-- Or, alternatively, find products that have never been ordered:
SELECT
p.product_id,
p.product_name
FROM
products p
WHERE NOT EXISTS (
SELECT 1
FROM order_items oi
WHERE oi.product_id = p.product_id
);
How it works: This SQL snippet demonstrates how to find customers who have never placed an order using the `NOT EXISTS` clause with a subquery. The outer query selects customers, and the `WHERE NOT EXISTS` condition checks if there is *any* record in the `orders` table for that specific customer. If no such record exists, the customer is included in the result. This pattern is efficient for identifying missing relationships without a full outer join.