Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases Reporting with SQL Ordering, Limiting and Paging Results Practice Session

Miràs Maulenov
Miràs Maulenov
1,787 Points

How to find missing values in a sequence?

There is a table that has missing id in the Playground. Is there any chance to write a query in the Playground to find the missing number (id)?

1 Answer

Steven Parker
Steven Parker
231,272 Points

To get a complete list of missing values, you could create a temporary table with an unbroken sequence to compare with. But you could identify the start (but not length) of any sequence gaps just by comparing the table with itself. For example, the "actors" table has two sequence gaps that can be revealed this way:

select a.id + 1 as gap from actors a
left join actors b on b.id = a.id + 1
where b.id is null
  and a.id < (select max(id) from actors)