Skip to main content

Rails UNION Query in ActiveRecord

ActiveRecord 8.1 has no union method on a Relation. User.respond_to?(:union) returns false. Build the UNION with Arel, then wrap it in from so you still get a Relation back.

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

SELECT * FROM users WHERE id = 1
UNION
SELECT * FROM users WHERE id = 2

ActiveRecord

a = User.where(id: 1).arel
b = User.where(id: 2).arel
User.from(Arel::Nodes::TableAlias.new(a.union(b), :users))

SQL that Rails 8.1.1 generates

SELECT "users".* FROM ( SELECT "users".* FROM "users" WHERE "users"."id" = 1 UNION SELECT "users".* FROM "users" WHERE "users"."id" = 2 ) "users"

A cleaner alternative

User.where(id: 1).or(User.where(name: "u2"))

If both sides query the same table and only the WHERE differs, .or is simpler. It produces one query with OR and no UNION.

Related form

SELECT * FROM users WHERE id = 1
UNION ALL
SELECT * FROM users WHERE id = 1
a = User.where(id: 1).arel
b = User.where(id: 1).arel
User.from(Arel::Nodes::TableAlias.new(a.union(:all, b), :users))

What goes wrong

There is no Relation#union

Many blog posts show User.where(...).union(...). It raises NoMethodError on Rails 8.1.1. Use Arel, or add a gem if you need the shortcut everywhere.

Both sides need the same columns

UNION needs the same number and types of columns on each side. Build both relations from the same model with the same select list.

UNION removes duplicates, UNION ALL does not

UNION sorts or hashes to drop duplicate rows, which costs time. Use union(:all, b) when duplicates are impossible or acceptable. In the UNION ALL example above, the same user comes back twice.

Do not paste to_sql into strings with user input

Building the UNION from to_sql strings inlines the values into SQL. Arel keeps the quoting and bind handling inside Rails.

Convert your own UNION 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 UNION in ActiveRecord?

Take the Arel of each relation, call a.union(b), and wrap it with Model.from(Arel::Nodes::TableAlias.new(union, :table_name)).

Does Rails have a union method?

Not on ActiveRecord 8.1. Relation does not respond to union. Use Arel or a gem.

How do I do UNION ALL in Rails?

Call a.union(:all, b) on the Arel node. It keeps duplicate rows and skips the de-duplication step.