Find the Orphaned Rows

order.customer_id and order_item.order_id were never declared as foreign keys. A migration is about to add both, and it will fail on any row pointing at something that does not exist.

List those rows, from both tables, in one result set:

  • table_name — 'order' or 'order_item'
  • row_id — the row's own id
  • missing_ref — the value it points at, which has no parent

Order by table_name, then row_id.

Report direct orphans only. An order_item whose order_id does exist is not an orphan, even if that order turns out to be one.

Expected output


table_name | row_id | missing_ref
-----------+--------+------------
order      | 12     | 99
order_item | 102    | 999
PostgreSQL

Press Run to start the SQL engine.

SensAI
Beta
Tap the mic to stop voice mode