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 data of two tables.

Compare two tables using EXCEPT and UNION operators

First, let’s create table two tables named foo and bar, and insert some sample data for the demonstration.

CREATE TABLE foo ( ID INT PRIMARY KEY, NAME VARCHAR (50) );
Code language: SQL (Structured Query Language) (sql)
INSERT INTO foo (ID, NAME) VALUES (1, 'a'), (2, 'b');
Code language: SQL (Structured Query Language) (sql)
CREATE TABLE bar ( ID INT PRIMARY KEY, NAME VARCHAR (50) );
Code language: SQL (Structured Query Language) (sql)
INSERT INTO bar (ID, NAME) VALUES (1, 'a'), (2, 'b');
Code language: SQL (Structured Query Language) (sql)

The foo table has the same structure and data as the bar table.

Next, we update one row in the bar table.

UPDATE bar SET name = 'c' WHERE id = 2;
Code language: SQL (Structured Query Language) (sql)
compare-two-tables-postgresql

Then, to find the rows in the foo table but not in the bar table, we use the following query:

SELECT ID, NAME, 'not in bar' AS note FROM foo EXCEPT SELECT ID, NAME, 'not in bar' AS note FROM bar
Code language: SQL (Structured Query Language) (sql)
postgresql compare two tables: not in bar table


We used 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.

SELECT ID, NAME, 'not in foo' AS note FROM bar EXCEPT SELECT ID, NAME, 'not in foo' AS note FROM foo
Code language: SQL (Structured Query Language) (sql)
compare two tables not in foo table


Finally, we use UNION operator to combine the result of both queries to find:

  • Rows in the bar table but not in the foo table
  • Rows in the foo table but not in the bar table.
compare two tables: result

Compare two tables using OUTER JOIN

We can use the outer join to compare two tables as follows:

SELECT id, name FROM foo FULL OUTER JOIN bar USING (id, name) WHERE foo.id IS NULL OR bar.id IS NULL;
Code language: SQL (Structured Query Language) (sql)

It returns the differences between two tables:

postgresql compare two tables differences

To find the number of rows that are in the foo table but not bar table and vice versa, we use the COUNT function as follows:

SELECT COUNT (*) FROM foo FULL OUTER JOIN bar USING (id, name) WHERE foo.id IS NULL OR bar.id IS NULL;
Code language: SQL (Structured Query Language) (sql)
number of rows differences

In this tutorial, we have shown you two ways to compare two tables in PostgreSQL.

Was this tutorial helpful ?