1

I'm using UUID as primary key in my tables, created in this way:

Migration:

class CreateAccounts < ActiveRecord::Migration
  def change
    create_table :accounts, :id => false do |t|
      t.uuid :uuid, :null => false
      t.timestamps
    end
    execute "ALTER TABLE accounts ADD PRIMARY KEY (uuid);"
    add_index :accounts, :uuid, :unique => true
  end
end

Model:

class Account < ActiveRecord::Base  
    primary_key = :uuid
    base.default_value_for(:uuid, :allows_nil => false) { UUIDTools::UUID.random_create.to_s }
end

But I now see that I have double indexes on the primary key UUID column:

Double indexes on the primary key

(1) I guess this comes from ADD PRIMARY KEY which creates the "XXX_pkey" index, and I can safely remove add_index :accounts, :uuid, :unique => true in this migration and from the running database?

(2) I can see that only the manually added index is used, and not the automatically added. Is this by random?

(3) Which of these indexes should be removed and what is the best way to do that in production through Rails' migrations?

0

2 Answers 2

1

A column defined as the primary key is (by definition) unique. PostgreSQL (actually every DBMS) will automatically create an unique index to ensure this.

So there is no need need to create an additional unique index manually.

So you should remove the one that you created manually (I don't know Ruby, in plain SQL this would as easy as drop index ...)

Sign up to request clarification or add additional context in comments.

Comments

1

They are not primary indexes, how have one index primary (added by execute) and one unique (added by add_index). There is a difference between primary key and unique index. Primary key does not accept NULL where unique does.. If you need to remove the index just create a migration which will remove the index:

remove_index(table_name, :column => column_name): Removes the index specified by column_name.

Source: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.