ruby sql 78 lines · 4 tabs

Fast “Exists” Checks with select(1) and LIMIT

Shared by codesnips Jan 2026
4 tabs
module ExistenceChecks
  extend ActiveSupport::Concern

  class_methods do
    def has_any?(conditions = {})
      relation = conditions.present? ? where(conditions) : all
      relation.select(Arel.sql('1')).limit(1).exists?
    end

    def exists_efficiently?(conditions = {})
      where(conditions).exists?
    end

    def pluck_exists(conditions = {})
      sql = where(conditions).select(Arel.sql('1')).limit(1).to_sql
      connection.select_value("SELECT EXISTS(#{sql})") == true
    end
  end
end
4 files · ruby, sql Explain with highlit

Existence checks are one of the most common queries in a web app: does this user have an unread notification, has this order already shipped, is this coupon still valid. A naive Model.where(...).count > 0 or loading the full record wastes work because the database materializes rows or computes a full aggregate when the only fact needed is whether at least one row exists. The idiomatic answer is a query that selects a constant and stops at the first match: SELECT 1 FROM ... WHERE ... LIMIT 1. This snippet shows how that pattern is wrapped into a reusable Rails concern and then consumed by a service object.

In ExistenceChecks concern, the has_any? scope-like class method builds a relation, applies select(Arel.sql('1')) and limit(1), and asks the connection for a single value. Selecting the literal 1 means the database never has to read column data or visit the heap for the projected values; combined with LIMIT 1 the planner can short-circuit on the first qualifying index entry. exists_efficiently? delegates to ActiveRecord's built-in exists?, which already emits SELECT 1 ... LIMIT 1, but the concern also exposes pluck_exists for cases where a raw boolean from SELECT EXISTS(...) is preferable inside a larger query.

The reason count is avoided is subtle: on Postgres a COUNT(*) with a filter must scan every matching row even when the answer is only ever compared to zero. exists? instead asks the planner for the cheapest path to a single tuple, which an index can satisfy immediately. The trade-off is that exists? fires an extra query rather than reusing an already-loaded association, so it is wrong to call it in a loop over records that were eager-loaded — that reintroduces N+1 queries.

In EligibilityService, can_redeem? composes several of these checks and relies on short-circuit boolean evaluation so the most selective, cheapest check runs first and later queries are skipped entirely once one fails. The raw SQL tab shows exactly what Postgres receives and why the LIMIT 1 matters for the index scan. A developer reaches for this pattern whenever the code only needs a yes/no answer and correctness does not depend on the exact count.


Related snips

Share this code

Here's the card — post it anywhere.

Fast “Exists” Checks with select(1) and LIMIT — share card
Link copied