Example 1
Find missing ticket numbers from 1 through 6
The CTE generates the expected numbers 1 through 6. The left join finds which expected numbers have no matching ticket row, leaving 3 and 5 as the gaps.
CREATE TABLE tickets (ticket_no INT);
INSERT INTO
tickets (ticket_no)
VALUES
(1),
(2),
(4),
(6);WITH RECURSIVE
expected (n) AS (
SELECT
1
UNION ALL
SELECT
n + 1
FROM
expected
WHERE
n < 6
)
SELECT
expected.n AS missing_ticket_no
FROM
expected
LEFT JOIN tickets ON tickets.ticket_no = expected.n
WHERE
tickets.ticket_no IS NULL
ORDER BY
expected.n;| missing_ticket_no |
|---|
| 3 |
| 5 |
CREATE TABLE tickets (ticket_no INT);
INSERT INTO
tickets (ticket_no)
VALUES
(1),
(2),
(4),
(6);WITH
expected (n) AS (
SELECT
1
UNION ALL
SELECT
n + 1
FROM
expected
WHERE
n < 6
)
SELECT
expected.n AS missing_ticket_no
FROM
expected
LEFT JOIN tickets ON tickets.ticket_no = expected.n
WHERE
tickets.ticket_no IS NULL
ORDER BY
expected.n;| missing_ticket_no |
|---|
| 3 |
| 5 |
SQL Server omits the `RECURSIVE` keyword. The generated sequence and final anti-join are otherwise the same.