Skip to main content

SQL INTERSECT and EXCEPT in Rails ActiveRecord

ActiveRecord 8.1.1 has no intersect or except on relations, so here are four tested ways to get the same rows, plus the NOT IN trap.

R
Raza Hussain
· 8 min read · 12
Two overlapping stone discs for product 1 and product 2 with the overlap in red, on a cracked slab marked INTERSECT, EXCEPT and NOT IN trap.

ActiveRecord 8.1.1 has no intersect or except method on relations. You get set operations in one of three ways: build the node with Arel and wrap it in from, write the SQL by hand, or rewrite the question with where(id: subquery). The rewrite is the best choice most of the time because the result stays a normal relation.

Everything below ran on ActiveRecord 8.1.1, Ruby 3.3.6 and PostgreSQL 16.15. Only PostgreSQL was tested. The full script and its output are in the test files for this post. For UNION, see the existing UNION post. This post covers the other two set operators.

The schema and the question

Two tables. Five customers. Seven purchase rows, one of them with a NULL customer_id.

class Customer < ActiveRecord::Base; has_many :purchases; end
class Purchase < ActiveRecord::Base; end
# ann: products 1 and 2   bob: product 1   cy: product 2
# dee: products 1 and 2   eve: nothing
# plus one product 2 purchase with customer_id NULL

The two questions:

-- INTERSECT: customers who bought product 1 AND product 2
SELECT customer_id FROM purchases WHERE product_id = 1
INTERSECT
SELECT customer_id FROM purchases WHERE product_id = 2;

-- EXCEPT: customers who bought product 1 but NOT product 2
SELECT customer_id FROM purchases WHERE product_id = 1
EXCEPT
SELECT customer_id FROM purchases WHERE product_id = 2;

INTERSECT returns ann and dee. EXCEPT returns bob.

Two lookalike methods are not set operators

respond_to?(:intersect) returns false on a relation. Calling it raises NoMethodError. Nothing set-related exists there.

Two neighbors are easy to confuse with set operators:

Customer.where(name: "ann").except(:where).to_sql
# SELECT "customers".* FROM "customers"

Relation#except removes query parts from the relation. It does not subtract rows. You get the whole table back with no error, which is the worst way to be wrong.

Customer.where(id: [1,2,3]).and(Customer.where(id: [3,4])).to_sql
# ... WHERE "customers"."id" IN (1, 2, 3) AND "customers"."id" IN (3, 4)
Customer.where(id: [1,2,3]).excluding(Customer.find(3)).to_sql
# ... WHERE "customers"."id" IN (1, 2, 3) AND "customers"."id" != 3

and merges two WHERE clauses. excluding removes given records by primary key. Both work on one table with plain conditions. Neither builds an INTERSECT or EXCEPT.

Option 1: Arel nodes and from

Arel has the nodes. SelectManager#intersect and #except return Arel::Nodes::Intersect and Arel::Nodes::Except. Wrap the node in a table alias and hand it to from:

p1 = Customer.joins(:purchases).where(purchases: { product_id: 1 })
p2 = Customer.joins(:purchases).where(purchases: { product_id: 2 })

node = p1.arel.intersect(p2.arel)
rel  = Customer.from(Arel::Nodes::TableAlias.new(node, :customers))
rel.to_sql
SELECT "customers".* FROM (
  SELECT "customers".* FROM "customers" INNER JOIN "purchases" ON "purchases"."customer_id" = "customers"."id" WHERE "purchases"."product_id" = 1
  INTERSECT
  SELECT "customers".* FROM "customers" INNER JOIN "purchases" ON "purchases"."customer_id" = "customers"."id" WHERE "purchases"."product_id" = 2
) "customers"

rel.map(&:name) returned ["ann", "dee"]. The bound values (product_id = 1) came through correctly on 8.1.1, and the result is a real relation. You chain order, limit and count on it.

The cost: you pass .arel objects around and pick the alias by hand. Both sides must return the same column list in the same order. SELECT customers.* on both sides works. A mismatch fails in PostgreSQL with each INTERSECT query must have the same number of columns.

I would only use this when the pieces are built dynamically, for example a search form with a variable number of filters. For two fixed queries it is more ceremony than raw SQL.

Option 2: from with a raw string

rel = Customer.from(<<~SQL.squish, :customers)
  (SELECT c.* FROM customers c JOIN purchases p ON p.customer_id = c.id WHERE p.product_id = 1
   INTERSECT
   SELECT c.* FROM customers c JOIN purchases p ON p.customer_id = c.id WHERE p.product_id = 2) customers
SQL

rel.order(:name).limit(10).pluck(:name)  # ["ann", "dee"]
rel.count                                # 2

This reads like the SQL you started from. The second argument to from is the alias and it must match the alias inside the string. Do not interpolate user input into the string. If you need values, build the string with sanitize_sql_array first, or use Option 3.

Option 3: find_by_sql

sql = <<~SQL
  SELECT customer_id FROM purchases WHERE product_id = ?
  INTERSECT
  SELECT customer_id FROM purchases WHERE product_id = ?
