Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select values not in a certain range in a table

Tags:

sql

I have a table with an id column and hundreds of thousands of rows. I have been given a list of 1000 IDs to check other table data against. The IDs are not stored in order. The list of IDs is not in order either. When I select the table data using those ids only 990 results are returned, meaning since that list was produce, 10 of the results have changed/been removed. How can I find the 10 missing values from that range of data? This is what I'm doing at the moment:

select * from mytable
where theId in (100, 2223, 31, 43321...92199, 14000)

Returns the 990 results. Can I do something like:

select val from (1, 2, 3, 4...999, 1000) 
where val not in (
select * from mytable
where theId in (1, 2, 3, 4...999, 1000)
)

EDIT: Sorry for the confusion. I should have mentioned that the ID's aren't in any particular order and I was just using the number 1000 as an example. They're in a random order and the 1000 is just a selection from a much larger table (100,000s of rows).

like image 590
edwardmlyte Avatar asked Oct 10 '22 20:10

edwardmlyte


2 Answers

There might be case like there is no any record for those missing ids or it might be have some other id like less than 1 or greater than 1000. If table have 1000 records and you got only 990 records in your query then definately missing records have id which is less than 1 or greater than 1000. So those missing records will be come in following query :

select val from mytable where 
val not in ( select distinct theId from mytable where theId in (1, 2, 3, 4...999, 1000)) 

UPDATE :

For random ids, you can do like :

create table #temp (id int)
insert into #temp values
(501),
(1),
(21),
......
....
(4350)

SELECT t.id
FROM #temp t
LEFT OUTER JOIN mytable mt on t.id = mt.device_id
WHERE mt.id IS NULL

drop table #temp
like image 148
Upendra Chaudhari Avatar answered Oct 14 '22 01:10

Upendra Chaudhari


I would suggest something like this:

WITH cte AS
(
SELECT 1 x
UNION ALL
SELECT x + 1
FROM cte
WHERE x < 1000
)

SELECT cte.x
FROM cte
LEFT OUTER JOIN myTable s on cte.x = s.theId
WHERE s.theId IS NULL
like image 33
Rikon Avatar answered Oct 14 '22 01:10

Rikon