How to list table foreign keys
To list all foreign keys stored in a database, we will traverse the information_schema. Here's a SQL Server example outlining the process:
Congratulations! You've just received a parcel carrying some fancy details, namely foreign key names, parent tables and columns, and referenced tables and columns.
Diving deeper
Different RDBMS have their own quirks when dealing with foreign keys. Here are some situation-specific examples:
PostgreSQL synthesis
In PostgreSQL, tap into pg_catalog
for some hidden gems:
PS: It's "ley" not "lie" in "foreign_key"!
MySQL magnifying glass
MySQL users aren't left out either:
SQLite sleuthing
For SQLite, PRAGMA is your best bet:
Examining multicolumn foreign key
Multicolumn foreign keys pose an interesting challenge. Below is a PostgreSQL solution:
Advanced goodies
Shortcut to foreign keys
Aggregated data improves efficiency. In PostgreSQL, a view for quick access with SQL looks like:
Handling name conflicts
Fully qualified names are your best friends when names get confusing in PostgreSQL.
Unleashing Postgres extensions
For serious advanced querying capabilities, consider exploring Postgres extensions like adminpack
.
Was this article helpful?