// SQL snippet

Find candidate key columns

Compare COUNT(DISTINCT col) with COUNT(*) for each key-hopeful column; equality means the column is unique today.

Main statement
All engines

The task

You suspect order_ref or the email column could carry a unique constraint. Today's distinct counts tell you which columns are actually unique, and which just look unique in small samples.

The snippet

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

All engines
SELECT 'email' AS column_name,
       COUNT(*) AS total_rows,
       COUNT(email) AS non_null_values,
       COUNT(DISTINCT email) AS distinct_values,
       CASE WHEN COUNT(email) = COUNT(DISTINCT email)
            THEN 'unique where set'
            ELSE 'has duplicates'
       END AS verdict
FROM customers
UNION ALL
SELECT 'phone', COUNT(*), COUNT(phone), COUNT(DISTINCT phone),
       CASE WHEN COUNT(phone) = COUNT(DISTINCT phone)
            THEN 'unique where set'
            ELSE 'has duplicates'
       END
FROM customers;

Как это работает

COUNT(col) counts the non-NULL values and COUNT(DISTINCT col) the distinct ones; when they are equal, no value repeats. Comparing against COUNT(*) instead would call any column with a NULL a duplicate. If non_null_values is below total_rows the column is unique but not a primary key candidate until the NULLs are filled; a UNIQUE constraint still accepts it on every engine except SQL Server, which allows only one NULL in a unique index. The CASE turns the counts into a verdict and UNION ALL stacks the checked columns into one report. Run it before any CREATE UNIQUE INDEX: the index fails the moment a duplicate exists.

Variations

Show the duplicate rows blocking a candidate key

SELECT email, COUNT(*) AS occurrences
FROM customers
WHERE email IS NOT NULL
GROUP BY email
HAVING COUNT(*) > 1;

Check a composite candidate key

SELECT t.total_rows, d.distinct_pairs
FROM (SELECT COUNT(*) AS total_rows FROM order_items) t
CROSS JOIN (
  SELECT COUNT(*) AS distinct_pairs
  FROM (SELECT DISTINCT order_id, product_id FROM order_items) pairs
) d;

Questions that come up

The column is unique today. Is that a candidate key?

Only provisionally: uniqueness in a snapshot is a property of the data, while a key is a property of the rules. If the business guarantees the value is never reused, add the unique constraint; if not, the next load will break the index. Unique-today columns with no business rule behind them are a trap, not a key.

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.