Sep
5
2009

List foreign keys in mysql

One interesting way of listing foreign keys is like this :

select
    concat(table_name, '.', column_name) as 'foreign key',
    concat(referenced_table_name, '.', referenced_column_name) as 'references'
from
    information_schema.key_column_usage
where
    referenced_table_name is not null;

which is found here

and gives an output like this :

+-----------------------+-------------+
| foreign key           | references  |
+-----------------------+-------------+
| orders.client_id      | clients.id  |
| line_items.order_id   | orders.id   |
| line_items.product_id | products.id |
+-----------------------+-------------+

Another way would be to :

SHOW CREATE TABLE tablename;

which displays the sql query to create the table and has the foreign key constraints too.

Apart from this phpmyadmin too shows the foreign keys on the top of a table structure.

References :
1. Mysql Docs

Popularity: 17% [?]

4 Comments + Add Comment

  • The show create table command is great.. too bad describe [table] doesn’t provide more information about keys and such.

  • Thank you, I’ve tried the first solution and it worked perfectly.

  • Thanks a lot!!! Super!!! Finally someone posted a real solution.

  • It doesn’t work. Because the referenced_table_name IS NULL. Is this a MySQL bug ?

    Can your provide the schema definition ?

Leave a comment