Skip to main content

Rails CTE (WITH) in ActiveRecord

Rails 7.1 added Relation#with. Pass the CTE name and a Relation, then point the outer query at it with from. The example selects from a CTE of published posts.

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

WITH recent AS (
  SELECT * FROM posts WHERE published = true
)
SELECT * FROM recent

ActiveRecord

Post.with(recent: Post.where(published: true)).from("recent AS posts")

SQL that Rails 8.1.1 generates

WITH "recent" AS (SELECT "posts".* FROM "posts" WHERE "posts"."published" = $1) SELECT "posts".* FROM recent AS posts

What goes wrong

with alone only defines the CTE

Post.with(recent: ...) adds WITH "recent" AS (...) but the outer query still reads FROM posts. Add from("recent AS posts") to read from the CTE, or join to it.

Rails 7.1 or later

Older versions raise NoMethodError for with. Upgrade, or write the CTE as a raw SQL string with from.

Check the plan on PostgreSQL 12 and later

PostgreSQL 12 inlines simple CTEs, so they often cost the same as a subquery. Add MATERIALIZED only when you want the old barrier behavior.

Convert your own CTE (WITH) query

Paste your SQL and press Convert. Always run .to_sql on the result and compare it with your original.

Questions

How do I write a WITH clause in ActiveRecord?

Use Post.with(recent: Post.where(published: true)).from("recent AS posts"). It needs Rails 7.1 or later.

Does ActiveRecord support CTEs?

Yes, since Rails 7.1 through Relation#with.

Is a CTE faster than a subquery?

Usually the same. PostgreSQL 12 and later inline simple CTEs. Read the output of explain on your data.