Find The Missing IDs Problem


Description

LeetCode Problem 1613.

Table: Customers

1
2
3
4
5
6
7
8
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| customer_id   | int     |
| customer_name | varchar |
+---------------+---------+
customer_id is the primary key for this table.
Each row of this table contains the name and the id customer.

Write an SQL query to find the missing customer IDs. The missing IDs are ones that are not in the Customers table but are in the range between 1 and the maximum customer_id present in the table.

Notice that the maximum customer_id will not exceed 100.

Return the result table ordered by ids in ascending order.

The query result format is in the following example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Customers table:
+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
| 1           | Alice         |
| 4           | Bob           |
| 5           | Charlie       |
+-------------+---------------+

Result table:
+-----+
| ids |
+-----+
| 2   |
| 3   |
+-----+
The maximum customer_id present in the table is 5, so in the range [1,5], IDs 2 and 3 are missing from the table.


MySQL Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
with recursive cte (ids) as
(
    select 1 as ids
    
    union all
    
    select ids + 1 
    from cte 
    where ids < (select max(customer_id) from Customers)
)
select ids
from cte
where ids not in (select customer_id from Customers)
order by ids




Related Posts

Find The Missing IDs Problem

LeetCode 1613. Write an SQL query to find the missing...

The Most Frequently Ordered Products For Each Customer Problem

LeetCode 1596. Write an SQL query to find the most...

Sellers With No Sales Problem

LeetCode 1607. Write an SQL query to report the names...

Customer Who Visited But Did Not Make Any Transactions Problem

LeetCode 1581. Write an SQL query to find the IDs...

Bank Account Summary II Problem

LeetCode 1587. Write an SQL query to report the name...

Warehouse Manager Problem

LeetCode 1571. Write an SQL query to report how much...