Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL get missing IDs from table

Tags:

mysql

I have this table in MySQL, for example:

ID | Name 1  | Bob 4  | Adam 6  | Someguy 

If you notice, there is no ID number (2, 3 and 5).

How can I write a query so that MySQL would answer the missing IDs only, in this case: "2,3,5" ?

like image 678
Reacen Avatar asked Sep 07 '12 20:09

Reacen


People also ask

How can I get missing ID in mysql?

SELECT t1. id+1 AS 'Missing From', MIN(t2.id) - 1 AS 'To' FROM table AS t1, table AS t2 WHERE t1.id < t2.id GROUP BY t1.id HAVING t1.id < MIN(t2.id) - 1; This query gives the following result. Using this dataset we can figure out where the gaps in the data are and perhaps do something with them.

What is id in mysql?

Authentication ID Each row in the mysql. user table is identified by a user and host tuple. This tuple is the authorization ID. A client can authenticate with an authorization ID and a password. The ID is then referred to as a user or user name.


2 Answers

SELECT a.id+1 AS start, MIN(b.id) - 1 AS end     FROM testtable AS a, testtable AS b     WHERE a.id < b.id     GROUP BY a.id     HAVING start < MIN(b.id) 

Hope this link also helps http://www.codediesel.com/mysql/sequence-gaps-in-mysql/

like image 178
hagensoft Avatar answered Oct 20 '22 03:10

hagensoft


A more efficent query:

SELECT (t1.id + 1) as gap_starts_at,         (SELECT MIN(t3.id) -1 FROM my_table t3 WHERE t3.id > t1.id) as gap_ends_at FROM my_table t1 WHERE NOT EXISTS (SELECT t2.id FROM my_table t2 WHERE t2.id = t1.id + 1) HAVING gap_ends_at IS NOT NULL 
like image 22
Iván Pérez Avatar answered Oct 20 '22 05:10

Iván Pérez