Blog ❯ Author: Fabio Moschini|Date: 13.10.2022
Comparing database structures
DatabaseSql

How to Compare Database Structures
In the previous article, we saw how to use INFORMATION_SCHEMA to get information about a database's metadata.Now we'll see how to use this tool to compare the structures of two databases with the goal of highlighting the differences between them.
JOIN: Quick Review
Through the use of JOINs, it's possible to read correlated data between two or more tables.JOIN conditions tell the SQL engine how to read rows from one table based on the data present in the rows of another table and are expressed through SQL commands:
- INNER JOIN: selects and relates rows from two tables for which there is a match of values in the columns indicated for correlation:![alt text for image]()
- LEFT OUTER JOIN (LEFT JOIN): selects all rows from the first table (the left one) with the rows from the second table (the right one) that satisfy the join condition. Rows from the first table without a match in the second are extended with null values:![alt text for image]()
- RIGHT OUTER JOIN (RIGHT JOIN): works symmetrically to LEFT OUTER JOIN, meaning it selects all rows from the second table (the right one) with the rows from the first table (the left one) that satisfy the join condition. Rows from the second table without a match in the first are extended with null values:![alt text for image]()
- FULL OUTER JOIN (FULL JOIN): selects all rows from both the first and second tables, obtained with LEFT OUTER JOIN and RIGHT OUTER JOIN:![alt text for image]()
Which JOIN to Use for Our Objective?
Through the FULL OUTER JOIN operation (equivalent to FULL JOIN) we can determine the tables defined only in one of the two databases.To do this, it's sufficient to apply this type of JOIN to the tables DB_Source.INFORMATION_SCHEMA.TABLES and DB_Target.INFORMATION_SCHEMA.TABLES, where DB_Source and DB_Target are the two databases to analyze:
The query result is:

Similarly, we can determine differences at the column level as well:
This script highlights the columns defined only in one of the two databases. All columns belonging to tables present only in one database are also listed. The query result is:

Using the same technique, it's possible to determine differences also regarding other types of entities defined on a database, such as integrity constraints, indexes, primary keys, stored procedures or functions, triggers.



