cdub cdub - 1 month ago 5
SQL Question

A script to test existence of primary keys

Trying to figure out a SQL script to test the existence of primary keys in cerain tables. If the table has no primary key, then the script should output the table name.

Tables to test:
TableA
TableB
TableC


After running the script (and lets say TableA and TableC have PKs, but not TableB), then the output would be below:

NoKeys
TableB

Answer
;WITH tables_with_pk AS (
  SELECT t.table_schema, t.table_name  
  FROM INFORMATION_SCHEMA.TABLES t 
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
      ON t.TABLE_NAME = tc.TABLE_NAME AND t.table_schema = tc.table_schema
  WHERE tc.constraint_type = 'PRIMARY KEY'
)
SELECT t.table_schema, t.table_name 
FROM INFORMATION_SCHEMA.TABLES t 
EXCEPT
SELECT table_schema, table_name
FROM tables_with_pk
Comments