Search code examples
ruby-on-railspostgresqlruby-on-rails-5database-schema

Does the order of keys in a primary key array matter?


We've got a distributed/sharded database, so we use a combination of id and partner_id (which is our partition ID) as the primary key on any of our distributed tables.

In my schema.rb file, this declaration would look like this:

create_table "back_in_stock_subscriptions", primary_key: ["id", "partner_id"], force: :cascade do |t|

The issue that's leading to my question is that when one of my co-workers runs migrations, the schema is modified to look like this:

create_table "back_in_stock_subscriptions", primary_key: ["partner_id", "id"], force: :cascade do |t|

So any time they run migrations, they have to stage for committing just the piece that they're actually adding to the database, then discard the remaining changes to the schema.rb file. Or if they're running migrations someone else added, they just discard the schema.rb changes altogether. Granted, it's a very minor nuisance, and I have no idea why it's happening to begin with, but it is slightly concerning.

So my question is does it even matter? If he accidentally lets one of the "reversals" slip into a commit, would it be a big deal (other than that the next time I run migrations, it would reverse it back)?


Solution

  • As far as uniqueness is concerned, the order of the columns in the primary key definition does not matter.

    But a primary key is always implemented with a unique index, and that index can be used to speed up queries. For that, the order of columns can matter a lot. For example, this query:

    SELECT * FROM tab WHERE col1 = 42;
    

    can use the index for a primary key on (col1, col2), but not the index for a primary key on (col2, col1).