0

I have a int column in my table in a SQL database. I keep some of codes in this table. For sample range of my codes is : (1, 9).
I need to not used code in this range.

Example:
Used Codes is :

Select code from MyTable  -- result is 2,6,7,8,9

Not used codes is : 1,3,4,5

Now , how can I select this codes? Expected result is : 1,3,4,5

Ehsan
  • 3,371
  • 8
  • 46
  • 68

2 Answers2

4

Generate a list of numbers for your range (here I use VALUES clause), then semi-join to the "used" list

SELECT
    *
FROM
   (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9)) X (Num)
WHERE
   NOT EXISTS (SELECT * FROM MyTable M WHERE M.Code = X.Num)

Edit:

You can replace the VALUES clause with any number table generation code. Examples:

Community
  • 1
  • 1
gbn
  • 408,740
  • 77
  • 567
  • 659
1

IMHO you should maintain the list of valid codes in a look up table in the database and have the used codes as a foreign key field in the other table (MyTable in your post).

Assuming you have created a table to save codes with name LookUpTable that has a code id and code. In the other table, you have code id as foriegn key. Then, you can use following query:

SELECT  LOOKUPTABLE.Code 
FROM    LOOKUPTABLE LEFT JOIN FOREIGNKEYTABLE ON LOOKUPTABLE.ID = FOREIGNKEYTABLE.CodeID 
WHERE FOREIGNKEYTABLE.USERID IS NULL
danish
  • 5,436
  • 2
  • 24
  • 28