Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
SQL

Writing SQL to Identify Customers or Entities with No Related Records: LEFT JOIN and Subquery Patterns for Finding Orphaned and Inactive Data

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.

⚡ Practitioner21 min readDec 3, 2026Updated Dec 3, 2026
Writing SQL to Identify Customers or Entities with No Related Records: LEFT JOIN and Subquery Patterns for Finding Orphaned and Inactive Data
On this page
  • Introduction
  • Prerequisites
  • The Core Problem: Why Standard JOINs Hide What You're Looking For
  • Pattern 1: LEFT JOIN with IS NULL Filter
  • A More Complete Example: Inactive Users in a SaaS Product
  • Pattern 2: NOT IN with a Subquery
  • The Critical NULL Problem with NOT IN
  • Pattern 3: NOT EXISTS with a Correlated Subquery
  • Why NOT EXISTS Handles NULLs Correctly
  • Comparing the Three Patterns
  • Time-Windowed Inactivity: "No Activity in the Last N Days"
  • Using an Aggregated Join
  • Conditional LEFT JOIN for Time-Bounded Matching
  • Orphaned Records: Finding Data Quality Problems
  • Extending to Multiple Tables: "Never Did Any of These Things"
  • Chaining LEFT JOINs
  • NOT EXISTS with Multiple Conditions
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Mistake 1: Putting the filter condition in ON instead of WHERE (accidentally)
  • Mistake 2: Joining on a non-unique key and getting multiplied rows
  • Mistake 3: NOT IN returns no rows due to hidden NULLs
  • Mistake 4: Forgetting that LEFT JOIN direction matters
  • Mistake 5: Applying a WHERE filter that eliminates NULL rows before they can be caught
  • Summary & Next Steps

Writing SQL to Identify Customers or Entities with No Related Records: LEFT JOIN and Subquery Patterns for Finding Orphaned and Inactive Data

Introduction

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:

  • Why INNER JOIN fails silently when searching for missing relationships
  • How to use LEFT JOIN with a NULL filter as the primary pattern for finding unmatched rows
  • How to write NOT IN and NOT EXISTS subquery alternatives and when each is appropriate
  • How to handle NULL pitfalls that break NOT IN queries in production data
  • How to extend these patterns to time-windowed "inactive since" queries
  • Performance tradeoffs between LEFT JOIN, NOT IN, and NOT EXISTS across different database engines

Prerequisites

This lesson assumes you're comfortable with:

  • Basic SELECT, FROM, WHERE syntax — if you need a refresher, see SQL Basics: Master SELECT, FROM, WHERE Clauses and Build Your First Queries
  • How INNER JOIN and LEFT JOIN work conceptually — SQL JOINs Explained with Real-World Examples covers this well
  • Subquery fundamentals — Understanding SQL Subqueries: Filtering and Looking Up Data with Nested SELECT Statements is a good foundation

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.


The Core Problem: Why Standard JOINs Hide What You're Looking For

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.


Pattern 1: LEFT JOIN with IS NULL Filter

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:

  1. 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.
  2. 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.

A More Complete Example: Inactive Users in a SaaS Product

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.


Pattern 2: NOT IN with a Subquery

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.

The Critical NULL Problem with NOT IN

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.


Pattern 3: NOT EXISTS with a Correlated Subquery

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.

Why NOT EXISTS Handles NULLs Correctly

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.


Comparing the Three Patterns

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.


Time-Windowed Inactivity: "No Activity in the Last N Days"

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.

Using an Aggregated Join

-- 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.

Conditional LEFT JOIN for Time-Bounded Matching

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.


Orphaned Records: Finding Data Quality Problems

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.


Extending to Multiple Tables: "Never Did Any of These Things"

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.

Chaining LEFT JOINs

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.

NOT EXISTS with Multiple Conditions

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.


Hands-On Exercise

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;

Common Mistakes & Troubleshooting

Mistake 1: Putting the filter condition in ON instead of WHERE (accidentally)

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.

Mistake 2: Joining on a non-unique key and getting multiplied rows

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.

Mistake 3: NOT IN returns no rows due to hidden NULLs

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.

Mistake 4: Forgetting that LEFT JOIN direction matters

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.

Mistake 5: Applying a WHERE filter that eliminates NULL rows before they can be caught

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.


Summary & Next Steps

The core patterns for finding entities with no related records are:

  1. LEFT JOIN + IS NULL — Most readable, works everywhere, the standard default
  2. NOT IN + IS NOT NULL guard — Intuitive syntax, but always filter NULLs from the subquery
  3. NOT EXISTS — Semantically precise, NULL-safe by design, often the best choice for correlated checks

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:

  • Move time filters to the ON clause when you want "no match in a specific period" rather than "no match ever"
  • Flip the table order to find orphaned records in child tables
  • Chain multiple LEFT JOINs when checking absence across multiple related tables
  • Index your foreign key columns — these queries hit join columns hard, and indexes make a big difference at scale

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.

Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

SQL Fundamentals

Previous

Writing SQL to Calculate Totals, Averages, and Counts Across Filtered Subsets: Combining WHERE, GROUP BY, and Aggregate Functions in One Query

Related Insights

SQLExpert

Optimizing Recursive CTEs for Large Hierarchies: Depth Limits, Cycle Detection, and Execution Plan Analysis

32 min
SQLFoundation

Writing SQL to Calculate Totals, Averages, and Counts Across Filtered Subsets: Combining WHERE, GROUP BY, and Aggregate Functions in One Query

15 min
SQLPractitioner

Writing SQL to Compare Rows Within a Partition Using LEAD and LAG: Calculating Deltas, Detecting Changes, and Handling Boundary Conditions

20 min

On this page

  • Introduction
  • Prerequisites
  • The Core Problem: Why Standard JOINs Hide What You're Looking For
  • Pattern 1: LEFT JOIN with IS NULL Filter
  • A More Complete Example: Inactive Users in a SaaS Product
  • Pattern 2: NOT IN with a Subquery
  • The Critical NULL Problem with NOT IN
  • Pattern 3: NOT EXISTS with a Correlated Subquery
  • Why NOT EXISTS Handles NULLs Correctly
  • Comparing the Three Patterns
  • Time-Windowed Inactivity: "No Activity in the Last N Days"
  • Using an Aggregated Join
  • Conditional LEFT JOIN for Time-Bounded Matching
  • Orphaned Records: Finding Data Quality Problems
  • Extending to Multiple Tables: "Never Did Any of These Things"
  • Chaining LEFT JOINs
  • NOT EXISTS with Multiple Conditions
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Mistake 1: Putting the filter condition in ON instead of WHERE (accidentally)
  • Mistake 2: Joining on a non-unique key and getting multiplied rows
  • Mistake 3: NOT IN returns no rows due to hidden NULLs
  • Mistake 4: Forgetting that LEFT JOIN direction matters
  • Mistake 5: Applying a WHERE filter that eliminates NULL rows before they can be caught
  • Summary & Next Steps