sqlcmd.net validated sql reference
intermediate data-quality MySQL MariaDB SQL Server PostgreSQL SQLite

Find Orphaned Child Rows

Find child rows whose foreign key value does not match any row in the parent table.

Docker-validated Not currently validation-green

List orders whose customer does not exist

Orders 101 and 103 reference existing customers, so the joined customer row is present. Orders 102 and 104 point to customer ids 9 and 8, which are missing from customers, so the parent side is NULL and those orders are flagged as orphans.

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

CREATE TABLE orders (id INT, customer_id INT, total INT);

INSERT INTO
  customers
VALUES
  (1, 'Ada'),
  (2, 'Bob');

INSERT INTO
  orders
VALUES
  (101, 1, 50),
  (102, 9, 75),
  (103, 2, 20),
  (104, 8, 40);
Shared across supported engines.
SQL
SELECT
  o.id,
  o.customer_id,
  o.total
FROM
  orders o
  LEFT JOIN customers c ON c.id = o.customer_id
WHERE
  c.id IS NULL
ORDER BY
  o.id;
Returned rows for the shared example.
idcustomer_idtotal
102975
104840

The child-to-parent audit uses the same `LEFT JOIN` and `IS NULL` pattern across engines.

Where this command helps.

  • auditing imported orders before adding a foreign key to customers
  • checking for broken references after a cleanup or migration

What the command is doing.

Orphaned rows appear when a child table stores a reference to a parent row that is missing. This can happen after imports, disabled constraints, manual deletes, or migrations that loaded tables out of order. Use a LEFT JOIN from the child table to the parent table and keep rows where the parent side is NULL. This is the child-side referential integrity audit to run before adding or re-enabling a foreign key.