Compare two tables and return missing ids in MySQL?


To compare two tables and return missing ids, you need to use a subquery. The syntax is as follows −

SELECT yourFirstTableName.yourIdColumnName FROM yourFirstTableName
WHERE NOT IN(SELECT yourSecondTableName.yourIdColumnName FROM youSecondTableName);

To understand the above syntax, let us create a table with sample fields and then we will insert records. The query to create the first table −

First_Table

mysql> create table First_Table
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (0.88 sec)

Now insert some records in the table using insert command. The query is as follows −

mysql> insert into First_Table values(1);
Query OK, 1 row affected (0.68 sec)
mysql> insert into First_Table values(2);
Query OK, 1 row affected (0.29 sec)
mysql> insert into First_Table values(3);
Query OK, 1 row affected (0.20 sec)
mysql> insert into First_Table values(4);
Query OK, 1 row affected (0.20 sec)

Display all records from the table using a select statement. The query is as follows −

mysql> select *from First_Table;

The following is the output −

+------+
| Id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+
4 rows in set (0.00 sec)

Here is the query to create the second table −

Second_Table

mysql> create table Second_Table
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (0.60 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into Second_Table values(2);
Query OK, 1 row affected (0.19 sec)
mysql> insert into Second_Table values(4);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement:
mysql> select *from Second_Table;

The following is the output −

+------+
| Id   |
+------+
|    2 |
|    4 |
+------+
2 rows in set (0.00 sec)

Here is the query to compare two tables and return missing ids −

mysql> select First_Table.Id from First_Table where
   -> First_Table.Id NOT IN(select Second_Table.Id from Second_Table);

The following is the output −

+------+
| Id   |
+------+
|    1 |
| 3 |
+------+
2 rows in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

934 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements