How can you determine the primary key using SQL?

From SQLZoo

How can you determine the primary key using SQL?

schema:gisq

If you have access to the SQL code which created the table the primary key can be seen easily. The primary key may be specified in one of two ways:

CREATE TABLE cia (name VARCHAR(10) PRIMARY KEY,
                 population INTEGER)

or, where the primary key is composite:

CREATE TABLE casting(movieid INTEGER,
                    actorid INTEGER,
                    PRIMARY KEY (movieid, actorid)
                    )

If this is not possible then implementation specific commands may work.

SELECT conkey
 FROM pg_constraint JOIN pg_class
  ON pg_class.oid=conrelid 
WHERE contype='p'
AND relname = 'casting'
SELECT a.owner, a.table_name, b.column_name
  FROM all_constraints a, all_cons_columns b
 WHERE a.constraint_type='P'
   AND a.constraint_name=b.constraint_name
   AND a.table_name = 'CASTING'
sp_pkeys @table_name=casting
DESCRIBE casting
DataWars, Data Science Practice Projects - LogoDataWars: Practice Data Science/Analysis with +100 Real Life Projects
  • Your server today is: Laa-Laa