0

I have a client using a PostgreSQL database. I'm new to PostgreSQL and need a little help. I need to get a list of primary and foreign keys from all the tables in the public schema. There seems to be inconsistent data in the database. I tried queries from other posts with no success. When I look at the constraints on the table I can see the primary and foreign keys. How can this same information using SQL?

table primary key properties foreign key properties

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263

1 Answers1

1

Using information_schema and restricting to public schema. NOTE: this will only display tables you have privileges on. So if you want to see everything you will need to do this as sufficiently privileged user.

SELECT
    constraint_schema,
    table_name,
    constraint_type,
    constraint_name
FROM
    information_schema.table_constraints
WHERE
    constraint_schema = 'public'
    AND constraint_type IN ('FOREIGN KEY', 'PRIMARY KEY')
ORDER BY
    table_name,
    constraint_type;
Adrian Klaver
  • 15,886
  • 2
  • 17
  • 28