Archive for July, 2024

Missing primary keys in MySQL

Some hosting providers (like DigitalOcean’s DBaaS) are very strict about importing a database which contains missing primary keys.
So to locate where those tables are, we can run the following query:

SELECT
t.TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES AS t
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS k
ON (
t.TABLE_NAME = k.TABLE_NAME
AND k.CONSTRAINT_SCHEMA = t.TABLE_SCHEMA
AND k.constraint_name = 'PRIMARY'
)
WHERE
t.TABLE_SCHEMA NOT IN ('information_schema', 'performance_schema', 'mysql', 'sys')
AND k.constraint_name IS NULL;

From here:
https://moiseevigor.github.io/programming/2015/02/17/find-all-tables-without-primary-key-in-mysql/