Finding entities with no related records — customers who've never ordered, users who've never logged in — is one of the most practical and frequently mishandled SQL skills. This lesson teaches you three production-ready patterns using LEFT JOIN, NOT IN, and NOT EXISTS, including the NULL pitfall that silently breaks queries and how to avoid it.

You're three weeks into a new role and your manager drops a task on your desk: "Find all the customers who've never placed an order." Simple enough request. You write an INNER JOIN, get back a list, and hand it over. Your manager looks at the results and says, "That's odd — this doesn't include the 847 customers we imported last month." You've just discovered one of the most common and consequential mistakes in SQL: when you're looking for the absence of something, most JOIN types will silently hide exactly what you're searching for.
Finding entities with no related records — customers who've never ordered, users who've never logged in, products that have never been purchased, accounts with no transactions — is one of the most practical skills in data analysis. It powers churn detection, data quality audits, compliance checks, and lead prioritization. The tricky part is that the standard "get me related data" toolkit doesn't work here. You need patterns specifically built for absence.
By the end of this lesson, you'll have a solid, production-ready toolkit for finding orphaned and inactive data. You'll understand why the patterns work at a logical level, not just how to copy-paste them.
What you'll learn:
This lesson assumes you're comfortable with:
You don't need to be an expert in any of these. But if terms like "foreign key," "NULL," or "correlated subquery" are completely unfamiliar, spend twenty minutes on those resources first.
Before we get into solutions, let's understand the problem precisely. Consider a standard e-commerce schema:
-- customers table
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
email VARCHAR(255),
created_at TIMESTAMP,
country VARCHAR(50)
);
-- orders table
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT, -- foreign key to customers
order_date DATE,
total_amount DECIMAL(10,2)
);
Say you want to find customers who have never placed an order. A new SQL writer might try:
-- ❌ This does NOT find customers with no orders
SELECT c.customer_id, c.email
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_id IS NULL;
This query returns zero rows — always. INNER JOIN (the default JOIN) only returns rows where matches exist in both tables. If a customer has no orders, there's no row in orders to join to, so that customer is eliminated from the result set entirely. Then the WHERE clause checks for NULL on a column that only has real values (because those are the only rows that survived the join). It's logically impossible for this to return anything useful.
This is worth internalizing: when you INNER JOIN two tables, you've already thrown away every customer who has no orders before your WHERE clause even runs.
Key insight
Filtering for absent relationships has to happen in a way that keeps the "no match" rows in play. You need a technique that preserves unmatched rows from the left table. That's exactly what LEFT JOIN does — but only if you use it correctly.
This is the most readable and widely understood pattern for finding unmatched rows. The logic is clean: bring every row from the left table regardless of whether it has a match, then filter to keep only the rows where no match was found.
-- ✅ Find customers who have never placed an order
SELECT
c.customer_id,
c.email,
c.created_at,
c.country
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.customer_id IS NULL;
Let's trace through the logic:
LEFT JOIN orders o — Every row from customers is preserved. For customers with orders, the orders columns are populated. For customers with no orders, the orders columns are all NULL.WHERE o.customer_id IS NULL — This keeps only the rows where no match was found, i.e., the unmatched customers.Notice we filter on o.customer_id, not o.order_id. Either column works technically, but filtering on the join key (customer_id) makes the intent crystal clear: "where there's no matching record in orders."
Tip
You can use any non-nullable column from the right table in your IS NULL check. Using the foreign key column (o.customer_id) is a good convention because it directly expresses the relationship you're testing.
Let's move to a scenario with more business context. You're working with a SaaS product that has users and login events. Your growth team wants a list of users who have never logged in — these are the people who signed up but never activated.
-- users table: everyone who created an account
-- login_events table: one row per login
SELECT
u.user_id,
u.email,
u.signup_date,
u.plan_type
FROM users u
LEFT JOIN login_events le ON u.user_id = le.user_id
WHERE le.user_id IS NULL
ORDER BY u.signup_date DESC;
This gives you the never-activated users. If you want to add more business context, you can extend it:
SELECT
u.user_id,
u.email,
u.signup_date,
u.plan_type,
CURRENT_DATE - u.signup_date::DATE AS days_since_signup
FROM users u
LEFT JOIN login_events le ON u.user_id = le.user_id
WHERE le.user_id IS NULL
AND u.signup_date >= CURRENT_DATE - INTERVAL '90 days'
ORDER BY u.signup_date DESC;
Now you're looking at people who signed up in the last 90 days and still haven't logged in — a targeted activation problem. This is the kind of query you'd hand to a lifecycle marketing team.
Warning
LEFT JOIN with IS NULL finds rows with zero matching records. If a customer has even one order, they won't appear. If you need "customers who haven't ordered in 90 days" (at least one historical order, but nothing recent), that's a different pattern — we'll cover it in the time-windowed section later.
The second major pattern uses a subquery to build a list of entity IDs that do have related records, then excludes them.
-- ✅ Find customers who have never placed an order
SELECT
customer_id,
email,
created_at
FROM customers
WHERE customer_id NOT IN (
SELECT customer_id
FROM orders
);
This is often more intuitive to read aloud: "Give me customers whose ID is not in the list of customer IDs that appear in orders." For many people this reads more naturally than the LEFT JOIN version.
Here's where things get dangerous in production. The NOT IN pattern has a severe failure mode that bites people constantly, and it's rooted in how SQL handles NULLs.
Imagine your orders table has even one row where customer_id is NULL. This can happen with bad data, an optional foreign key column, or a migration that left some nulls behind.
-- What happens when orders has a NULL customer_id?
SELECT customer_id FROM orders;
-- Result: 101, 102, 103, NULL, 105, 108...
Now when SQL evaluates customer_id NOT IN (101, 102, 103, NULL, 105, 108...), it has to check whether each customer's ID matches any value in the list. When it reaches NULL, the comparison is customer_id = NULL, which is never TRUE or FALSE — it's UNKNOWN. SQL's three-valued logic means that if any comparison returns UNKNOWN, the entire NOT IN expression returns UNKNOWN, which acts like FALSE.
The result? The entire query returns zero rows. No error. No warning. Just silently empty results.
-- ❌ This returns nothing if ANY row in orders has a NULL customer_id
SELECT customer_id, email
FROM customers
WHERE customer_id NOT IN (
SELECT customer_id FROM orders -- NULL in here = silent failure
);
The fix is simple once you know about it:
-- ✅ Defensive NOT IN: always filter NULLs from the subquery
SELECT customer_id, email
FROM customers
WHERE customer_id NOT IN (
SELECT customer_id
FROM orders
WHERE customer_id IS NOT NULL -- This saves you
);
Warning
Always add WHERE column IS NOT NULL to any NOT IN subquery in production code. Even if your data is clean today, one bad import or schema change can make a NOT IN query silently return nothing — the most dangerous kind of bug because it looks correct.
For a deeper look at NULL behavior in SQL, see NULL Handling in SQL: IS NULL, COALESCE, and NULLIF.
The third pattern uses NOT EXISTS, which many experienced SQL writers consider the most semantically precise way to express "find rows with no related records."
-- ✅ Find customers who have never placed an order
SELECT
c.customer_id,
c.email,
c.created_at
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
The inner SELECT is a correlated subquery — it references c.customer_id from the outer query, so it runs once per customer row. For each customer, it checks: "Does at least one order exist for this customer?" If the answer is no, NOT EXISTS is TRUE and the customer is included in results.
Notice SELECT 1 in the subquery. The actual value selected doesn't matter — EXISTS only cares whether any rows come back, not what those rows contain. SELECT 1, SELECT *, and SELECT order_id are all equivalent here. SELECT 1 is conventional because it signals clearly that you're not trying to retrieve data.
Unlike NOT IN, NOT EXISTS doesn't suffer from NULL contamination. The correlated subquery is simply asking "do any rows exist?" rather than comparing values against a list. Even if orders.customer_id has nulls, the existence check isn't affected — the null rows just don't match the WHERE o.customer_id = c.customer_id condition, so they're ignored.
-- ✅ NOT EXISTS behaves correctly even with NULL foreign keys
SELECT
c.customer_id,
c.email
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
-- No special NULL handling needed
);
This NULL safety is one of the main reasons experienced SQL developers often prefer NOT EXISTS over NOT IN.
For more on correlated subqueries and their broader applications, Mastering SQL EXISTS and NOT EXISTS: Correlated Subquery Patterns for Filtering with Related Data goes deeper on this topic.
Each pattern has the same logical purpose but different characteristics. Here's how they stack up:
| Pattern | Readable? | NULL Safe? | Performance Profile |
|---|---|---|---|
| LEFT JOIN + IS NULL | Very high | Yes | Generally fast with indexes on join keys |
| NOT IN + subquery | High | Only with explicit filter | Can be slow on large subquery results |
| NOT EXISTS | Medium | Yes | Often best for correlated checks; optimizer-friendly |
On readability: LEFT JOIN + IS NULL wins for most analysts because it uses familiar JOIN syntax. NOT IN reads naturally in plain English. NOT EXISTS is preferred by developers who think in set logic.
On performance: This varies by database engine and data volume. In PostgreSQL and SQL Server, NOT EXISTS often performs equivalently or better than LEFT JOIN + IS NULL because the query optimizer recognizes both and may execute them the same way. NOT IN with large subquery result sets can be problematic because the database has to load the entire list into memory. That said, don't optimize prematurely — test on your actual data.
Tip
When your "right side" table is large (millions of rows), LEFT JOIN + IS NULL or NOT EXISTS will usually outperform NOT IN. Add an index on the foreign key column (orders.customer_id in our examples) and both patterns become very fast. See SQL Indexes Explained: How They Work and When to Create Them for guidance on where to add indexes.
The patterns above find complete absence — entities that never had a related record. But real business questions are often more nuanced: "which customers haven't ordered in 90 days?" or "which users haven't logged in since last quarter?"
This is a different problem. These customers do have orders; they're just not recent. The approach shifts.
-- Customers who have ordered before but not in the last 90 days
SELECT
c.customer_id,
c.email,
MAX(o.order_date) AS last_order_date,
CURRENT_DATE - MAX(o.order_date) AS days_since_last_order
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.email
HAVING MAX(o.order_date) < CURRENT_DATE - INTERVAL '90 days'
OR MAX(o.order_date) IS NULL;
The HAVING clause here does two things: it catches customers whose last order was more than 90 days ago, plus it catches customers who have never ordered at all (where MAX is NULL). This combined approach is useful when your stakeholder wants "everyone who isn't actively purchasing."
For more on HAVING clause patterns, Filtering Groups After Aggregation: Writing HAVING Clauses That Answer Real Business Questions is worth reading.
Another elegant approach: join on a time-bounded condition, then filter for no match.
-- Customers with no orders in the last 90 days
-- (includes both never-ordered AND recently-lapsed)
SELECT
c.customer_id,
c.email,
c.created_at
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id
AND o.order_date >= CURRENT_DATE - INTERVAL '90 days'
WHERE o.customer_id IS NULL;
This is a subtle but powerful technique: the time filter goes in the ON clause, not the WHERE clause. If you put o.order_date >= ... in the WHERE clause, it would eliminate customers with no recent orders (because NULL doesn't satisfy the comparison), which defeats the purpose. In the ON clause, it's part of the join condition — a customer only gets a match if they ordered in the last 90 days. If they didn't, their orders columns are NULL, and the WHERE clause catches them.
Key insight
Moving a filter from WHERE to the ON clause changes its semantics fundamentally with a LEFT JOIN. WHERE filters happen after the join and can eliminate non-matching rows. ON conditions are part of the join logic itself and preserve unmatched rows from the left table.
The same patterns apply to data quality work, not just business analytics. "Orphaned records" are rows in a child table that reference a parent that doesn't exist — a symptom of missing foreign key constraints or bad data migrations.
-- Find orders with no matching customer (orphaned orders)
SELECT
o.order_id,
o.customer_id,
o.order_date,
o.total_amount
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id
WHERE c.customer_id IS NULL;
Here we've flipped the direction: orders is now the left table, customers is the right. Any order that references a non-existent customer shows up with NULL customer columns.
This kind of query is essential when you're auditing a database schema, investigating referential integrity issues, or preparing a migration. A few variants worth knowing:
-- Count orphans by table to assess data quality scope
SELECT
'orders' AS source_table,
COUNT(*) AS orphaned_count
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id
WHERE c.customer_id IS NULL
UNION ALL
SELECT
'order_items' AS source_table,
COUNT(*) AS orphaned_count
FROM order_items oi
LEFT JOIN orders o ON oi.order_id = o.order_id
WHERE o.order_id IS NULL;
This kind of multi-table audit query quickly tells you where your data quality problems live.
Sometimes you need to find entities that have no related records across multiple tables. For example: "find users who have never posted, never commented, and never liked anything" — the completely passive accounts.
SELECT
u.user_id,
u.email,
u.signup_date
FROM users u
LEFT JOIN posts p ON u.user_id = p.author_id
LEFT JOIN comments c ON u.user_id = c.author_id
LEFT JOIN likes l ON u.user_id = l.user_id
WHERE p.post_id IS NULL
AND c.comment_id IS NULL
AND l.user_id IS NULL;
Each LEFT JOIN adds a new "absence check." The WHERE clause then requires that all three are unmatched. This is clean and efficient — a single pass through the data.
SELECT
u.user_id,
u.email
FROM users u
WHERE NOT EXISTS (SELECT 1 FROM posts WHERE author_id = u.user_id)
AND NOT EXISTS (SELECT 1 FROM comments WHERE author_id = u.user_id)
AND NOT EXISTS (SELECT 1 FROM likes WHERE user_id = u.user_id);
Both approaches work. The chained LEFT JOIN approach is typically faster because it's a single query plan. The NOT EXISTS approach can be clearer when each subquery has complex filtering conditions.
Work through this exercise to cement the patterns. Use the following schema:
-- Schema
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(200),
category VARCHAR(50),
list_price DECIMAL(10,2),
added_date DATE
);
CREATE TABLE order_items (
item_id INT PRIMARY KEY,
order_id INT,
product_id INT,
quantity INT,
unit_price DECIMAL(10,2)
);
CREATE TABLE reviews (
review_id INT PRIMARY KEY,
product_id INT,
customer_id INT,
rating INT,
review_date DATE
);
Part 1: Write a query using LEFT JOIN + IS NULL to find all products that have never appeared in any order. Show product_id, product_name, category, and list_price.
Part 2: Rewrite Part 1 using NOT EXISTS.
Part 3: Find products that have no reviews AND have been in the catalog for more than 180 days (i.e., added_date is older than 180 days). These are your "long-tail dead weight" products.
Part 4: Write a data quality query to find any order_items rows that reference a product_id not found in the products table.
Part 5 (challenge): Find products that have been ordered but have never received a review. Show the product name, total units sold, and number of distinct orders it appeared in. Order by units sold descending.
Sample solutions:
Part 1:
SELECT
p.product_id,
p.product_name,
p.category,
p.list_price
FROM products p
LEFT JOIN order_items oi ON p.product_id = oi.product_id
WHERE oi.product_id IS NULL;
Part 2:
SELECT
p.product_id,
p.product_name,
p.category,
p.list_price
FROM products p
WHERE NOT EXISTS (
SELECT 1
FROM order_items oi
WHERE oi.product_id = p.product_id
);
Part 3:
SELECT
p.product_id,
p.product_name,
p.category,
p.list_price,
p.added_date,
CURRENT_DATE - p.added_date AS days_in_catalog
FROM products p
LEFT JOIN reviews r ON p.product_id = r.product_id
WHERE r.product_id IS NULL
AND p.added_date < CURRENT_DATE - INTERVAL '180 days'
ORDER BY p.added_date;
Part 4:
SELECT
oi.item_id,
oi.order_id,
oi.product_id
FROM order_items oi
LEFT JOIN products p ON oi.product_id = p.product_id
WHERE p.product_id IS NULL;
Part 5:
SELECT
p.product_name,
SUM(oi.quantity) AS total_units_sold,
COUNT(DISTINCT oi.order_id) AS distinct_orders
FROM products p
JOIN order_items oi ON p.product_id = oi.product_id
WHERE NOT EXISTS (
SELECT 1
FROM reviews r
WHERE r.product_id = p.product_id
)
GROUP BY p.product_id, p.product_name
ORDER BY total_units_sold DESC;
The flip side of the "ON vs WHERE" insight cuts both ways. Sometimes you want the filter in WHERE, and you accidentally write it in ON, which keeps rows you wanted to exclude.
-- ❌ This does NOT filter to unmatched rows correctly
SELECT c.customer_id, c.email
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id
AND o.order_id IS NULL; -- Wrong: this is in ON, not WHERE
This JOIN condition is saying "match orders where order_id is null" — which will never match anything, so every customer gets a NULL row from orders, and no filtering occurs. Put the IS NULL check in WHERE.
If the right table has multiple matching rows per left-table row, you can accidentally count or list an entity multiple times.
-- Customer appears multiple times if they have multiple orders
SELECT c.customer_id, c.email
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.customer_id IS NULL;
-- This is fine for "no orders" case — each customer has at most one NULL row
-- But if you remove WHERE o.customer_id IS NULL, you'll see duplicates
For the absence pattern specifically, this isn't a problem — a customer with no orders only gets one NULL row in the join. But be aware that if you add other LEFT JOINs for non-absence purposes, you can still generate duplicates.
If your NOT IN query suddenly returns zero rows where you expected some, the first thing to check is whether the subquery can produce NULLs.
-- Diagnostic: check if your subquery produces NULLs
SELECT COUNT(*) AS total_rows,
COUNT(customer_id) AS non_null_rows
FROM orders;
-- If total_rows > non_null_rows, you have NULLs
Fix by adding WHERE customer_id IS NOT NULL to the subquery.
LEFT JOIN keeps all rows from the left table (the one after FROM). If you accidentally swap the table positions, you'll keep all rows from the wrong table.
-- ✅ Keep all customers, optionally match orders
FROM customers c LEFT JOIN orders o
-- ❌ Keep all orders, optionally match customers
-- (finds orders with no customer, not customers with no orders)
FROM orders o LEFT JOIN customers c
When debugging a LEFT JOIN + IS NULL that returns unexpected results, verify which table is on the left.
Tip
Use Debugging SQL Queries: How to Read Error Messages, Trace Wrong Results, and Fix Broken Joins Step by Step if you're getting unexpected results and can't identify why. Stepping through intermediate results is key.
This is particularly sneaky. Consider:
-- ❌ The o.order_date filter eliminates NULL rows before WHERE o.customer_id IS NULL
SELECT c.customer_id
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_date > '2024-01-01' -- This kills the unmatched rows!
AND o.customer_id IS NULL;
For unmatched customers, o.order_date is NULL. NULL > '2024-01-01' evaluates to UNKNOWN, which is filtered out. Zero rows returned. The fix: move o.order_date > '2024-01-01' into the ON clause, as covered in the time-windowed section above.
The core patterns for finding entities with no related records are:
The underlying idea across all three: you need a technique that preserves unmatched rows long enough for you to identify and return them. INNER JOIN discards them before you get the chance.
A few patterns to carry forward:
As your queries grow more complex, these absence-detection patterns become a building block within larger analytical queries. You might identify inactive customers and then aggregate their historical spend to prioritize who to re-engage first. You might combine absence checks with CASE expressions to segment customers into activation tiers. Or you might build a multi-step analytical query that layers these findings with current-period cohort data for a full churn analysis.
The ability to confidently find what's missing — not just what's present — separates analysts who answer surface questions from those who find the signal in the gaps.