Difference between revisions of "How can you determine the primary key using SQL?"

From SQLZOO
Jump to: navigation, search
 
Line 31: Line 31:
 
   AND a.table_name = 'CASTING'
 
   AND a.table_name = 'CASTING'
 
</source>
 
</source>
<source lang='sql' class='def e-sqlserver'>sp_pkeys @table_name=casting
+
<source lang='sql' class='def e-mssql'>sp_pkeys @table_name=casting
 
</source>
 
</source>
 
<source lang='sql' class='def e-mysql'>DESCRIBE casting
 
<source lang='sql' class='def e-mysql'>DESCRIBE casting

Latest revision as of 17:28, 1 July 2017

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