Goal This query identifies non-inherited base tables where the primary key columns are not positioned at the very beginning of the table. Specifically, it flags tables where at least one non-primary key column precedes a primary key column in the ordinal position. Placing primary key columns first is a recognized best practice that significantly improves schema readability and comprehension. Tables created via inheritance are appropriately excluded from this check, as inherited columns automatically precede child-specific columns, which can unavoidably force primary keys out of the initial positions.
Notes For each found table the query shows the names of primary key columns with the ordinal number of the column in the table. PostgreSQL 14 added primary keys, unique constraints, and foreign keys to system catalogs. Thus the query was modified to exclude the results from the system catalog.
Type Problem detection Each row in the result could represent a flaw in the design
Reliability High Few or no false-positive results
License MIT (opens in new tab)
Data Source INFORMATION_SCHEMA+system catalog
SQL Query
WITH pk_columns AS (
    SELECT 
        target_table_oid, 
        target_schema AS table_schema, 
        target_table AS table_name, 
        a.attname AS column_name, 
        a.attnum AS ordinal_position
    FROM (
        SELECT 
            nc.nspname AS target_schema,
            c.relname AS target_table, 
            c.oid AS target_table_oid,
            unnest(o.conkey) AS target_col
        FROM pg_constraint o 
        INNER JOIN pg_class c ON c.oid = o.conrelid
        INNER JOIN pg_namespace AS nc ON nc.oid = c.relnamespace
        INNER JOIN pg_authid AS a ON nc.nspowner = a.oid
        WHERE (nc.nspname = 'public' OR rolname <> 'postgres')
          AND o.contype = 'p'
    ) t
    INNER JOIN pg_attribute a ON t.target_col = a.attnum 
        AND t.target_table_oid = a.attrelid 
        AND a.attisdropped = false
),
non_pk_columns AS (
    SELECT table_schema, table_name, column_name, ordinal_position
    FROM INFORMATION_SCHEMA.columns
    EXCEPT 
    SELECT table_schema, table_name, column_name, ordinal_position
    FROM pk_columns
)
SELECT 
    table_schema, 
    table_name,     
    string_agg(column_name || '(' || ordinal_position::text || ')', ',' ORDER BY ordinal_position) AS primary_key_columns
FROM pk_columns AS p
WHERE EXISTS (
    SELECT 1 
    FROM non_pk_columns AS n 
    WHERE p.table_schema = n.table_schema 
      AND p.table_name = n.table_name 
      AND p.ordinal_position > n.ordinal_position
)
AND NOT EXISTS (
    SELECT 1 
    FROM pg_inherits pi 
    WHERE pi.inhrelid = p.target_table_oid
)
GROUP BY table_schema, table_name
ORDER BY table_schema, table_name;

Fixing Suggestion

To resolve this issue and improve schema readability, the primary key columns should be moved to the beginning of the table. Since PostgreSQL does not support reordering columns via a simple ALTER TABLE command, you must rebuild the table. The standard approach is to create a new table with the correct column order (primary key first), migrate the existing data, drop the old table, and rename the new one. Alternatively, if rebuilding is too costly, this can be noted as technical debt for the next major schema refactoring.

Collections

This query belongs to the following collections:

Find problems about base tables

A selection of queries that return information about the data types, field sizes, default values as well as general structure of base tables. Contains all the types of queries - problem detection, software measure, and general overview

Find problems automatically

Queries, that results point to problems in the database. Each query in the collection produces an initial assessment. However, a human reviewer has the final say as to whether there is a problem or not .

NameDescription
Find problems about base tablesA selection of queries that return information about the data types, field sizes, default values as well as general structure of base tables. Contains all the types of queries - problem detection, software measure, and general overview
Find problems automaticallyQueries, that results point to problems in the database. Each query in the collection produces an initial assessment. However, a human reviewer has the final say as to whether there is a problem or not .

Categories

This query is classified under the following categories:

Comfortability of data management

Queries of this category provide information about the means that have been used to make the use or management of database more comfortable and thus, more efficient.

Inconsistencies

Queries of this catergory provide information about inconsistencies of solving the same problem in different places.

NameDescription
Comfortability of data managementQueries of this category provide information about the means that have been used to make the use or management of database more comfortable and thus, more efficient.
InconsistenciesQueries of this catergory provide information about inconsistencies of solving the same problem in different places.