Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do case-insensitive order in Rails with postgresql

People also ask

Is Postgres order by case insensitive?

No, these both are the same, just a different naming convention. As a_horse_with_no_name said, Postgres uses the collation implementation from the OS. There is no way to get the same result on both operating systems. In your case you may(I said maybe)do like this: ORDER BY lower(fieldname) .

Is like case sensitive in PostgreSQL?

Case Sensitivity Edit on GitHubString comparisons in PostgreSQL are case sensitive* (unless a case-insensitive collation were to be introduced).


result = Users.find(:all, :order => "LOWER(name)")

To take a little bit from both Brad and Frank.


Now with Rails 5.2 you probably will get a warning if using the accepted answer.

DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s): "LOWER(?) ASC".

An alternative could be relying on Arel (it's merged now into Rails):

results = User.order(User.arel_table['name'].lower.asc)
# results.to_sql == "SELECT \"users\".* FROM \"users\" ORDER BY LOWER(\"users\".\"name\") ASC" 

LanecH's answer adapted for Rails 3+ (including Rails 4 and 5):

users = User.order('LOWER(name)')

Or create a named scope you can reuse:

class User < ActiveRecord::Base
  scope :order_by_name, -> { order('LOWER(name)') }
end

users = User.order_by_name

Have you considered storing your column as citext type? It really just internalizes the call to lower() as I understand it. It would be automatic for you afterwards. If there are times you need a case sensitive search, this may not be the best idea though.


IN SQL you could use ORDER BY LOWER(columnname), no idea how to do it in Ruby. A functional index (also on LOWER(columnname) ) will help to speed things up.