How to Compare Two Tables in PostgreSQL
Summary: in this tutorial, you will learn various ways to compare two tables in PostgreSQL.
There are several ways to compare the content of two tables to find the differences between them. We will show you two commonly used techniques to compare the data from two tables.
Comparing two tables using EXCEPT and UNION operators
First, create table two tables called foo
and bar
, and insert some sample data for demonstration purposes:
The foo
table has the same structure and data as the bar
table.
Next, update one row in the bar
table.
Then, find the rows in the foo
table but not in the bar
table using the following query:
Output:
We used the EXCEPT
operator that returns the rows in the foo
table but not in the bar
table. We can apply the same technique to find the rows that are in the bar
table but not in the foo
table.
Output:
Finally, use the UNION operator to combine the results of both queries to find the rows in the bar
table but not in the foo
table and vice versa:
Output:
Comparing two tables using an outer join
You can use the outer join to compare two tables as follows:
It returns the differences between the two tables:
To find the number of rows that are in the foo
table but not bar
table and vice versa, you use the COUNT function as follows:
Output:
Summary
- Use
UNION
andEXCEPT
operators or outer join to compare two tables in PostgreSQL.