Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at Unwanted.cloud

RSS Latest posts from my personal blog


Most viewed posts


Subscribe to RSS feed


Finding MySQL tables that do not have a PRIMARY key

Stanislav KhromovStanislav Khromov

Some web hosts (such ad DigitalOcean managed databases) are now enforcing that all tables should have a primary key, as lack of a primary key on a table causes performance and replication issues.

To check if any of your tables lack a primary key, you can run the SQL query below. Ideally this query should return an empty result set.

USE INFORMATION_SCHEMA;
SELECT 
    TABLES.table_name
FROM TABLES
LEFT JOIN KEY_COLUMN_USAGE AS c 
ON (
       TABLES.TABLE_NAME = c.TABLE_NAME
   AND c.CONSTRAINT_SCHEMA = TABLES.TABLE_SCHEMA
   AND c.constraint_name = 'PRIMARY'
)
WHERE 
    TABLES.table_schema <> 'information_schema'
AND TABLES.table_schema <> 'performance_schema'
AND TABLES.table_schema <> 'mysql'
AND c.constraint_name IS NULL;

Source / further reading

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 0
There are currently no comments.