Amrinder Singh
Amrinder Singh

Reputation: 5532

How to make LIKE clause case-insensitive?

I'm using a LIKE clause in Ruby On Rails. When I try to search for records by typing "more" it doesn't return anything, but when I do with "More", then it returns the records which contains More keyword, so it seems like it behaves in a case-sensitive way.

Is it possible to make this case-insensitive?

Here is the query I am using currently:

Job.where('title LIKE ? OR duration LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%")

Upvotes: 10

Views: 16021

Answers (2)

sa77
sa77

Reputation: 3603

try something like this

def query_job(query)
  job_query = "%#{query.downcase}%"
  Job.where("lower(title) LIKE ? or lower(duration) LIKE ?", job_query, job_query) 
end 

query_job(params[:search])

Upvotes: 0

Roman Kiselenko
Roman Kiselenko

Reputation: 44380

I assume you're using Postgres.

You can use ILIKE

Job.where('title ILIKE ? OR duration ILIKE ?', "%#{params[:search]}%", "%#{params[:search]}%")

Or a some tricky hack lower():

Job.where('lower(title) LIKE lower(?) OR lower(duration) LIKE lower(?)', "%#{params[:search]}%", "%#{params[:search]}%")

Upvotes: 25

Related Questions