Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all primary keys which don't have an auto-increment

Tags:

mysql

How to find all primary keys in all tables in a database, which don't have an auto-increment identifier to it. We have a large amount of tables and would like to identify all tables which don't have the auto increment identifier on the primary key.

like image 358
Rpj Avatar asked Oct 21 '25 10:10

Rpj


1 Answers

You can extract this information from the information_schema.columns table

select distinct table_name
from information_schema.columns
where table_schema = 'DATABASENAME'
      and table_name not in (select table_name
                             from information_schema.columns
                             where table_schema = 'DATABASENAME'
                                   and column_key = 'PRI'
                                   and data_type = 'int'
                                   and extra = 'auto_increment')

This looks for all tables in one database having an auto_increment column and then returns the remaining tables. This also correctly detects tables with composite keys.

like image 76
Olaf Dietsche Avatar answered Oct 23 '25 01:10

Olaf Dietsche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!