SQL LIKE and ILIKE in Rails ActiveRecord
Translate LIKE and ILIKE to ActiveRecord, escape user input with sanitize_sql_like, and avoid the leading wildcard index trap.
Use where("name LIKE ?", "%#{sanitize_sql_like(term)}%") for case-sensitive matching and swap LIKE for ILIKE on PostgreSQL when you want case-insensitive matching. Escape every user-supplied term with sanitize_sql_like. Placeholders stop SQL injection but do not stop % and _ from acting as wildcards. A pattern with a leading wildcard also ignores a normal btree index.
Everything below was run on ActiveRecord 8.1.1, PostgreSQL 16.15 and Ruby 3.3.6. The SQLite checks use the sqlite3 gem. The converter at SQL ILIKE to ActiveRecord handles the basic translation. This post covers what the converter output does not warn you about.
The SQL and the direct translation
SELECT * FROM users WHERE name ILIKE 'ann%';
User.where("name ILIKE ?", "ann%")
Real output from the test run:
SELECT "users".* FROM "users" WHERE (name ILIKE 'ann%')
["Ann Lee", "ANNA"]
The test table holds six rows: “Ann Lee”, “100% Cotton”, “a_b”, “axb”, “ANNA” and “Bob”. Plain LIKE 'ann%' on the same table returns [], because PostgreSQL LIKE is case-sensitive.
LIKE injection is not SQL injection
The ? placeholder quotes the value. The string stays closed. But LIKE has its own metacharacters inside the string: % matches any run of characters and _ matches exactly one.
User.where("name LIKE ?", "%#{'%'}%")
WHERE (name LIKE '%%%')
["Ann Lee", "100% Cotton", "a_b", "axb", "ANNA", "Bob"]
A user who types % gets every row. A user who types a_b gets “a_b” and also “axb”:
WHERE (name LIKE '%a_b%')
["a_b", "axb"]
GitHub described this problem in 2015 under the name LIKE injection. Their article, which I opened, frames it as a performance and denial-of-service risk more than a data leak. Its update note says Rails 4.2 added the helper described next.
Escape with sanitize_sql_like
sanitize_sql_like is a class method on every model. It puts a backslash before %, _ and the backslash itself.
q = "a_b"
User.where("name LIKE ?", "%#{User.sanitize_sql_like(q)}%")
WHERE (name LIKE '%a\_b%')
["a_b"]
More output from the run:
sanitize_sql_like('100%_x') => 100\%\_x
sanitize_sql_like with backslash => a\\b
with escape_character '!': 50!%!!
The second argument picks another escape character. The default backslash matches the PostgreSQL default for LIKE. Use the default unless your database needs something else. I did not test MySQL or any database other than PostgreSQL and SQLite.
Inside a model, call sanitize_sql_like(term) directly. Outside one, call it on the class. Do not call it on the whole pattern. Escape the term first, then add your own wildcards around it:
scope :search_name, ->(term) { where("name ILIKE ?", "#{sanitize_sql_like(term)}%") }
Case-insensitive search
You have three options on PostgreSQL. All three returned ["Ann Lee", "ANNA"] for ann% in my test.
User.where("name ILIKE ?", "ann%")
User.where("LOWER(name) LIKE ?", "ann%")
User.where(User.arel_table[:name].matches("ann%"))
WHERE (name ILIKE 'ann%')
WHERE (LOWER(name) LIKE 'ann%')
WHERE "users"."name" ILIKE 'ann%'
Arel matches produces ILIKE on PostgreSQL by default. Pass true as the third argument for case-sensitive LIKE:
User.where(User.arel_table[:name].matches("ann%", nil, true))
# WHERE "users"."name" LIKE 'ann%'
does_not_match gives NOT ILIKE. matches does not escape anything. You still call sanitize_sql_like first.
The portability trap is SQLite. ILIKE is a syntax error there:
ILIKE on SQLite: ActiveRecord::StatementInvalid: SQLite3::SQLException: near "ILIKE": syntax error
Plain LIKE ran on SQLite and matched “Ann” for ann%. I only checked ASCII input. If your test suite runs on SQLite and production runs on PostgreSQL, write LOWER(name) LIKE ? or use Arel matches. On SQLite, matches generated LIKE 'ann%' and returned “Ann Lee”.
Searching several columns
q = "%#{User.sanitize_sql_like('ann')}%"
User.where("name ILIKE :q OR email ILIKE :q", q: q)
WHERE (name ILIKE '%ann%' OR email ILIKE '%ann%')
["Ann Lee", "ANNA"]
ActiveRecord wraps the string in parentheses, as the output shows, so chained where calls stay safe.
The index trap
I loaded 200,000 rows named user1 to user200000 and ran EXPLAIN. The numbers below are planner cost estimates, not timings. The database collation here is C.UTF-8.
With only a plain btree index on name, a prefix search still scans the table:
SELECT * FROM users WHERE name LIKE 'user1999%'
Seq Scan on users (cost=0.00..3582.00 rows=20 width=14)
A plain btree index serves = but not LIKE unless the database uses the C collation. After I added an index with text_pattern_ops, the same query used it:
Index Scan using idx_name_pattern on users (cost=0.42..8.44 rows=20 width=14)
Index Cond: (((name)::text ~>=~ 'user1999'::text) AND ((name)::text ~<~ 'user199:'::text))
Three more results from the same table:
name LIKE '%1999' Seq Scan (cost=0.00..3582.00)
name ILIKE 'user1999%' Seq Scan (cost=0.00..3582.00)
name = 'user1999' Index Scan using idx_name_pattern (cost=0.42..8.44)
A leading wildcard cannot use a btree index. ILIKE with a btree on name does not use it either, even with a fixed prefix. For case-insensitive prefix search, index LOWER(name) with text_pattern_ops and query LOWER(name) LIKE ?. I tested it on the same table: Index Scan using idx_lower (cost=0.42..8.45).
For contains-style search (%term%), the pg_trgm extension is the standard answer. After I created a GIN trigram index, name ILIKE '%1999' switched to a bitmap index scan:
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_trgm ON users USING gin (name gin_trgm_ops);
Bitmap Heap Scan on users (cost=30.28..102.37 rows=20 width=0)
-> Bitmap Index Scan on idx_trgm (cost=0.00..30.27 rows=20 width=0)
Trigram indexes cost write time and disk space. Terms shorter than three characters get little help from them. Measure on your own data before you add one. Past a few hundred thousand rows, or once users type free-form phrases, consider full-text search instead of LIKE.
Blank input
An empty search term becomes %%, which matches every non-NULL row. Decide what a blank box means before you write the scope. Most apps want all rows back, so skip the filter:
scope :search_name, ->(term) {
term.present? ? where("name ILIKE ?", "#{sanitize_sql_like(term.strip)}%") : all
}
Rows where name is NULL never match a LIKE pattern, even %. If you need them, add OR name IS NULL explicitly. I inserted one NULL name in the test table: LIKE ‘%’ matched 6 of the 7 rows.
Rules to keep
- Escape user input with
sanitize_sql_like, every time. - Anchor the pattern at the start (
term%) when you control the UX. Autocomplete works fine with a prefix. - Index for the operator you use.
ILIKEandLIKEneed different indexes. - Do not assume your SQLite test database accepts
ILIKE. - Check the plan with
explainbefore you ship a search box.
Related: rails-where-clause-in-activerecord-conditions-multiple-clauses-and-or-logic, sql-case-when-in-rails-activerecord, database-indexes-existed-activerecord-ignored-them
Frequently asked questions
- How do I write SQL LIKE in ActiveRecord?
- Use where("name LIKE ?", "%#{sanitize_sql_like(term)}%"). The placeholder quotes the value and sanitize_sql_like escapes the percent and underscore wildcards.
- Does Rails have an ILIKE method?
- No dedicated one. Use where("name ILIKE ?", pattern) on PostgreSQL or Arel matches, which produced ILIKE in my test. SQLite raised a syntax error on ILIKE.
- Is a placeholder enough to stop LIKE injection?
- No. The placeholder stops SQL injection but a user who types a percent sign still matched every row in my test, and a_b also matched axb until I escaped it.
- Why does my LIKE query ignore the index?
- A leading wildcard cannot use a btree index. With a plain btree on a C.UTF-8 database even a prefix LIKE did a sequential scan until I added text_pattern_ops.
- How do I index contains-style searches?
- Use the pg_trgm extension with a GIN index using gin_trgm_ops. In my test it turned an ILIKE with a leading wildcard from a sequential scan into a bitmap index scan.
Was this article helpful?
Your feedback helps us improve our content
How We Verify Conversions
Every conversion shown on this site follows a strict verification process to ensure correctness:
- Compare results on same dataset — We run both SQL and ActiveRecord against identical test data and verify results match
-
Check generated SQL with
to_sql— We inspect the actual SQL Rails generates to catch semantic differences (INNER vs LEFT JOIN, WHERE vs ON, etc.) - Add regression tests for tricky cases — Edge cases like NOT EXISTS, anti-joins, and predicate placement are tested with multiple scenarios
- Tested on Rails 8.1.1 — All conversions verified on current Rails version to ensure compatibility
Last updated: November 28, 2026
Try These Queries in Our Converter
See the SQL examples from this article converted to ActiveRecord—and compare the SQL Rails actually generates.
Deep Dive into ActiveRecord
Raza Hussain
Full-stack developer specializing in Ruby on Rails, React, and modern JavaScript. 15+ years upgrading and maintaining production Rails apps. Led Rails 4/5 → 7 upgrades with 40% performance gains, migrated apps from Heroku to Render cutting costs by 35%, and built systems for StatusGator, CryptoZombies, and others. Available for Rails upgrades, performance work, and cloud migrations.
More on SQL to ActiveRecord
date_trunc and Group by Month in ActiveRecord
Group by month in ActiveRecord with PostgreSQL date_trunc. Tested time zone handling, key types, missing months, and what groupdate adds.
Rails ORDER BY NULLS LAST in ActiveRecord
Sort NULLs last in Rails: Arel nulls_last, the raw string trap on SQLite, an IS NULL fallback and the PostgreSQL index. Tested on Rails 8.1.1.
Rails Window Functions: ROW_NUMBER in ActiveRecord
Use ROW_NUMBER, RANK and LAG in ActiveRecord for latest-per-group and top N queries. Tested SQL and Ruby on Rails 8.1.1 and PostgreSQL 16.
Leave a Response
Responses (0)
No responses yet
Be the first to share your thoughts