Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, does ordering by created_at need an index?

Or does Rails do something like automatically adding an index or order by id?

Rails 4.

like image 669
B Seven Avatar asked Mar 24 '15 22:03

B Seven


2 Answers

Yes, you need to add an index yourself for created_at.

You can look in your migration files and you will see that no index on created_at is defined by default.

It is OK without an index if you have only few hundred rows.

Edit:

Lets assume you have a model named Product, in order to add an index on created_at just add a new migration bundle exec rails d migration AddCreatedAtIndexToProducts and then open your newly created migration and add the index definition:

class AddCreatedAtIndexToProducts < ActiveRecord::Migration[6.0]
  def change
    add_index :products, :created_at
  end
end
like image 76
cristian Avatar answered Oct 13 '22 00:10

cristian


Rails handles adding an index on the primary key column.
As of version 4.2, rails has support for foreign key indexes (note a few gotchas)

Other than that, Rails will leave indexing for all other fields entirely up to you. So no, it won't create one on your created_at field.

Do you need one? Only if you're running in to performance issues (or see that you'll soon be running in to issues). You can handle much more than just a few hundred rows before running into issues.

Once you do feel you need one, then you should use Rails migrations to add it - you shouldn't add it yourself directly on the database.

like image 26
joshua.paling Avatar answered Oct 13 '22 00:10

joshua.paling