← All Exercises

Find Missing Invoice Numbers with generate_series

intermediatesql~20min

Background

Billing teams reconcile issued invoices against their numbering sequence. A missing number can mean a voided document or a failed insert, so auditors need the exact gaps.

Problem

Given a PostgreSQL invoices table whose invoice_no values contain gaps, return every integer between the minimum and maximum invoice_no that has no matching row.

Input

A PostgreSQL invoices table with invoice_no integer PRIMARY KEY, customer_id integer, and issued_on date; the table may be empty.

Output

A single column missing_invoice_no listing each absent number in ascending order, or no rows when the sequence is complete.

Sample tests

Sample 1

Input: invoice_no values: 1001, 1002, 1003, 1005, 1006, 1009
Expected: 1004
1007
1008

Sample 2

Input: invoice_no values: 1, 2, 3
Expected: no rows

Your solution

Learning objective

Practice PostgreSQL set-generating functions, anti-joins with NOT EXISTS, and reasoning about empty input.