> For the complete documentation index, see [llms.txt](https://ploegert.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ploegert.gitbook.io/til/programmy/rails/replace-an-index-with-a-unique-index.md).

# Replace An Index With A Unique Index

Indexes and uniqueness constraints often go together. In fact, in Postgres, when you create a unique constraint, an index is created under the hood to support that constraint.

What if you already have an index, but you want to turn it into a unique index? There is no way to alter or update the index to be unique. Instead, what you'll want to do is drop the index and then recreate it as a unique index.

Here's how you can do that with the Rails migration DSL:

```ruby
class ReplaceIndexWithUniqueIndex < ActiveRecord::Migration[5.2]
  disable_ddl_transaction!

  def up
    remove_index :users_roles, [:user_id, :role_id]
    add_index :users_roles, [:user_id, :role_id], unique: true, algorithm: :concurrently
  end

  def down
    remove_index :users_roles, [:user_id, :role_id]
    add_index :users_roles, [:user_id, :role_id], algorithm: :concurrently
  end
end
```

This removes the original multi-column index and then adds back in a unique index that covers the same columns. I added `disable_ddl_transactions!` so that the new index could be added concurrently.

I've also included a `down` migration that reverses the process in case a rollback is needed.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ploegert.gitbook.io/til/programmy/rails/replace-an-index-with-a-unique-index.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
