PostgreSQL: Compare Two Tables in PostgreSQL

CREATE TABLE foo (
   ID INT PRIMARY KEY,
   NAME VARCHAR (50)
);

CREATE TABLE bar(
   ID INT PRIMARY KEY,
   NAME VARCHAR (50)
);

INSERT INTO foo (ID, NAME)
VALUES
   (1, 'a'),
   (2, 'b');

INSERT INTO bar (ID, NAME)
VALUES
   (1, 'a'),
   (2, 'c');

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

select * from foo
except
select * from bar; -- returns row present in foo and not in bar => 2,b

select * from bar
except
select * from foo; -- returns row present in bar and not in foo => 2,c

(select * from foo
except
select * from bar)
UNION
(select * from bar
except
select * from foo); -- returns union of above two query. i.e rows which are not present in other table.

Compare two tables using OUTER JOIN

SELECT
   id,
   name
FROM
   foo
FULL OUTER JOIN bar USING (id, name)
WHERE
   foo.id IS NULL
OR bar.id IS NULL;
It returns the differences between two tables:

To find the number of rows that are in the foo table but not bar table and vice versa, just use COUNT function in select statement instead of selecting columns.

SELECT
   COUNT (*)
FROM
   foo
FULL OUTER JOIN bar USING (id, name)
WHERE
   foo.id IS NULL
OR bar.id IS NULL;

Output:
Count
2

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.