// SQL snippet

Find duplicate rows across all columns

A table without a primary key or an import that ran twice can hold byte-for-byte identical rows. This recipe surfaces each distinct row that appears more than once, with its copy count.

Main statement
All engines

The task

imported_orders landed without a key and the ETL may have loaded the same file twice. Before you can dedupe or add a primary key you need to know which rows repeat and how often.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT customer_id, order_date, status, total, COUNT(*) AS copies
FROM imported_orders
GROUP BY customer_id, order_date, status, total
HAVING COUNT(*) > 1
ORDER BY copies DESC;

So funktioniert es

GROUP BY over every column collapses identical rows into one group; HAVING COUNT(*) > 1 keeps only the groups that repeated, and the ORDER BY puts the worst offenders first. GROUP BY treats NULLs as equal, so two rows that both have a NULL status still count as copies, which is what a dedupe wants. What counts as identical text depends on collation: MySQL's and SQL Server's default collations are case-insensitive, and SQL Server also ignores trailing spaces, so those engines can report more copies than PostgreSQL, SQLite or Oracle on the same data.

Variations

Count total wasted rows

SELECT COALESCE(SUM(copies - 1), 0) AS surplus_rows
FROM (
  SELECT customer_id, order_date, status, total, COUNT(*) AS copies
  FROM imported_orders
  GROUP BY customer_id, order_date, status, total
  HAVING COUNT(*) > 1
) dupes;

Keep one copy in a result set

SELECT DISTINCT customer_id, order_date, status, total
FROM imported_orders;

Questions that come up

Why not just GROUP BY the primary key?

A primary key is unique by definition, so grouping by it can never reveal duplicates. This recipe is for tables that lack a key, or for the non-key columns that should have been unique together. Once you confirm the shape of the duplicates, add a key so it cannot happen again.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.