Search code examples
sqlpostgresqlpsqlpgadmin-4

How do I see the primary key of a table? And how can I add multiple primary keys?


I have the following table: https://i.imgur.com/gWyCQxS.png

db name: testdb
table name: testtable

I purposely did not create any primary keys when creating the table because I wanted to learn how to it afterwards.

I used the following to add a primary key:

ALTER TABLE testtable
ADD PRIMARY KEY (column2);

In pgAdmin, I can see that it worked: https://i.imgur.com/3wKsOLo.png

I tried to do the same for column1 but I got this error: ERROR: multiple primary keys for table "testtable" are not allowed SQL state: 42P16

Q1: Why am I not allowed to have multiple primary keys for this table and how can I add multiple ones?

Also, without using the pgAdmin GUI, I'm trying to see what the current primary key is for testtable. I found a thread here on Stackoverflow that recommended the following code:

select OBJECT_NAME(OBJECT_ID) AS NameofConstraint
FROM sys.objects
where OBJECT_NAME(parent_object_id)='testtable'
and type_desc LIKE '%CONSTRAINT'

I get an error after executing this: ERROR: relation "sys.objects" does not exist.

Q2: How can I view all of the primary keys using psql or without using the pgAdmin GUI?


Solution

  • A1: Try to use a composite KEY like this:

    ALTER TABLE testtable
    ADD PRIMARY KEY (column1,column2);
    

    A2: (Q2: How can I view all of the primary keys using psql?)

    Something like this:

    select tc.table_schema, tc.table_name, kc.column_name
    from information_schema.table_constraints tc
      join information_schema.key_column_usage kc 
        on kc.table_name = tc.table_name and kc.table_schema = tc.table_schema and kc.constraint_name = tc.constraint_name
    where tc.constraint_type = 'PRIMARY KEY'
      and kc.ordinal_position is not null
    order by tc.table_schema,
             tc.table_name,
             kc.position_in_unique_constraint;