capypad
0 day streak
sql / expert
Snippet

Multi-set Difference with EXCEPT ALL

EXCEPT ALL performs a multiset difference between two result sets. Unlike EXCEPT, which removes all duplicates, EXCEPT ALL subtracts the count of values in the second set from the first. If 'Product A' appears 5 times in the first set and 2 times in the second, EXCEPT ALL will return 'Product A' 3 times.

snippet.sql
sql
1
2
3
SELECT product_id FROM inventory_2023
EXCEPT ALL
SELECT product_id FROM inventory_2024;
Breakdown
1
SELECT product_id FROM inventory_2023
Retrieves all product IDs from the first source, including duplicates.
2
EXCEPT ALL
Subtracts matching occurrences from the second set without performing a distinct operation.
3
SELECT product_id FROM inventory_2024
Retrieves the IDs from the second source that will be 'removed' from the first.