i Know this question asked several times in StackOverFlow. i have tried few of them but i am out of luck.
i have a MySQL table where there is a field(orders_id) which is might appear randomly in the table (Not sequentially) and i need to find out which ids are missing from the table.
orders_id product_name qty
1007 Wireless Mouse 1
1000 Laptop 1
1004 Wireless Mouse 3
1020 PC 3
1003 Wireless Mouse 4
1025 IPAD 4
1026 iphone 1
Expected Answer:
Assume orders_id start from 1000.
orders_id
1000
1001
1002
1005
1006
1008
......
i have already created above table at "SqlFiddle" , you guys can use it.
**the SQL i have tried: **
declare @id int
declare @maxid int
set @id = 1
select @maxid = max(`orders_id`) from orders
create temporary table IDSeq
(
id int
)
while @id < @maxid
begin
insert into IDSeq values(@id)
set @id = @id + 1
end
select
s.id
from
idseq s
left join orders t on
s.id = t.`orders_id`
where t.`orders_id` is null
drop table IDSeq
I have taken above SQL from the following Answer:
SQL: find missing IDs in a table
i have also tried the ANSI SQL:
SELECT a.orders_id+1 AS start, MIN(b.orders_id) - 1 AS end
FROM orders AS a, orders AS b
WHERE a.orders_id < b.orders_id
GROUP BY a.orders_id
HAVING start < MIN(b.orders_id)
Anyone has any idea?? how can i find out the missing orders id.