By default, simple SELECT * FROM %table_name%
will not order results by primary key.
But you can obtain list of columns of primary key of table:
SELECT ind_column.attname AS columns_of_pk
FROM pg_class tbl
INNER JOIN pg_index ind ON ind.indrelid = tbl.oid
INNER JOIN pg_class ind_table ON ind_table.oid = ind.indexrelid
INNER JOIN pg_attribute ind_column ON ind_column.attrelid = ind_table.oid
WHERE tbl.relname = 'my_table'
AND ind.indisprimary;
And then build dynamic query with this columns in ORDER BY
clause.
Add INNER JOIN pg_namespace sch ON sch.oid = tbl.relnamespace
and WHERE
condition on sch.nspname
if you have multiple tables with the same name in different schemas.
You can obtain PK's for all tables in 1 query:
SELECT sch.nspname AS "schema"
, tbl.relname AS "table"
, array_agg(ind_column.attname) AS columns_of_pk
FROM pg_class tbl
INNER JOIN pg_namespace sch ON sch.oid = tbl.relnamespace
INNER JOIN pg_index ind ON ind.indrelid = tbl.oid
INNER JOIN pg_class ind_table ON ind_table.oid = ind.indexrelid
INNER JOIN pg_attribute ind_column ON ind_column.attrelid = ind_table.oid
WHERE sch.nspname <> 'pg_toast'
AND ind.indisprimary
GROUP BY "schema", "table";
order by
. There is no alternative. Any order you see without an order by is pure coincidence. Plus:cluster
is a one-time operation, that ordering is not maintained by Postgres.CLUSTER
on all the tables and then apg_dump
would do nearly exactly what I want, with nearly zero extra work.