INTERSECT ALL Keeps Duplicate Matches
Compare INTERSECT and INTERSECT ALL on duplicate rows, combine them with EXCEPT ALL, and confirm multiset counts in a grouped query.
Code
CREATE TABLE yesterday (sku text NOT NULL);
CREATE TABLE today (sku text NOT NULL);
INSERT INTO yesterday VALUES ('a'), ('a'), ('b'), ('c');
INSERT INTO today VALUES ('a'), ('a'), ('a'), ('b'), ('d');
-- INTERSECT removes duplicates and returns each value once.
SELECT sku FROM yesterday
INTERSECT
SELECT sku FROM today
ORDER BY sku;
-- INTERSECT ALL keeps the smaller multiplicity of each value.
SELECT sku FROM yesterday
INTERSECT ALL
SELECT sku FROM today
ORDER BY sku;
-- EXCEPT ALL is the multiset difference: counts subtract.
SELECT sku FROM today
EXCEPT ALL
SELECT sku FROM yesterday
ORDER BY sku;
-- Count the surviving duplicates explicitly.
SELECT sku, count(*) AS copies
FROM (
SELECT sku FROM yesterday
INTERSECT ALL
SELECT sku FROM today
) AS shared
GROUP BY sku
ORDER BY sku;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with yesterday and today among the objects involved.
What the statements actually assemble: COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
Using it
Run the statement against the yesterday table.
Key statements
SELECT sku, count(*) AS copies
FROM (
SELECT sku FROM yesterday
INTERSECT ALL
SELECT sku FROM today
) AS shared
GROUP BY sku
ORDER BY sku;
SELECT sku FROM yesterday
INTERSECT ALL
SELECT sku FROM today
ORDER BY sku;
SELECT sku FROM today
EXCEPT ALL
SELECT sku FROM yesterday
ORDER BY sku;
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.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.
FAQ
- Which tables appear in this script?
- `yesterday`, `today` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.