rails - created_at when user for ordering, Should you add an Index to the table?

前端 未结 3 1223
萌比男神i
萌比男神i 2021-02-01 21:24

Hello for one of my models photos I have:

default_scope :order => \'photos.created_at DESC, photos.version DESC\'

Given that I\'m ordering b

3条回答
  •  无人及你
    2021-02-01 21:57

    The following is based on my PostgreSQL experience but would probably also apply for MySQL and others.

    If you plan on retrieving a large number of records from this table or making use of pagination, an index on the fields used in the ORDER BY would be useful.

    You should create an index on all order fields in the same order. If you are mixing ASC and DESC in your ORDER BY you would need to create an index with these specific orderings to take full advantage of the index.

    A suitable ActiveRecord migration for your photos table would be:

    add_index :photos, [:created_at, :version]
    

    I would recommend looking at the EXPLAIN ANALYZE output with production-like data before and after adding the index to confirm it is having the effect you are after.

提交回复
热议问题