How can I find all the tables of db that contains primary key or particular column of a single table in Postgresql Database....Means a column of a perticular table that is included in many tables either as foreign key or non - foreign key...column can be primary key or a non - primary key....
Asked
Active
Viewed 406 times
1 Answers
2
Use below Query to find particular column of a single table:
SELECT table_name
FROM information_schema.columns
WHERE table_schema = 'public'
AND column_name = 'YOUR_COLUMN_NAME'
Use below Query to find List of all the tables of db that contains primary key
SELECT t.table_catalog,
t.table_schema,
t.table_name,
kcu.constraint_name,
kcu.column_name,
kcu.ordinal_position
FROM INFORMATION_SCHEMA.TABLES t
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
ON tc.table_catalog = t.table_catalog
AND tc.table_schema = t.table_schema
AND tc.table_name = t.table_name
AND tc.constraint_type = 'PRIMARY KEY'
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
ON kcu.table_catalog = tc.table_catalog
AND kcu.table_schema = tc.table_schema
AND kcu.table_name = tc.table_name
AND kcu.constraint_name = tc.constraint_name
WHERE t.table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY t.table_catalog,
t.table_schema,
t.table_name,
kcu.constraint_name,
kcu.ordinal_position;
Use below Query to find List of table having Foreign Key in another Table
SELECT t.table_name as FK_Table, tc.constraint_name,tc.constraint_type,ccu.table_name as PK_Table
FROM INFORMATION_SCHEMA.TABLES t
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
ON tc.table_catalog = t.table_catalog
AND tc.table_schema = t.table_schema
AND tc.table_name = t.table_name
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
ON ccu.constraint_name = tc.constraint_name
/* Remove comments for check based on CONSTRAINT'name OR 'PRIMARY_KEY' name */
--and ccu.constraint_name = 'CONSTRAINT_NAME'
--and AND ccu.column_name = 'COLUMN_NAME'
WHERE t.table_schema NOT IN ('pg_catalog', 'information_schema')

Ilesh Patel
- 2,053
- 16
- 27
-
SELECT t.table_name as FK_Table, tc.constraint_name,tc.constraint_type,ccu.table_name as PK_Table FROM INFORMATION_SCHEMA.TABLES t INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON tc.table_catalog = t.table_catalog AND tc.table_schema = t.table_schema AND tc.table_name = t.table_name INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON ccu.constraint_name = tc.constraint_name AND ccu.table_name = 'YOUR_TABLE_NAME' AND ccu.column_name = 'YOUR_COLUMN_NAME' WHERE t.table_schema NOT IN ('pg_catalog', 'information_schema'); – samkit shah Apr 14 '14 at 05:55
-
This is great example, This helped me a lot. – prem30488 Aug 06 '14 at 08:49