Rails ORDER BY NULLS LAST in ActiveRecord
NULL rows sort differently on PostgreSQL and SQLite. Tested Arel, raw SQL and index options on Rails 8.1.1.
To get ORDER BY due_at DESC NULLS LAST in ActiveRecord, use Arel: Task.order(Task.arel_table[:due_at].desc.nulls_last). On PostgreSQL you can also pass the raw string "due_at DESC NULLS LAST". On SQLite that string raises UnknownAttributeReference unless you wrap it in Arel.sql. All of this was tested on ActiveRecord 8.1.1 with PostgreSQL 16.15 and SQLite.
The reason you need it: order(due_at: :desc) does not put NULL rows where you expect on every database. PostgreSQL treats NULL as larger than any value, so a descending sort puts the empty rows on top. SQLite treats NULL as smaller than any value, so the same Rails code gives the opposite result.
If you have this SQL in front of you, paste it into the SQL to ActiveRecord converter first. The rest of this post explains what to do with the NULL part.
The problem: the same Rails line, two different orders
The test table has five tasks. Two have no due date.
create_table :tasks do |t|
t.string :title
t.datetime :due_at
end
# A: Dec 1, B: NULL, C: Dec 3, D: NULL, E: Dec 2
Now sort by due date, newest first:
Task.order(due_at: :desc).pluck(:title)
The SQL is the same on both databases:
SELECT "tasks".* FROM "tasks" ORDER BY "tasks"."due_at" DESC
The result is not:
| Database | Result | Where NULL rows land |
|---|---|---|
| PostgreSQL 16.15 | B D C E A | first |
| SQLite | C E A B D | last |
The ascending sort flips the same way. PostgreSQL returned A E C B D (NULL last). SQLite returned B D A E C (NULL first). If you develop on SQLite and deploy on PostgreSQL, your “tasks due soonest” screen changes order in production and no test fails.
Fix 1: Arel nulls_first and nulls_last
Arel ordering nodes have nulls_first and nulls_last. They produce the standard SQL syntax.
Task.order(Task.arel_table[:due_at].desc.nulls_last)
SELECT "tasks".* FROM "tasks"
ORDER BY "tasks"."due_at" DESC NULLS LAST
Result on both PostgreSQL and SQLite: C E A B D. The dated rows come first, newest to oldest, and the two empty rows come last.
nulls_first works the same way. Task.arel_table[:due_at].asc.nulls_first returned B D A E C on both databases.
The BigBinary write-up “Rails 6.1 adds nulls_first and nulls_last to Arel” covers when this was added. SQLite itself only understands NULLS FIRST and NULLS LAST from version 3.30.0 (see the SQLite 3.30.0 release log), so very old SQLite builds will fail on this SQL.
Fix 2: a raw string, with one trap
PostgreSQL accepts the string form:
Task.order("due_at DESC NULLS LAST")
SELECT "tasks".* FROM "tasks" ORDER BY due_at DESC NULLS LAST
On SQLite the same line raised this in my test:
ActiveRecord::UnknownAttributeReference: Dangerous query method
(method whose arguments are used as raw SQL) called with
non-attribute argument(s): "due_at DESC NULLS LAST"
Rails checks raw order strings against a pattern for each adapter. The PostgreSQL pattern allows the NULLS suffix. The SQLite one did not in 8.1.1. Wrapping the string in Arel.sql works on both:
Task.order(Arel.sql("due_at DESC NULLS LAST"))
Only pass strings you wrote yourself to Arel.sql. Never pass a request parameter to it. If the sort column comes from the user, map it through a hash of allowed columns and use the Arel form.
Fix 3: the portable version for databases without NULLS LAST
Not every database supports the NULLS LAST syntax. The older trick sorts on IS NULL first. A boolean sorts false before true, so non-null rows come first.
t = Task.arel_table
Task.order(t[:due_at].eq(nil), t[:due_at].desc, t[:id])
SELECT "tasks".* FROM "tasks"
ORDER BY "tasks"."due_at" IS NULL, "tasks"."due_at" DESC, "tasks"."id"
Result on PostgreSQL and SQLite: C E A B D. I did not test MySQL for this post, so check it on your own version before relying on it.
Add a tie-breaker, especially with pagination
All the NULL rows tie with each other. Without a second sort key, the database may return them in a different order on each page. Add the primary key last:
Task.order(Task.arel_table[:due_at].desc.nulls_last, Task.arel_table[:id].asc)
.limit(20).offset(40)
SELECT "tasks".* FROM "tasks"
ORDER BY "tasks"."due_at" DESC NULLS LAST, "tasks"."id" ASC
LIMIT 20 OFFSET 40
Without id, B and D in the test data have no guaranteed order between them.
NULLS LAST and indexes in PostgreSQL
The sort direction and the NULL position both have to match your index, or PostgreSQL falls back to a sort. I loaded 20,000 rows with a plain index on due_at and compared plans.
With ORDER BY due_at ASC NULLS LAST LIMIT 10, the plan was a cheap index scan:
Limit (cost=0.29..0.62 rows=10 width=22)
-> Index Scan using idx_due on tasks (cost=0.29..659.45 rows=20005 width=22)
With ORDER BY due_at DESC NULLS LAST LIMIT 10 and the same plain index, the planner chose a full scan and a sort:
Limit (cost=760.35..760.38 rows=10 width=22)
-> Sort (cost=760.35..810.36 rows=20005 width=22)
Sort Key: due_at DESC NULLS LAST
-> Seq Scan on tasks (cost=0.00..328.05 rows=20005 width=22)
A default PostgreSQL index is ASC NULLS LAST. A descending scan of it gives DESC NULLS FIRST, so DESC NULLS LAST does not match. The fix is an index that spells out the order. In a migration:
add_index :tasks, :due_at,
order: { due_at: "DESC NULLS LAST" },
name: "idx_tasks_due_at_desc_nulls_last"
After I created the equivalent index, the plan went back to Index Scan using idx_due_desc_last with cost 0.29..0.62. These are planner estimates on a small test table, not timings. Run EXPLAIN on your own data before adding an index.
When to use which
Use the Arel form by default. It generates the same SQL on PostgreSQL and SQLite and passes Rails’ raw SQL check without a wrapper. Use Arel.sql for fixed strings you control. Use the IS NULL form only if your database lacks NULLS LAST.
Related: DISTINCT and the ORDER BY error, window functions and ROW_NUMBER, and CASE WHEN for custom sort orders.
Frequently asked questions
- Does Rails have an order(nulls_last: true) option?
- Not in 8.1.1. order(due_at: :desc) takes only :asc or :desc. Use arel_table[:due_at].desc.nulls_last.
- Where does PostgreSQL put NULL by default?
- NULL sorts as larger than any non-null value. That means last on ASC and first on DESC.
- Why does my order differ between SQLite and PostgreSQL?
- SQLite sorts NULL as smaller than any value. Same Rails code, opposite NULL position. Set the NULL position explicitly.
- Why does order("due_at DESC NULLS LAST") raise UnknownAttributeReference?
- In my 8.1.1 test it raised on SQLite and worked on PostgreSQL. Wrap the string in Arel.sql or use the Arel node.
- Can I make NULLS LAST use an index?
- Yes on PostgreSQL, if the index declares the same order: add_index :tasks, :due_at, order: { due_at: "DESC NULLS LAST" }. Confirm with EXPLAIN.
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 27, 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
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.
Rails with_recursive: Recursive CTE in ActiveRecord
Use with_recursive in Rails 7.2+ to walk trees in one query. Tested on ActiveRecord 8.1.1 and PostgreSQL 16, with depth, path and cycle guards.
ActiveRecord where vs find_by — Which to Use When
where returns a relation, find_by returns one record or nil. Here's when each is correct, what breaks if you pick wrong, and Rails 7/8 production patterns.
Leave a Response
Responses (0)
No responses yet
Be the first to share your thoughts