I’ve got the following SQL code which returns the tables in my database, along with the primary key field in each table.
SELECT Keys.TABLE_NAME As 'Table Name',
Keys.COLUMN_NAME AS 'Primary Key'
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS Constraints
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS Keys
ON Constraints.TABLE_NAME = Keys.TABLE_NAME
AND Constraints.CONSTRAINT_NAME = Keys.CONSTRAINT_NAME
WHERE Constraints.CONSTRAINT_TYPE = 'PRIMARY KEY'
As it is, it only displays those tables which have a primary key. How can I modify the sql to display all tables, and those tables which do not have a primary key will display “null” in the “Primary Key” column instead?
To do this, you need to start with a list of all tables, and then join the tables using a left outer join: