// SQL snippet

Full outer compare of two result sets

Rows with NULL on either side are the differences; everything else lines up.

Main statement
PostgreSQL
Also covers
MySQL

The task

This month's customer totals should match last month's. You want a single query listing only the customers present on one side but not the other.

The snippet

Written for PostgreSQL. Versions for MySQL are under Variations.

PostgreSQL
WITH this_month AS (
  SELECT customer_id, SUM(amount) AS total
  FROM orders
  WHERE order_date >= DATE '2026-07-01'
  GROUP BY customer_id
),
last_month AS (
  SELECT customer_id, SUM(amount) AS total
  FROM orders
  WHERE order_date >= DATE '2026-06-01'
    AND order_date <  DATE '2026-07-01'
  GROUP BY customer_id
)
SELECT COALESCE(t.customer_id, l.customer_id) AS customer_id,
       t.total AS this_month_total,
       l.total AS last_month_total
FROM this_month t
FULL OUTER JOIN last_month l ON l.customer_id = t.customer_id
WHERE t.customer_id IS NULL OR l.customer_id IS NULL
ORDER BY customer_id;

How it works

FULL OUTER JOIN keeps every customer from both sides; rows that matched show both totals and rows that did not show NULL on the missing side. The WHERE keeps only the one-sided rows, which is the difference set in both directions at once. MySQL has no FULL OUTER JOIN, so emulate it with two LEFT JOINs, one from each side, each keeping only its unmatched rows, glued with UNION ALL.

Variations

MySQL: two anti-joins glued with UNION ALL

MySQL
WITH this_month AS (
  SELECT customer_id, SUM(amount) AS total
  FROM orders
  WHERE order_date >= DATE '2026-07-01'
  GROUP BY customer_id
),
last_month AS (
  SELECT customer_id, SUM(amount) AS total
  FROM orders
  WHERE order_date >= DATE '2026-06-01'
    AND order_date <  DATE '2026-07-01'
  GROUP BY customer_id
)
SELECT t.customer_id,
       t.total AS this_month_total,
       l.total AS last_month_total
FROM this_month t
LEFT JOIN last_month l ON l.customer_id = t.customer_id
WHERE l.customer_id IS NULL
UNION ALL
SELECT l.customer_id, NULL, l.total
FROM last_month l
LEFT JOIN this_month t ON t.customer_id = l.customer_id
WHERE t.customer_id IS NULL
ORDER BY customer_id;

Questions that come up

How do I also catch rows that exist on both sides but differ in value?

Extend the WHERE: OR (t.customer_id = l.customer_id AND t.total <> l.total). The same query then lists added, removed and changed customers. If totals can be NULL, use t.total IS DISTINCT FROM l.total (PostgreSQL, SQL Server 2022+, SQLite 3.39+) or NOT (t.total <=> l.total) on MySQL.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.