Skip to main content

SQL CASE WHEN in Rails ActiveRecord

How to write CASE WHEN, conditional sums and custom sort order in ActiveRecord, tested on Rails 8.1.1 and PostgreSQL 16.

R
Raza Hussain
· 8 min read · 27
Diagram: a CASE block feeds select, which works, order with a raw string, which raises an error, and order wrapped in Arel.sql, which works.

ActiveRecord has no case method. Write a SQL CASE WHEN as a string inside select, order, group or sum, wrap it in Arel.sql where Rails refuses raw SQL, or build it with Arel::Nodes::Case. For custom sort order, skip CASE and use in_order_of.

Every example below ran on ActiveRecord 8.1.1 with PostgreSQL 16 on 24 November 2026. The SQL shown is the SQL Rails logged.

The schema used in every example

class Order < ApplicationRecord
  enum :status, { pending: "pending", paid: "paid", refunded: "refunded", failed: "failed" }
end
# orders: status (string), amount_cents (integer), created_at, updated_at

Six rows: ids 1, 2 and 6 are paid (5000, 2500 and 800 cents), id 3 is pending (1200), id 4 is refunded (3000), id 5 is failed (900).

Label rows with CASE in select

SQL:

SELECT id, amount_cents,
  CASE WHEN amount_cents >= 5000 THEN 'large'
       WHEN amount_cents >= 1000 THEN 'medium'
       ELSE 'small' END AS size_label
FROM orders

ActiveRecord:

orders = Order.select(
  "orders.id, orders.amount_cents, " \
  "CASE WHEN amount_cents >= 5000 THEN 'large' " \
  "WHEN amount_cents >= 1000 THEN 'medium' ELSE 'small' END AS size_label"
).order(:id)

orders.map { |o| [o.id, o.size_label] }
# => [[1, "large"], [2, "medium"], [3, "medium"], [4, "medium"], [5, "small"], [6, "small"]]

select accepts a plain string, and the alias becomes a method on each record. The alias is not a column, so you cannot use it in where on the same query.

Build the same CASE with Arel

If you want Rails to quote and qualify the names, use Arel::Nodes::Case:

amount = Order.arel_table[:amount_cents]

size = Arel::Nodes::Case.new
  .when(amount.gteq(5000)).then(Arel::Nodes.build_quoted("large"))
  .when(amount.gteq(1000)).then(Arel::Nodes.build_quoted("medium"))
  .else(Arel::Nodes.build_quoted("small"))

Order.select(:id, size.as("size_label")).order(:id).to_sql

Rails 8.1.1 produced:

SELECT "orders"."id", CASE WHEN "orders"."amount_cents" >= 5000 THEN 'large'
  WHEN "orders"."amount_cents" >= 1000 THEN 'medium' ELSE 'small' END AS size_label
FROM "orders" ORDER BY "orders"."id" ASC

The rows came back identical to the string version. Arel is a lower-level API than the query interface, so re-run your tests when you upgrade Rails. For one or two CASE expressions, the string version is easier to read.

Count and sum by condition (conditional aggregation)

This is the most common reason to reach for CASE: several totals in one pass, instead of one query per status.

SELECT SUM(CASE WHEN status = 'paid' THEN amount_cents ELSE 0 END) AS paid_cents,
       SUM(CASE WHEN status = 'refunded' THEN amount_cents ELSE 0 END) AS refunded_cents
FROM orders
row = Order.select(
  "SUM(CASE WHEN status = 'paid' THEN amount_cents ELSE 0 END) AS paid_cents",
  "SUM(CASE WHEN status = 'refunded' THEN amount_cents ELSE 0 END) AS refunded_cents"
).take

[row.paid_cents, row.refunded_cents]
# => [8300, 3000]

One query, one table scan. The calculation methods take the expression too, and both of these returned 8300:

Order.sum("CASE WHEN status = 'paid' THEN amount_cents ELSE 0 END")
Order.sum(Arel.sql("CASE WHEN status = 'paid' THEN amount_cents ELSE 0 END"))

Use Arel.sql anyway. It marks the string as SQL you wrote on purpose, and it keeps the code working if you later move the same expression to a method that checks its arguments, such as order.

PostgreSQL and SQLite also offer FILTER, which reads better for counts:

Order.select("COUNT(*) FILTER (WHERE status = 'paid') AS paid_count").take.paid_count
# => 3
SELECT COUNT(*) FILTER (WHERE status = 'paid') AS paid_count FROM "orders"

MySQL has no FILTER, so keep SUM(CASE ...) if your app must run on both.

For simple grouped counts without any CASE, see ActiveRecord GROUP BY and COUNT.

Group by a CASE bucket

bucket = "CASE WHEN amount_cents >= 5000 THEN 'large' " \
         "WHEN amount_cents >= 1000 THEN 'medium' ELSE 'small' END"

Order.group(Arel.sql(bucket)).count
# => {"large"=>1, "medium"=>3, "small"=>2}

group accepted the plain string in my test, so Arel.sql is optional there. It becomes required the moment you add .order(bucket), which raises the same UnknownAttributeReference error shown in the next section.

ORDER BY CASE: Rails blocks the plain string

Order.order("CASE status WHEN 'failed' THEN 0 ELSE 1 END").to_a
# ActiveRecord::UnknownAttributeReference: Dangerous query method (method whose
# arguments are used as raw SQL) called with non-attribute argument(s): ...

