Skip to content

Check optimal column order #860

Description

@subnix

In PostgreSQL, every data type has its own alignment requirements. When columns are not ordered with these alignments in mind, PostgreSQL automatically inserts padding bytes between them to maintain proper alignment. This can lead to wasted storage space and less efficient processing.

To check the alignment requirements of data types, you can run:

SELECT typalign, typlen, string_agg(typname, ', ') AS types
FROM pg_type
WHERE typtype = 'b' 
  AND typelem = 0 
  AND typnamespace = 'pg_catalog'::regnamespace 
  AND typname NOT LIKE 'reg%'
GROUP BY typalign, typlen;

Because PostgreSQL does not allow changing the column order, it is best to optimize the column order during the initial schema design to improve both storage efficiency and access performance.

Example:

CREATE TABLE unordered (
  a boolean,
  b bigint,
  c boolean,
  d bigint
);

bigint requires 8-byte alignment. PostgreSQL will insert padding bytes as follows:
a boolean → 1 byte
padding → 7 bytes
b bigint → 8 bytes
c boolean → 1 byte
padding → 7 bytes
d bigint → 8 bytes
Total: 32 bytes per row

Optimizing the column order reduces padding:

CREATE TABLE ordered (
  b bigint,
  d bigint,
  a boolean,
  c boolean
);

Here, PostgreSQL stores the row as:
b bigint → 8 bytes
d bigint → 8 bytes
a boolean → 1 byte
c boolean → 1 byte
Total: 18 bytes per row

Designing tables with awareness of type alignment can significantly improve tuple storage and memory efficiency.

References:
https://www.percona.com/blog/postgresql-column-alignment-and-padding-how-to-improve-performance-with-smarter-table-design/
https://www.cybertec-postgresql.com/en/type-alignment-padding-bytes-no-space-waste-in-postgresql/
https://docs.gitlab.com/development/database/ordering_table_columns/
https://www.postgresql.org/docs/current/catalog-pg-type.html

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions