This gives the correct answer, even if there are no entries in the selected range. It also allows you to group by field to get the set of the lowest values ββby group. The SKU in this example refers to sequential numbers.
SELECT A.myType, COALESCE (MIN( A.sku) + 1, 1) AS SKU FROM ( SELECT distinct myType, sku FROM dbo.myTable AS p1 where p1.sku > 0 and p1.sku < 100 union select distinct myType, 0 as sku from dbo.myTable as t1 ) AS A LEFT OUTER JOIN ( SELECT distinct myType, sku FROM dbo.myTable AS p2 where p2.sku > 0 and p2.sku < 100 union select distinct myType, 0 as sku from dbo.myTable as t2 ) AS B ON A.myType = B.myType AND A.sku + 1 = B.sku where (B.sku IS NULL) GROUP BY A.myType
distinct does speed up the request, although union already executes distinct . As long as you have a pointer to myType and SKU, it should be instantaneous.
Obviously, you can replace 0 with the smallest and 100 with the highest allowable values.
source share