Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add index with sort order?

In Rails, how can I add an index in a migration to a Postgres database with a specific sort order?

Ultimately wanting to pull off this query:

CREATE INDEX index_apps_kind_release_date_rating ON apps(kind, itunes_release_date DESC, rating_count DESC);

But right now in my migration I have this:

add_index :apps, [:kind, 'itunes_release_date desc', 'rating_count desc'], name: 'index_apps_kind_release_date_rating'

Which spits out this:

CREATE INDEX "index_apps_kind_release_date_rating" ON "apps" ("kind", "itunes_release_date desc", "rating_count desc")

Which errors out:

PG::Error: ERROR:  column "itunes_release_date desc" does not exist
like image 646
Shpigford Avatar asked Jun 03 '13 14:06

Shpigford


2 Answers

Rails now supports specifying index order in migrations:

def change
  add_index(:accounts, [:branch_id, :party_id, :surname], order: {branch_id: :desc, party_id: :asc})
end

From http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index

like image 199
nitrogen Avatar answered Sep 22 '22 06:09

nitrogen


You do not need to specify DESC in the index. It will give a small speed benefit for the queries, that use this particular ordering, but in general - an index can be used for any oredring of a column.

like image 40
Ihor Romanchenko Avatar answered Sep 22 '22 06:09

Ihor Romanchenko