Is the order of columns significant in a Postgresql Primary key definition?

2

Postgresql allows you to define a primary key using a group of columns instead of one if desired, like so:

PRIMARY KEY(a_id, b_id)

But is the order of the columns in this definition significant? Is there any practical or actual difference between the above and the below:

PRIMARY KEY(b_id, a_id)

The documentation does not address this directly. It implies that the order should not be significant, and when I query the information_catalog tables I do not see anything to note the difference in parameter order.

But using the \d command on two tables using the alternate definitions and the order of the columns as described by the output does change. Apparently there is something in pg_catalog which retains the order of the primary key definition, but does this imply there is any functional difference at all between the two definitions?

Thank you

Radmilla Mustafa

Posted 2015-05-21T15:46:41.380

Reputation: 205

Have you done a simple experiment to find the answer? It isn't hard to find out for yourself. – Julian Knight – 2015-05-21T19:54:30.313

Answers

3

But is the order of the columns in this definition significant? Is there any practical or actual difference between the above and the below:

The order of columns in the PRIMARY KEY is significant in that the underlying UNIQUE b-tree index is created with the attributes in that order, and that affects index lookup efficiency. You generally want the most selective attributes first. This only affects performance, it doesn't change the meaning of queries.

There is no semantic difference, because UNIQUE (a, b) implies UNIQUE (b,a).

Craig Ringer

Posted 2015-05-21T15:46:41.380

Reputation: 2 630

1Thank you, this was exactly the type of answer I was looking for. – Radmilla Mustafa – 2015-05-26T15:06:26.907

More detail about the performance implications and how ordering relates to queries' WHERE clauses is at https://www.postgresql.org/docs/9.2/static/indexes-multicolumn.html

– mbaynton – 2017-07-18T20:12:28.463