Except Snapshot Row Diff
Diff two row snapshots with EXCEPT in both directions: rows only in the old load are removals, rows only in the new load are additions.
Code
CREATE TABLE import_prev (
sku text PRIMARY KEY,
price numeric NOT NULL
);
INSERT INTO import_prev (sku, price) VALUES
('tshirt', 1900),
('mug', 1200),
('coat', 4800);
CREATE TABLE import_new (
sku text PRIMARY KEY,
price numeric NOT NULL
);
INSERT INTO import_new (sku, price) VALUES
('tshirt', 1900),
('mug', 900),
('poster', 1500);
-- 旧有新无:被移除的行(EXCEPT 自带去重,集合语义)
SELECT 'removed' AS change, sku, price
FROM import_prev
EXCEPT
SELECT 'removed', sku, price
FROM import_new;
-- 新有旧无:新增或改价的行
SELECT 'added-or-changed' AS change, sku, price
FROM import_new
EXCEPT
SELECT 'added-or-changed', sku, price
FROM import_prev
ORDER BY sku;
DROP TABLE import_prev, import_new;How it works
Several statements share this file — SELECT / INSERT / CREATE, with import_prev and import_new among the objects involved.
Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Putting it to use
Run it in the import_prev database context.
Core lines
SELECT 'added-or-changed' AS change, sku, price
FROM import_new
EXCEPT
SELECT 'added-or-changed', sku, price
FROM import_prev
ORDER BY sku;
SELECT 'removed' AS change, sku, price
FROM import_prev
EXCEPT
SELECT 'removed', sku, price
FROM import_new;
INSERT INTO import_prev (sku, price) VALUES
('tshirt', 1900),
('mug', 1200),
('coat', 4800);
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 relations are involved here?
- `import_prev`, `import_new` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.