Jonah Katz
Jonah Katz

Reputation: 5298

SQL Where clause 'that begins with'?

In my rails application i have an SQL query tha tuses where and like to search for a query (params[:q]). How can i change it so query/:q cant be anywhere within the row, but must BEGIN with it? Here the code:

 AccountNumber.where("account_number like?", "%#{params[:q]}%")

Upvotes: 2

Views: 3176

Answers (3)

hspain
hspain

Reputation: 17568

The wildcard character '%' can be used anywhere in the query to indicated that a string of any length can be found there. Remove the first '%' to search for results that only start with the #{params[:q]} rather than contains it:

AccountNumber.where("account_number like?", "#{params[:q]}%")

Upvotes: 1

micha
micha

Reputation: 1085

Just remove the '%' at the front

like this

AccountNumber.where("account_number like?", "#{params[:q]}%")

http://en.wikipedia.org/wiki/Percent_sign

Upvotes: 1

Joe Stefanelli
Joe Stefanelli

Reputation: 135818

Remove the leading % wildcard from the string.

AccountNumber.where("account_number like?", "#{params[:q]}%")

Upvotes: 9

Related Questions