SQL
Purchase.find_by_sql([sql, 1, 2]).map(&:customer_id)   # [1, 4]
Purchase.find_by_sql([sql.sub("INTERSECT", "EXCEPT"), 1, 2]).map(&:customer_id)  # [2]

Placeholders work. The result is an Array of model instances, not a relation. Each instance carries only the selected columns, so attributes shows {"customer_id"=>2, "id"=>nil}. Reading an unselected attribute raises ActiveModel::MissingAttributeError. Use this when you need ids or a flat list and do not need to chain.

Option 4: rewrite it and skip the set operator

Most INTERSECT queries are AND over two subqueries:

Customer.where(id: Purchase.where(product_id: 1).select(:customer_id))
        .where(id: Purchase.where(product_id: 2).select(:customer_id))
SELECT "customers".* FROM "customers"
WHERE "customers"."id" IN (SELECT "purchases"."customer_id" FROM "purchases" WHERE "purchases"."product_id" = 1)
  AND "customers"."id" IN (SELECT "purchases"."customer_id" FROM "purchases" WHERE "purchases"."product_id" = 2)

Result: ann and dee. When the number of required products is large or dynamic, group and count instead:

Customer.joins(:purchases).where(purchases: { product_id: [1, 2] })
        .group("customers.id").having("COUNT(DISTINCT purchases.product_id) = 2")

Same two names came back. The count in HAVING is the number of products you require.

The EXCEPT rewrite has a NULL trap

The obvious rewrite of EXCEPT is where.not(id: subquery):

Customer.where(id: Purchase.where(product_id: 1).select(:customer_id))
        .where.not(id: Purchase.where(product_id: 2).select(:customer_id))

This generates NOT IN (SELECT customer_id ...). Our data has one product 2 purchase with a NULL customer_id. The result on PostgreSQL was []. The real EXCEPT query returned [2] for the same sets.

NOT IN against a list holding a NULL never evaluates to true, so every row is dropped. The same trap is covered for NOT EXISTS in the EXISTS post. Two fixes were tested, and both returned bob:

# 1. strip NULLs from the subquery
.where.not(id: Purchase.where(product_id: 2).where.not(customer_id: nil).select(:customer_id))

# 2. NOT EXISTS
.where("NOT EXISTS (SELECT 1 FROM purchases p2 WHERE p2.customer_id = customers.id AND p2.product_id = ?)", 2)

A real EXCEPT does not have this problem. It treats NULLs as equal to each other. In the test, intersecting the product 2 customer ids with themselves returned the NULL row too ([nil, 1, 3, 4]), while IN never matches NULL. If your data has NULL keys and you want them in the result, the rewrites silently differ from the set operator.

Duplicates

INTERSECT and EXCEPT remove duplicate rows. PostgreSQL also has INTERSECT ALL and EXCEPT ALL. After adding a second purchase of product 1 for ann, SELECT customer_id ... WHERE product_id = 1 intersected with the same select over product_id IN (1, 2) returned [1, 2, 4] with INTERSECT and [1, 1, 2, 4] with INTERSECT ALL. The IN rewrites always behave like the deduplicated form. Row-multiplying joins in the rewrite need distinct.

Which to pick

Situation Use
Same table, key lookups Option 4, where(id: subquery)
Need chaining, fixed SQL Option 2, from with a string
Pieces built at runtime Option 1, Arel node in from
Need ids or a flat list Option 3, find_by_sql

There is also the gem activerecord-setops, which adds intersect and difference to relations. Its README says it has only been tested with Rails 5, and Ruby Toolbox lists the last release (1.0.1) as March 2021. I did not test it on 8.1.1. For a production codebase I would not add it for a feature you write in ten lines.

To translate a query you already have, paste it into the SQL to ActiveRecord converter and compare the output with the options above. Check the generated SQL with to_sql before you ship it.

Related: SQL UNION in Rails, EXISTS and NOT EXISTS in Rails, Rails where clause conditions

Frequently asked questions

Does ActiveRecord have an intersect method?
No. On ActiveRecord 8.1.1, respond_to?(:intersect) returned false and calling it raised NoMethodError. Use Arel nodes with from, a raw SQL string, find_by_sql or a where IN rewrite.
What does Relation#except do in Rails?
It removes query parts such as :where or :order from a relation. Customer.where(name: 'ann').except(:where) returned the full table. It does not subtract rows like SQL EXCEPT.
How do I write SQL EXCEPT in ActiveRecord?
Either wrap an Arel except node in from, write EXCEPT in a find_by_sql string, or use where.not(id: subquery). The last form needs the subquery to exclude NULLs or it returns no rows.
Why does where.not(id: subquery) return nothing?
It generates NOT IN. When the subquery returns a NULL, NOT IN is never true and every row is dropped. In the test it returned an empty array while a real EXCEPT returned one row.
Does INTERSECT remove duplicates?
Yes. INTERSECT and EXCEPT deduplicate. PostgreSQL also supports INTERSECT ALL, which in the test returned [1, 1, 2, 4] where INTERSECT returned [1, 2, 4].

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

Try These Queries in Our Converter

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

12

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 📝 62 posts