Skip to content

Instantly share code, notes, and snippets.

@timhwang21
Created July 23, 2020 04:05
Show Gist options
  • Select an option

  • Save timhwang21/ec7e69e88025c2b5ad02009f5186ea62 to your computer and use it in GitHub Desktop.

Select an option

Save timhwang21/ec7e69e88025c2b5ad02009f5186ea62 to your computer and use it in GitHub Desktop.
Spotting missing indexes for MariaDB & MySQL
SELECT
t.TABLE_SCHEMA,
t.TABLE_NAME,
c.COLUMN_NAME,
IFNULL(
kcu.CONSTRAINT_NAME, 'Not indexed'
) AS `Index`
FROM
information_schema.TABLES t
INNER JOIN information_schema.`COLUMNS` c ON c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND c.COLUMN_NAME LIKE '%Id'
LEFT JOIN information_schema.`KEY_COLUMN_USAGE` kcu ON kcu.TABLE_SCHEMA = t.TABLE_SCHEMA
AND kcu.TABLE_NAME = t.TABLE_NAME
AND kcu.COLUMN_NAME = c.COLUMN_NAME
AND kcu.ORDINAL_POSITION = 1
WHERE
kcu.TABLE_SCHEMA IS NULL
AND t.TABLE_SCHEMA NOT IN (
'information_schema', 'performance_schema',
'mysql'
);
@chienle

chienle commented Mar 21, 2023

Copy link
Copy Markdown

Great, thank for shared!

@bfontaine

Copy link
Copy Markdown

Does it properly detect indexes automatically created by MySQL?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment