Thursday, 27 May 2021

Postgresql: Get all primary keys from all the tables in DB

SELECT 

kcu.table_schema, kcu.table_name, tco.constraint_name, kcu.ordinal_position AS position, kcu.column_name AS key_column

FROM information_schema.table_constraints tco

JOIN information_schema.key_column_usage kcu 

    ON kcu.constraint_name = tco.constraint_name

    AND kcu.constraint_schema = tco.constraint_schema

    AND kcu.constraint_name = tco.constraint_name

WHERE tco.constraint_type = 'PRIMARY KEY'

ORDER BY 

kcu.table_schema, kcu.table_name, position;


Columns


table_schema - PK schema name

table_name - PK table name

constraint_name - PK constraint name

position - index of column in table (1, 2, ...). 2 or higher means key is composite (contains more than one column)

key_column - PK column name


DBT - Models

Models are where your developers spend most of their time within a dbt environment. Models are primarily written as a select statement and ...