LOWER() in ActiveRecord and the Functional Index Trap
Case-insensitive matching with LOWER() skips a normal index, so you need an expression index, shown with EXPLAIN on PostgreSQL.
Write where("LOWER(email) = ?", email.downcase) for a case-insensitive match, then add an expression index on lower(email). The plain index on email does not help this query. In my test, PostgreSQL ignored it and scanned all 100,000 rows until the expression index existed. Rails gives you no warning about this.
Tested with ActiveRecord 8.1.1, PostgreSQL 16.15 and Ruby 3.3.6. PostgreSQL only. The test table had 100,000 users and a regular index on email. Cost figures are planner estimates from EXPLAIN, not timings.
The SQL you start with
SELECT * FROM users WHERE LOWER(email) = 'user500@example.com'
The query in ActiveRecord
User.where("LOWER(email) = ?", "user500@example.com")
SELECT "users".* FROM "users" WHERE (LOWER(email) = 'user500@example.com')
Pass the search value already lowercased. If you write LOWER(email) = ? and hand over "User500@Example.com", nothing matches. Either lowercase in Ruby or write LOWER(email) = LOWER(?).
The Arel version quotes the column for you:
User.where(User.arel_table[:email].lower.eq("user500@example.com"))
SELECT "users".* FROM "users" WHERE LOWER("users"."email") = 'user500@example.com'
Both versions produced identical plans. The converter has a page on the related ILIKE pattern.
The trap: the normal index is not used
Here is the exact-match lookup with the plain index on email:
Index Scan using index_users_on_email on users (cost=0.42..8.44 rows=1 width=35)
Index Cond: ((email)::text = 'User500@Example.com'::text)
Now the LOWER query with the same index:
Seq Scan on users (cost=0.00..2334.00 rows=500 width=35)
Filter: (lower((email)::text) = 'user500@example.com'::text)
The index stores email values. The query asks about lower(email). Those are different values, so the planner reads every row and applies the function. The estimate is 2334 against 8.44. The gap grows with the table. Your development database with 200 rows hides it.
The fix: an expression index
class AddLowerEmailIndexToUsers < ActiveRecord::Migration[8.1]
def change
add_index :users, "lower(email)", name: "index_users_on_lower_email"
end
end
Rails accepts a string expression where you normally pass column names. Give it an explicit name. A generated name from an expression is hard to read in logs. After the index and ANALYZE:
Index Scan using index_users_on_lower_email on users (cost=0.42..8.44 rows=1 width=35)
Index Cond: (lower((email)::text) = 'user500@example.com'::text)
The cost is back to 8.44. schema.rb dumps the index as t.index "lower((email)::text)", name: "index_users_on_lower_email". Keep the migration and schema.rb in step, so a fresh database build has the index.
The expression in the query must match the expression in the index. I tested two near misses against the lower(email) index:
User.where("UPPER(email) = ?", "USER500@EXAMPLE.COM") # Seq Scan, cost 2334
User.where("email ILIKE ?", "user500@example.com") # Seq Scan, cost 2084
Both fall back to a sequential scan. UPPER is a different expression. ILIKE uses a different operator and the btree index cannot serve it. Pick one normalization, lower, and use it everywhere. Mixing ILIKE in one place and LOWER in another leaves one of them unindexed.
Prefix search with LIKE
A LOWER(email) LIKE 'user500%' query against the plain lower(email) index also ran as a sequential scan (cost 2334). I added a second index with an operator class:
add_index :users, "lower(email) text_pattern_ops", name: "index_users_on_lower_email_pattern"
The plan changed:
Index Scan using index_users_on_lower_email_pattern on users (cost=0.42..8.44 rows=10 width=35)
Index Cond: ((lower((email)::text) ~>=~ 'user500'::text) AND (lower((email)::text) ~<~ 'user501'::text))
Filter: (lower((email)::text) ~~ 'user500%'::text)
This works for prefixes only. A leading wildcard such as '%500' is not served by this index. I did not test trigram indexes. Escape user input before you put it in a LIKE pattern, because % and _ in the input act as wildcards. Use sanitize_sql_like.
ORDER BY LOWER
User.order("lower(name)").limit(2)
# ORDER BY lower(name) LIMIT 2
User.order(User.arel_table[:name].lower.asc).limit(2)
# ORDER BY LOWER("users"."name") ASC LIMIT 2
The plain string version ran without error in Rails 8.1.1. Rails accepts a function call on a column name in order. Anything more complex, such as an expression with user input, needs Arel.sql, and you must never put user input into it. An ORDER BY lower(name) over a large table sorts every row unless an index on lower(name) exists. I did not run EXPLAIN on the ordering query.
Uniqueness: the validation and the index
validates :email, uniqueness: { case_sensitive: false }
This ran:
SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER($1) LIMIT $2
Rails already writes LOWER(email) = LOWER($1). So your validation hits the same missing index and scans the table on every save, until you add lower(email). The validation is also a check followed by an insert, so two requests racing both pass. Back it with a unique expression index:
add_index :users, "lower(email)", unique: true, name: "uniq_users_lower_email"
I ran this migration step against the test table. It did not raise, and the table held no case-colliding emails. It does not clean existing duplicates for you, and the index build fails if two rows differ only by case. Find them first:
SELECT lower(email), COUNT(*) FROM users GROUP BY 1 HAVING COUNT(*) > 1
I did not run this query.
citext as an alternative
The citext extension gives you a column type with case-insensitive comparison. I tested it:
enable_extension "citext"
create_table :people do |t|
t.column :email, :citext
t.index :email
end
Person.where(email: "a@b.COM")
# SELECT "people".* FROM "people" WHERE "people"."email" = 'a@b.COM'
A row stored as A@B.com matched, and the query kept a plain where(email: ...) with an ordinary index on the column. I did not run EXPLAIN on it. The trade-off: you need the extension on every database, the column type is not a standard string, and the case rule is tied to the column, not to the query. For a new table, citext is less code. For an existing varchar column, the expression index changes no data.
Decision
| Situation | Use |
|---|---|
| Existing string column, lookups by email |
lower(email) expression index |
| Prefix search, case-insensitive |
lower(col) text_pattern_ops index |
| New table, one case rule everywhere | citext column |
| Uniqueness regardless of case | unique lower(col) index plus the validation |
Related: indexes existed and ActiveRecord ignored them, where clause conditions in ActiveRecord, generated SQL was horrific, check EXPLAIN
Frequently asked questions
- How do I do a case-insensitive where in ActiveRecord?
- Use where('LOWER(email) = ?', email.downcase). You must lowercase the value yourself or write LOWER(?) around the placeholder.
- Why is my index on email not used with LOWER(email)?
- The index stores email values, not lower(email) values. In my test the planner chose a sequential scan with estimated cost 2334 instead of an index scan at 8.44.
- How do I add an expression index in a Rails migration?
- Pass a string: add_index :users, 'lower(email)', name: 'index_users_on_lower_email'. After that the same query used an index scan.
- Does ILIKE use the lower(email) index?
- No. In my test email ILIKE fell back to a sequential scan, as did UPPER(email). Use one normalization everywhere.
- Does validates uniqueness case_sensitive false use LOWER?
- Yes. Rails ran WHERE LOWER(users.email) = LOWER($1), so it needs the same expression index. Add a unique lower(email) index to cover races.
Tested conversions for this topic
Each page shows the SQL, the ActiveRecord code, and the SQL Rails actually generated on Rails 8.1.1.
- Rails ILIKE Query in ActiveRecord Convert SQL ILIKE to Rails ActiveRecord with a bound string or Arel matches. Tested on Rails 8.1 and PostgreSQL 16, including escaping percent signs.
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: December 02, 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 Patterns
DELETE with JOIN in ActiveRecord
Delete with a join in ActiveRecord: tested SQL for delete_all, where.missing and DELETE USING on PostgreSQL, plus skipped callbacks.
UPDATE with JOIN in Rails: update_all and joins
UPDATE with JOIN in Rails on PostgreSQL: joins plus update_all, the UPDATE FROM SQL on 8.1.1, the 8.0 error and safe alternatives. Tested.
SQL INTERSECT and EXCEPT in Rails ActiveRecord
ActiveRecord has no intersect or except method. Four tested options for Rails 8.1: Arel nodes, from with raw SQL, find_by_sql and where IN rewrites.
Leave a Response
Responses (0)
No responses yet
Be the first to share your thoughts