Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more: , +
Hi,

I am passing 1000 values into select query. I am getting 300 rows , but i need to know what are all passing values ddnt have rows.

for eg.:
Table : Table1

ColA
1
2
3
...
..
..
300

select colA from Table1 where ColA in (1,2,3....1000)

I need Out as follows

ColA
301
302
...
..
..
1000
Posted
Comments
Kornfeld Eliyahu Peter 10-Aug-15 3:37am    
Search for 'NOT IN'...
itsureshuk 10-Aug-15 3:42am    
NOT IN will get rows in table only, i need passing values what are all not in table.
Kornfeld Eliyahu Peter 10-Aug-15 3:44am    
I didn't told you to switch IN with NOT IN - I suggested to you to read about the possibilities of NOT IN...

1 solution

Ok. Some confusion that I see here.

You list of (1,2,3,...,1000) does actually act as a table. If you have an actual list of numbers here (there are betters ways of generating a table like this) then use this as your select table. You will have to name the column if you wish to use it as the select

SQL
select ColA
from (
    select 1 as colA
    union select 2
    union select 3
    ...
    union select 1000)
where ColA not in(
   select t.ColA from table t)


I hope you see how awful this could be if you have to enter the sequence each time, and not in is not the most efficient method of discerning the missing values.

You can set up a tabular function that takes the list of numbers as, for example, a csv and returns a table, or you can use a Common Table Expression to set up the table on the fly. If you have a set 1 to n range then I would create this with a CTE.

The query below would be how I would do it:
SQL
DECLARE @UpperLimit int

set @UpperLimit = 1000

--CTE
    WITH mycte AS (
        SELECT 1 AS ColA
        UNION ALL SELECT ColA+ 1 FROM mycte
        WHERE ColA < @UpperLimit
    ) 
--mycte is now a table with ColA and 1-1000 as values
--CTE's are more efficient as they are evaluated in the select (below) so do not have to generate all values if there is a where clause

    SELECT m.ColA
    FROM mycte m
    WHERE NOT EXISTS (SELECT * FROM table1 t where m.ColA = t.ColA)
-- this is more efficient as the inner select does not have to perform the full query


--This might also be written with a tabular function:
   SELECT m.ColA
   FROM TableFromCSVFunction(@TheCsvNumbers) m
   WHERE NOT EXISTS (SELECT * FROM table1 t where m.ColA = t.ColA)
-- This is a lot less efficient as the whole function must complete before the select is performed



I hope that helps ^_^

Andy
 
Share this answer
 
Comments
Maciej Los 10-Aug-15 4:22am    
Well said! +5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900