Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find missing table by comparing two different databases

Tags:

sql

mysql

I would like to find a missing table in a database.

I have two databases:

  1. database_1 (It contains 120 tables)
  2. database_1_backup (It contains 121 tables)

What I have done so far:

I found the list of tables in two databases by using the following sql query:

show tables;

Using the tables list, I made two text files, then compared two textfiles. That is how I found the missing table (That was a time-consuming task, so).

Is there any query available to find missing table by comparing two databases?

like image 432
MjM Avatar asked Feb 06 '26 09:02

MjM


2 Answers

You can use aggregation to find tables missing in either database:

SELECT TABLE_NAME,
       (CASE WHEN SUM(TABLE_SCHEMA = 'dbname1') = 0
             THEN 'Missing in dbname1'
             ELSE 'Missing in dbname2'
        END) as which
FROM information_schema.TABLES
WHERE TABLE_SCHEMA IN ('dbname1', 'dbname2')
GROUP BY TABLE_NAME
HAVING COUNT(*) = 1
ORDER BY TABLE_NAME;
like image 117
Gordon Linoff Avatar answered Feb 09 '26 02:02

Gordon Linoff


Querying information_schema.TABLES should give you the answer you are looking for, try this to find to missing table:

SELECT table_name     
FROM information_schema.TABLES 
WHERE table_schema = 'database_1_backup'
AND table_name NOT IN (
  SELECT table_name 
  FROM information_schema.TABLES
  WHERE table_schema = 'database_1'
);
like image 28
jpw Avatar answered Feb 09 '26 03:02

jpw