Web Development

Indexes are copies of columns of data from a database table. It makes is easily searchable and thus making it fast and efficient. In Rails an index can easily be adding via migrations with:

class AddIndexToTable < ActiveRecord::Migration
  def change
    add_index :tables, :column_id
  end
end

Unique

We can add a unique option to make the index unique:

class AddIndexToTable < ActiveRecord::Migration
  def change
    add_index :tables, :column_id, unique: true
  end
end

This, however, would not allow duplicate value for the same column.

Unique with Combination

We sometimes have join tables wherein we need to scope out combinations of ids. With this, we can add an index that references both columns:

class AddIndexToJoinTable < ActiveRecord::Migration
  def change
    add_index :join_tabes, [:column_id, :column_2_id], unique: true
  end
end

This will make sure that combinations of column_id AND column_2_id are all the time.