EXCEPT ALL Multiset Diff Counts
EXCEPT ALL keeps duplicate multiplicities, so a multiset difference reports how many copies of each row disappeared between two loads.
Code
CREATE TABLE scan_old (sku text, qty int);
CREATE TABLE scan_new (sku text, qty int);
INSERT INTO scan_old VALUES ('mug', 1), ('mug', 1), ('mug', 1), ('cap', 2);
INSERT INTO scan_new VALUES ('mug', 1), ('cap', 2), ('cap', 2);
-- EXCEPT ALL 保留重复次数:旧有 3 个 mug、新有 1 个,差集剩 2 条
SELECT 'vanished' AS change, sku, qty
FROM scan_old
EXCEPT ALL
SELECT 'vanished', sku, qty
FROM scan_new;
-- 反向:新增的多余份数
SELECT 'gained' AS change, sku, qty
FROM scan_new
EXCEPT ALL
SELECT 'gained', sku, qty
FROM scan_old;
-- 对照:不带 ALL 的 EXCEPT 会把重复压成一行,丢失份数信息
SELECT 'vanished-distinct' AS change, sku, qty
FROM scan_old
EXCEPT
SELECT 'vanished-distinct', sku, qty
FROM scan_new;
DROP TABLE scan_old, scan_new;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with scan_old and scan_new among the objects involved.
Applying it
Run the statement against the scan_old table.
Statements that matter
SELECT 'vanished-distinct' AS change, sku, qty
FROM scan_old
EXCEPT
SELECT 'vanished-distinct', sku, qty
FROM scan_new;
SELECT 'vanished' AS change, sku, qty
FROM scan_old
EXCEPT ALL
SELECT 'vanished', sku, qty
FROM scan_new;
SELECT 'gained' AS change, sku, qty
FROM scan_new
EXCEPT ALL
SELECT 'gained', sku, qty
FROM scan_old;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.
FAQ
- Which tables does the SQL touch?
- `scan_old`, `scan_new`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.