Use exists?
Ruby:
irb(main):016:0> User.where("id > ?", 1).exists?
User Exists (0.9ms) SELECT 1 AS one FROM "users" WHERE (id > 1) LIMIT 1
=> true
Postgres:
------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.11..0.16 rows=1 width=0) (actual time=0.128..0.128 rows=1 loops=1)
-> Index Only Scan using users_pkey on users (cost=0.11..3958880.39 rows=85465216 width=0) (actual time=0.125..0.125 rows=1 loops=1)
Index Cond: (id > 1)
Heap Fetches: 1
Planning time: 2.707 ms
Execution time: 0.447 ms
(6 rows)
Ruby:
irb(main):017:0> User.where("id > ?", 1).present?
User Load (1.8ms) SELECT "users".* FROM "users" WHERE (id > 1)
=> true
Postgres:
-------- Ungodly slow
Ruby:
irb(main):019:0> User.where("id > ?", 1).any?
(1.1ms) SELECT COUNT(*) FROM "users" WHERE (id > 1)
=> true
Postgres:
postgres=# explain analyze SELECT COUNT(*) FROM "users" WHERE (id > 1);
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------------
Aggregate (cost=4001612.99..4001613.00 rows=1 width=0) (actual time=13830.287..13830.287 rows=1 loops=1)
-> Index Only Scan using users_pkey on users (cost=0.11..3958880.39 rows=85465216 width=0) (actual time=0.018..13335.110 rows=5155344 loops=1)
Index Cond: (id > 1)
Heap Fetches: 4864391
Planning time: 0.257 ms
Execution time: 13830.332 ms
(6 rows)