Chapter 14 · Lesson 2 of 4

IN, EXISTS, and the NOT IN Trap

Test whether related rows exist with IN and EXISTS subqueries, and learn why NOT IN returns nothing when the subquery contains a NULL.

Subqueries that return a list of values work with IN. This finds team members who appear in the projects table:

SELECT name
FROM team_members
WHERE id IN (SELECT member_id FROM projects)

EXISTS asks a yes/no question instead: does the inner query return at least one row? The inner query can refer to the outer row, here through m.id:

SELECT m.name
FROM team_members AS m
WHERE EXISTS (
  SELECT 1 FROM projects AS p WHERE p.member_id = m.id
)

To find members without a project, NOT IN looks natural, but it has a trap. The projects table contains a project with no member yet, so member_id is NULL in one row. x NOT IN (1, 2, NULL) can never be true, because SQL cannot rule out that x equals the unknown value. The whole query returns no rows.

NOT EXISTS does not have this problem, which makes it the safer choice for "has no match" questions:

SELECT m.name
FROM team_members AS m
WHERE NOT EXISTS (
  SELECT 1 FROM projects AS p WHERE p.member_id = m.id
)

Sample data

This lesson loads the team_members (8 rows) and projects (7 rows) tables into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for team_members, projects
CREATE OR REPLACE TABLE team_members (
    id INTEGER,
    name VARCHAR,
    team VARCHAR,
    salary INTEGER,
    hire_date DATE
  );

INSERT INTO team_members VALUES
    (1, 'Alice', 'Engineering', 120000, '2019-04-01'),
    (2, 'Bruno', 'Engineering', 95000, '2021-06-15'),
    (3, 'Chen', 'Engineering', 105000, '2020-01-10'),
    (4, 'Dara', 'Marketing', 70000, '2022-03-01'),
    (5, 'Elif', 'Marketing', 82000, '2018-09-20'),
    (6, 'Femi', 'Sales', 60000, '2023-01-05'),
    (7, 'Gita', 'Sales', 75000, '2020-11-11'),
    (8, 'Hugo', 'Support', 52000, '2021-02-01');

CREATE OR REPLACE TABLE projects (
    project_id INTEGER,
    member_id INTEGER,
    project VARCHAR
  );

INSERT INTO projects VALUES
    (1, 1, 'Search'),
    (2, 1, 'Billing'),
    (3, 3, 'Search'),
    (4, 5, 'Rebrand'),
    (5, 7, 'Q3 Push'),
    (6, 2, 'Billing'),
    (7, NULL, 'Research spike');

Practice challenge

Return the names of team members who are not assigned to any project, ordered by name. Watch out: projects contains a row with a NULL member_id.

Hint: Use WHERE NOT EXISTS (SELECT 1 FROM projects AS p WHERE p.member_id = m.id).

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Subqueries and CTEs

Nest one query inside another with subqueries, test membership with IN and EXISTS, and break long queries into named steps with WITH (common table expressions).

  1. 01 · Subqueries in WHERE
  2. 02 · IN, EXISTS, and the NOT IN Trap
  3. 03 · Common Table Expressions with WITH
  4. 04 · Correlated Subqueries

Related guides