diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index c565479c1a..9513e035af 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -315,6 +315,7 @@ module ActiveRecord end relation = construct_relation_for_exists(conditions) + return false if relation.where_clause.contradiction? skip_query_cache_if_necessary { connection.select_rows(relation.arel, "#{name} Exists?").size == 1 } end diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index aec6db961f..ba0d96b68c 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -444,6 +444,18 @@ module ActiveRecord end end + test "no queries on empty relation exists?" do + assert_queries(0) do + Post.where(id: []).exists?(123) + end + end + + test "no queries on empty condition exists?" do + assert_queries(0) do + Post.all.exists?(id: []) + end + end + private def skip_if_sqlite3_version_includes_quoting_bug if sqlite3_version_includes_quoting_bug?