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.

SqlData Integrity

Code

snippet
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

FAQ

Which tables appear in this script?
`yesterday`, `today` — referenced directly, no join needed.