dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/mysql/#29
Script #29
mysql
Data Qualityread-onlyMin Version: 5.7

Find Tables Without a Primary Key in MySQL

Lists tables that have no primary key. Such tables cause replication lag and break Group Replication/Galera.

#primary-key#replication#schema
mysql · sql
SELECT t.table_schema, t.table_name, t.engine, t.table_rows
FROM information_schema.tables t
LEFT JOIN information_schema.table_constraints c
       ON c.table_schema = t.table_schema AND c.table_name = t.table_name
      AND c.constraint_type = 'PRIMARY KEY'
WHERE t.table_type = 'BASE TABLE'
  AND t.table_schema NOT IN ('mysql','sys','information_schema','performance_schema')
  AND c.constraint_name IS NULL
ORDER BY t.table_rows DESC;
Operational Notes & Remediation Guidance

Verify in a staging environment prior to running in production. This is a read-only diagnostic query; it does not acquire exclusive locks.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 5.7).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.