# How to compare two tables in SQL

Source: https://sqlstreak.com/sql/how-to/compare-two-tables · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**Short answer:** `SELECT … FROM a EXCEPT SELECT … FROM b` lists rows in a that aren't identical in b; swap the tables for the other direction. To see added, removed and changed rows in one result, `FULL OUTER JOIN` on the key and compare the columns.

**The task:** Find what differs between two versions of a table: rows added, removed or changed.

### Rows in the new menu that aren't in the old one

`menu_v2` is a copy of the menu with one price changed, one item gone and one added.

```sql
WITH menu_v2 AS (
  SELECT id, name, CASE WHEN id = 4 THEN 16.5 ELSE price END AS price
  FROM menu_items WHERE id <> 11
  UNION ALL
  SELECT 12, 'Calzone Comet', 12.5
)
SELECT id, name, price FROM menu_v2
EXCEPT
SELECT id, name, price FROM menu_items
ORDER BY id;
```

Result (both engines):

| id | name | price |
| --- | --- | --- |
| 4 | BBQ Meteor | 16.5 |
| 12 | Calzone Comet | 12.5 |

### Added, removed and changed in one result

```sql
WITH menu_v2 AS (
  SELECT id, name, CASE WHEN id = 4 THEN 16.5 ELSE price END AS price
  FROM menu_items WHERE id <> 11
  UNION ALL
  SELECT 12, 'Calzone Comet', 12.5
)
SELECT COALESCE(o.id, n.id) AS id,
       COALESCE(o.name, n.name) AS name,
       o.price AS old_price, n.price AS new_price,
       CASE WHEN o.id IS NULL THEN 'added'
            WHEN n.id IS NULL THEN 'removed'
            ELSE 'changed' END AS change
FROM menu_items o
FULL OUTER JOIN menu_v2 n ON n.id = o.id
WHERE o.id IS NULL OR n.id IS NULL OR o.price <> n.price OR o.name <> n.name
ORDER BY id;
```

Result (both engines):

| id | name | old_price | new_price | change |
| --- | --- | --- | --- | --- |
| 4 | BBQ Meteor | 15.5 | 16.5 | changed |
| 11 | Tiramisu | 6.5 | NULL | removed |
| 12 | Calzone Comet | NULL | 12.5 | added |

## How it works

- `EXCEPT`: Rows from the first query that don't appear, exactly, in the second.
- `FULL OUTER JOIN … ON n.id = o.id`: Every id from either version, with NULLs on the side where it's missing.
- `WHERE … OR o.price <> n.price`: Keep only the differences.

## Variations

### Are the two tables identical?

Run EXCEPT both ways; if both return no rows (and the row counts match), the tables hold the same rows.

### Columns that can be NULL

`o.x <> n.x` is unknown when either side is NULL; use `o.x IS DISTINCT FROM n.x` to catch those changes.

## Common mistakes

- EXCEPT in one direction only: you see added rows but miss removed ones.
- Comparing with `<>` on nullable columns: NULL changes slip through.
- Expecting EXCEPT to show duplicates: it removes them. Use EXCEPT ALL in PostgreSQL to compare row counts.

## PostgreSQL and SQLite

Both support EXCEPT and FULL OUTER JOIN (SQLite since 3.39); the build ran both on each engine. EXCEPT ALL is PostgreSQL-only.
