Rails ILIKE Query in ActiveRecord
Use where("name ILIKE ?", "%an%") on PostgreSQL. A bound placeholder keeps user input safe. Arel gives you a version that works on other databases too.
Tested on Rails 8.1.1 and PostgreSQL 16, . Every example below ran, and the generated SQL is the SQL Rails sent.
The conversion
SQL
SELECT * FROM users WHERE name ILIKE '%an%'
ActiveRecord
User.where("name ILIKE ?", "%an%")
SQL that Rails 8.1.1 generates
SELECT "users".* FROM "users" WHERE (name ILIKE $1)
A cleaner alternative
User.where(User.arel_table[:name].matches("%an%"))
Arel matches generates ILIKE on PostgreSQL and LIKE on MySQL and SQLite, so the same Ruby runs on all three. Pass true as the third argument for a case-sensitive LIKE.
Related form
SELECT * FROM users WHERE name ILIKE '%an%'
User.where(User.arel_table[:name].matches("%an%"))
What goes wrong
Escape user input
A search box value such as 50% contains LIKE wildcards. Wrap it with ActiveRecord::Base.sanitize_sql_like before you add the % signs. It turns 50% into 50\%.
A leading wildcard skips normal indexes
ILIKE '%an%' cannot use a btree index. Add a pg_trgm GIN index when the table is large.
ILIKE only exists on PostgreSQL
MySQL compares text case-insensitively by default under common collations. SQLite LIKE is case-insensitive for ASCII. Use Arel matches if the app must run on more than one database.
Convert your own ILIKE query
Paste your SQL and press Convert. Always run .to_sql on the result and compare it with your original.
Questions
How do I do a case-insensitive search in Rails?
On PostgreSQL use where("name ILIKE ?", "%term%"), or User.arel_table[:name].matches("%term%") to stay database-neutral.
Does Arel matches use ILIKE?
On PostgreSQL, yes. The default is case-insensitive, and the adapter emits ILIKE. Other databases get LIKE.
How do I escape % in a Rails LIKE query?
Call ActiveRecord::Base.sanitize_sql_like(term) and add the wildcards around the result.
Related conversions
Rails WHERE IN Clause in ActiveRecord
Convert SQL IN and NOT IN to Rails ActiveRecord with where(id: [..]) and where.not. Tested on Rails 8.1, including empty arrays and NULL values.
Rails CASE WHEN in ActiveRecord
Convert SQL CASE WHEN to Rails ActiveRecord with select, Arel.sql and Arel::Nodes::Case. Tested on Rails 8.1, including the order and pluck errors.
ActiveRecord Subquery in Rails
Convert a SQL IN (SELECT ...) subquery to Rails ActiveRecord with where(id: relation.select). Tested on Rails 8.1, with the NOT IN NULL trap explained.
All SQL converters
Every tested SQL to ActiveRecord conversion on this site.
Safe conversion guide
How to check that a converted query returns the same rows.