sqlcmd.net validated sql reference
intermediate joins MySQL MariaDB SQL Server PostgreSQL SQLite

Find Rows With No Matching Related Row

Use a `LEFT JOIN` and filter for `NULL` on the joined table to find missing relationships.

Docker-validated Not currently validation-green

List customers who do not have any orders

Ada and Cara both have at least one order, so their joined rows contain a non-NULL o.id and are filtered out. Bob has no matching order row, so the right side stays NULL and Bob is returned.

Rows loaded before the example query runs.
Setup
CREATE TABLE customers (id INT, name VARCHAR(50));

CREATE TABLE orders (id INT, customer_id INT);

INSERT INTO
  customers (id, name)
VALUES
  (1, 'Ada'),
  (2, 'Bob'),
  (3, 'Cara');

INSERT INTO
  orders (id, customer_id)
VALUES
  (101, 1),
  (102, 1),
  (103, 3);
Shared across supported engines.
SQL
SELECT
  c.id,
  c.name
FROM
  customers c
  LEFT JOIN orders o ON o.customer_id = c.id
WHERE
  o.id IS NULL
ORDER BY
  c.id;
Returned rows for the shared example.
idname
2Bob

All engines use the same anti-join pattern: `LEFT JOIN` plus a `NULL` check on the joined table.

Where this command helps.

  • finding customers who have never placed an order
  • checking which parent records are missing expected child rows

What the command is doing.

An anti-join with LEFT JOIN is a practical way to find parent rows that have no match in a child table. The join keeps every row from the left table, and unmatched right-side columns become NULL. Filtering for those NULL right-side values returns only the rows with no related record.