Rails refuses raw SQL in order unless you mark it. Wrap it in Arel.sql when the string is yours and contains no user input:

Order.order(Arel.sql("CASE status WHEN 'failed' THEN 0 WHEN 'pending' THEN 1 ELSE 2 END"), :id)
  .pluck(:id, :status)
# => [[5, "failed"], [3, "pending"], [1, "paid"], [2, "paid"], [4, "refunded"], [6, "paid"]]

Never put params into that string. If a value comes from a request, pass it through a whitelist or use the next method.

Custom sort order: use in_order_of instead

in_order_of (added in Rails 7.0) generates the CASE for you, with quoting and no Arel.sql:

Order.in_order_of(:status, %w[failed pending paid refunded]).order(:id)
SELECT "orders".* FROM "orders"
WHERE "orders"."status" IN ('failed', 'pending', 'paid', 'refunded')
ORDER BY CASE WHEN "orders"."status" = 'failed' THEN 1
  WHEN "orders"."status" = 'pending' THEN 2
  WHEN "orders"."status" = 'paid' THEN 3
  WHEN "orders"."status" = 'refunded' THEN 4 END ASC,
  "orders"."id" ASC

Notice the WHERE ... IN (...). By default in_order_of drops every row whose status is not in your list. If you want to keep them and sort them last, pass filter: false:

Order.in_order_of(:status, %w[failed pending], filter: false).order(:id)
ORDER BY CASE WHEN "orders"."status" = 'failed' THEN 1
  WHEN "orders"."status" = 'pending' THEN 2 ELSE 3 END ASC, "orders"."id" ASC

I ran this on 8.1.1. Check the option on older Rails versions before you rely on it.

Bind values inside a CASE

select has no bind values. A second argument is read as another column, so select("... >= ?", 2000) produced SELECT ... >= ? ..., 2000 in my test. Build the fragment with sanitize_sql_array so the value is quoted:

fragment = Order.sanitize_sql_array(
  ["CASE WHEN amount_cents >= ? THEN 'large' ELSE 'small' END", 2000]
)
# => "CASE WHEN amount_cents >= 2000 THEN 'large' ELSE 'small' END"

Order.select(:id, Arel.sql("#{fragment} AS size_label")).order(:id).map(&:size_label)
# => ["large", "large", "small", "large", "small", "small"]

where does take placeholders:

Order.where("CASE WHEN status = 'paid' THEN amount_cents ELSE 0 END > ?", 1000).pluck(:id)
# => [1, 2]
SELECT "orders".* FROM "orders"
WHERE (CASE WHEN status = 'paid' THEN amount_cents ELSE 0 END > 1000)

UPDATE with CASE

Order.where(status: %w[pending failed]).update_all(
  ["amount_cents = CASE status WHEN 'pending' THEN amount_cents + 100 ELSE 0 END"]
)
# => 2

update_all skips validations and callbacks. It returned 2 here, and the pending row went from 1200 to 1300 while the failed row went to 0. Run it inside a transaction first if you are not sure about the WHERE.

Which form to use

Need Use
Label each row select("CASE ... AS label")
Several totals in one query select("SUM(CASE ...)") or FILTER on PostgreSQL
Group into buckets group(Arel.sql("CASE ..."))
Fixed sort order for a column in_order_of
Sort by a computed rank order(Arel.sql("CASE ..."))
Values that change at runtime sanitize_sql_array, then Arel.sql
You want Rails to quote everything Arel::Nodes::Case

Two checks before you ship any of these. First, call .to_sql and read the statement. Second, if the query filters or groups on the CASE, run EXPLAIN: an expression on a column usually cannot use a plain index on that column. This post on reading generated SQL shows how. For the where side of conditional logic, see Rails where clause: multiple conditions and OR logic.

Have a CASE WHEN query you need to translate? Paste it into the SQL to ActiveRecord converter and compare the output with .to_sql in your console.

Frequently asked questions

Does ActiveRecord have a CASE WHEN method?
No. Pass the CASE expression as a string to select, group, sum or where, wrap it in Arel.sql for order, or build it with Arel::Nodes::Case.
Why does order with a CASE string raise UnknownAttributeReference?
Rails refuses raw SQL in order unless you mark it. Wrap a CASE you wrote yourself in Arel.sql, and never put user input in it.
How do I sort by a custom list of values in Rails?
Use in_order_of, for example Order.in_order_of(:status, %w[failed pending paid]). It builds the CASE and quotes the values for you.
Does in_order_of remove rows that are not in my list?
By default yes, it adds a WHERE IN filter. Pass filter: false to keep the other rows and sort them last. Tested on Rails 8.1.1.
How do I sum a column by condition in one query?
Use SUM(CASE WHEN status = 'paid' THEN amount_cents ELSE 0 END) in select or pass it to sum. On PostgreSQL you can use COUNT(*) FILTER (WHERE ...) instead.

Was this article helpful?

Your feedback helps us improve our content

Be the first to vote!

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 24, 2026

Try These Queries in Our Converter

See the SQL examples from this article converted to ActiveRecord—and compare the SQL Rails actually generates.

27

Leave a Response

Responses (0)

No responses yet

Be the first to share your thoughts

R

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.

💼 15 years experience 📝 55 posts