How can I check if the contents of two tables are identical in PostgreSQL? I've checked this question but I couldn't find a solution: Checking whether two tables have identical content in PostgreSQL
What if
- my tables don't have a primary key?
- my tables contain duplicate rows?
- all columns are nullable (so in theory there could be rows containing only nulls)?
Maybe this scenario is not very likely, but is there a way to safely check if two tables with arbitrary content are completely identical?
This is supposed to return 0 rows if both tables contains identical rows. But a join doesn't work if columns contain null values. You need at least one ID column that doesn't contain any null values.
SELECT *
FROM table_a FULL OUTER JOIN table_b
USING (<list of columns to compare>)
WHERE a.id IS NULL
OR b.id IS NULL;
This is also supposed to return 0 rows if both tables are identical. But it doesn't work if the tables contain duplicate rows.
(TABLE a EXCEPT TABLE b)
UNION ALL
(TABLE b EXCEPT TABLE a)