Is there a way using SQL to list all foreign keys for a given table? I know the table name / schema and I can plug that in.
|
You can do this via the information_schema tables. For example:
|
|||||||||||||||||
|
Ollyc's answer is good as it is not Postgres-specific, however, it breaks down when the foreign key references more than one column. The following query works for arbitrary number of columns but it relies heavily on Postgres extensions:
|
|||||||||||||
|
psql does this, and if you start psql with:
it will show you exactly what query is executed. In the case of finding foreign keys, it's:
In this case, 16485 is the oid of the table I'm looking at - you can get that one by just casting your tablename to regclass like:
Schema-qualify the table name if it's not unique (or the first in your
|
|||||||||
|
You can use the PostgreSQL system catalogs. Maybe you can query pg_constraint to ask for foreign keys. You can also use the Information Schema |
|||
|
Extension to ollyc recipe :
|
|||||
|
This query works correct with composite keys also:
|
|||||
|
Use the name of the Primary Key to which the Keys are referencing and query the information_schema:
Here 'TABLE_NAME_pkey' is the name of the Primary Key referenced by the Foreign Keys. |
|||
|
check the ff post for your solution and don't forget to mark this when you fine this helpful http://errorbank.blogspot.com/2011/03/list-all-foreign-keys-references-for.html |
|||||||||
|
|
||||
|
I think what you were looking for and very close to what @ollyc wrote is this:
This will list all the tables that use your specified table as a foreign key |
|||
|
I wrote a solution that like and use frequently. The code is at http://code.google.com/p/pgutils/. See the pgutils.foreign_keys view. Unfortunately, the output is too wordy to include here. However, you can try it on a public version of the database here, like this:
This works with 8.3 at least. I anticipate updating it, if needed, in the next few months. -Reece |
||||
|
I created little tool to query and then compare database schema: Dump PostgreSQL db schema to text There is info about FK, but ollyc response gives more details. |
|||
|