tags:

views:

71

answers:

2

I've got a table which have a column describing a numeric ID, which is unique for all the rows (but it's not the primary key). The numeric ID are limited (let's say for the answer that can be from 1 up to 10)

 SELECT ID FROM TABLE;
 ID
 ---
 1
 2
 5

I've got to present to the user (via a UI) the unused values to let choosing a correct value for a new input. I know how to do it on code (it's a Grails web application), just get all the ID from database and generate a list with the ones that are not present. But I want to know if there is a way to do it directly on the SQL query.

So, that query should return

ID
---
3
4
6
7
8
9
10

The database is Oracle, but maybe there's a way to do it that work on other databases as well.

+4  A: 
SELECT  num
FROM    (
        SELECT  level AS num
        FROM    dual
        CONNECT BY
                level <= 10
        )
WHERE   num NOT IN
        (
        SELECT  id
        FROM    mytable
        )

The first subquery is a recursive query over the single-row pseudotable, dual.

It selects the records recursively until the value of pseudocolumn level reaches 10. level increases with each record.

This is a common way to generate recordsets of arbitrary length out of nothing in Oracle.

The second part just selects only those values of level (aliased as num to avoid usage of a reserved word) that are not already in your table.

@Abdullah Dogan provided another method of doing this using MINUS operator. This does the same, but is more legible.

Quassnoi
this looks better, anyhow, so i went ahead and deleted my own post. +1
David Hedlund
Great! Can you please explain a little more the code?
Khelben
+4  A: 

this might be helpful,

select level lvl from dual connect by level<=10
minus
select id from table;
Abdullah Dogan
+1 for using `MINUS`
Quassnoi