How to check if there is an index on a column through Rails console?

As others have mentioned, you can use the following to check if an index on the column exists:

ActiveRecord::Base.connection.index_exists?(:table_name, :column_name)

It's worth noting, however, that this only returns true if an index exists that indexes that column and only that column. It won't return true if you're using compound indices that include your column. You can see all of the indexes for a table with

ActiveRecord::Base.connection.indexes(:table_name)

If you look at the source code for index_exists?, you'll see that internally it's using indexes to figure out whether or not your index exists. So if, like me, their logic doesn't fit your use case, you can loop through these indexes and see if one of them will work. In my case, the logic was thus:

ActiveRecord::Base.connection.indexes(:table_name).select { |i| i.columns.first == column_name.to_s}.any? 

It's also important to note, indexes does not return the index that rails automatically generates for ids, which explains why some people above were having problems with calls to index_exists?(:table_name, :id)


There is an index_exists? method on one of the ActiveRecord "connection adapters" classes.

You can use it like on of the following methods:

ActiveRecord::Migration.connection.index_exists? :images, :post_id
ActiveRecord::Base.connection.index_exists? :images, :post_id