I want to find the lowest missing number from two tables
For Example,
Table1 columna has 1,2,3,8
Table2 columnb has 4,10,11
I want to return 5
I have been able to get the lowest missing number from one table, i.e. 4 from Table1, but every time I try to join or compare to another table all I can manage is to get the next ‘available’ number, i.e. 12.
my sql code:
WITH MissingValues AS (
SELECT a.bidder_number + 1 AS missing_value
FROM bidder a
LEFT JOIN bidder b ON a.bidder_number + 1 = b.bidder_number
WHERE b.bidder_number IS NULL
AND a.auctionid = 1)
SELECT MIN(missing_value) AS lowest_missing_value
FROM MissingValues
WHERE missing_value NOT IN (
SELECT permanent_biddernumber FROM customer
WHERE permanent_biddernumber > 0 AND permanent_biddernumber IS NOT NULL)
;
3
Answers
numbers
CTEmin
is choosen.Fiddle
You can do this pretty simply, by using
UNION ALL
to union the two tables, then useLEAD
to check if the next value for each row is exactly one more.This results in only a single merged scan of both tables and no joins, and assuming there are indexes there will be no sorts either.
db<>fiddle
I would suggest find every missing row for each table separately and then get the min missing one on both tables
See example
Note
Above answer will return null since there is no missing row