// SQL snippet

Find tables without a primary key

A table without a primary key can hold exact duplicate rows, gives you no reliable way to target one row in an UPDATE, and slows MySQL row-based replicas, which must scan to find each changed row.

Main statement
PostgreSQL
次もカバーします
SQL Server SQLite

The task

An audit of a schema you did not build should answer one question early: which tables have nothing enforcing unique row identity.

The snippet

Written for PostgreSQL. Versions for SQL Server and SQLite are under Variations.

PostgreSQL
SELECT n.nspname AS schema_name, c.relname AS table_name,
       c.reltuples::bigint AS row_estimate
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
  AND NOT EXISTS (
        SELECT 1 FROM pg_constraint con
        WHERE con.conrelid = c.oid AND con.contype = 'p')
ORDER BY c.reltuples DESC, c.relname;

仕組み

The NOT EXISTS subquery keeps only tables that have no 'p'-type constraint in pg_constraint. relkind 'r' limits the scan to ordinary tables; add 'p' if you also want to check partitioned parents. Sorting by the row estimate puts the riskiest offenders at the top.

Variations

SQL Server

SQL Server
SELECT s.name AS schema_name, t.name AS table_name
FROM sys.tables t
JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE NOT EXISTS (
      SELECT 1 FROM sys.key_constraints kc
      WHERE kc.parent_object_id = t.object_id AND kc.type = 'PK')
ORDER BY s.name, t.name;

SQLite

SQLite
-- pk_columns = number of columns in the declared primary key
SELECT m.name AS table_name,
       COALESCE(SUM(CASE WHEN p.pk > 0 THEN 1 ELSE 0 END), 0) AS pk_columns
FROM sqlite_master m
LEFT JOIN pragma_table_info(m.name) p ON true
WHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%'
GROUP BY m.name
HAVING pk_columns = 0;

Questions that come up

Are primary-key-less tables always wrong?

No. Append-only logs that are never updated and ETL staging tables that are truncated each run can do without one. On PostgreSQL, though, a table in a logical replication publication rejects UPDATE and DELETE unless it has a primary key or a REPLICA IDENTITY set, so add a synthetic key if the table might ever be replicated.

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.