Find the missing numbers in a given range

gaps-and-islands

Hi I have a table that has start and end columns that has the values

Start   End
9       10
11      19
29      44
45      51
56      60

Now if I give the range like 15 to 60 I need to return the values that not being covered in the above range.

The output I am expecting is – 20,21,22,23,24,25,26,27,28,52,53,54,55

How can I retrieve this?

Best Answer

In postgresql:

CREATE TABLE ranges
(n1 int,
n2 int);

INSERT INTO ranges
VALUES (9,10),(11,19),(29,44),(45,51),(56,60);

SELECT n FROM ranges
RIGHT JOIN generate_series(15,60) n
ON (n1 <= n AND n <= n2) WHERE n1 IS NULL;