Which SQL Script in Postgres to return the fields belonging to PK?

Asked

Viewed 77 times

-1

Which SQL Script in Postgres to return the fields belonging to the primary key of a specific database table ?

  • Guys I just put dicar of how to get this information, is not question.. I research a lot and only find in the stack in English.. and so I’m putting in more streamlined scripts for people who are appearing... Thank you.. ** no need to be negative...**

  • But you can ask this as a question. Ask by editing your question for example: What is the commando SQL to bring from a table in the Postgresql database which is the field configured as the primary key (primary key). What you did is valid is that you did wrong, can not be a statement but, yes a question really.

  • Ta I had asked as a question and negatively too.. I thought it had been because I had asked as a question... I will edit... Thanks

  • Gustavao is question and answer on the site, so one asks a question and can even answer it without problems. In the answer explain better also from a context, talk about the subject, etc etc etc ... !

  • References Gustavo I think that enriches also more the question and/or answers

1 answer

1

In my researches I found several ways to make this script, I want to show here a very simple way to return this data, this to help people who are starting

 select kcu.table_schema,
           kcu.table_name,
           tco.constraint_name,
           kcu.ordinal_position as position,
           kcu.column_name as key_column
    from information_schema.table_constraints tco
    join information_schema.key_column_usage kcu 
         on kcu.constraint_name = tco.constraint_name
         and kcu.constraint_schema = tco.constraint_schema
         and kcu.constraint_name = tco.constraint_name
    where tco.constraint_type = 'PRIMARY KEY' and 
           kcu.table_name = 'sua_tabela'
    order by kcu.table_schema,
             kcu.table_name,
             position;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.