Check existing record


How are you checking existing a record?
present? any? empty? exists?
Build.where(created_at: 7.days.ago..1.day.ago).passed.present?
Build.where(created_at: 7.days.ago..1.day.ago).passed.any?
Build.where(created_at: 7.days.ago..1.day.ago).passed.empty?
Build.where(created_at: 7.days.ago..1.day.ago).passed.exists?
Let's check SQL queries
Build.where(created_at: 7.days.ago..1.day.ago).passed.present?
# SELECT "builds".* FROM "builds" WHERE ("builds"."created_at" BETWEEN
# '2017-02-22 21:22:27.133402' AND '2017-02-28 21:22:27.133529') AND
# "builds"."result" = $1 [["result", "passed"]]
Build.where(created_at: 7.days.ago..1.day.ago).passed.any?
# SELECT COUNT(*) FROM "builds" WHERE ("builds"."created_at" BETWEEN
# '2017-02-22 21:22:16.885942' AND '2017-02-28 21:22:16.886077') AND
# "builds"."result" = $1 [["result", "passed"]]
Build.where(created_at: 7.days.ago..1.day.ago).passed.empty?
# SELECT COUNT(*) FROM "builds" WHERE ("builds"."created_at" BETWEEN
# '2017-02-22 21:22:16.885942' AND '2017-02-28 21:22:16.886077') AND
# "builds"."result" = $1 [["result", "passed"]]
Build.where(created_at: 7.days.ago..1.day.ago).passed.exists?
# SELECT 1 AS one FROM "builds" WHERE ("builds"."created_at" BETWEEN
# '2017-02-22 21:23:04.066301' AND '2017-02-28 21:23:04.066443') AND
# "builds"."result" = $1 LIMIT 1 [["result", "passed"]]


1. present? loads all the records from the database into memory and then checks</div>
2.  any? & empty? identical requests but opposite results. They are better, because load COUNT(*) of records.
3. exists? The best way. Is even more optimized. It uses the SELECT 1

Example
present?  =>  2892.7 ms
any?        =>   400.9 ms
empty?    =>   403.9 ms
exists?     =>     1.1 ms

Exception


For example, if we are checking for the existence of an association record without any scope, any? and empty? will also produce a very optimized query that uses SELECT 1 FROM ... LIMIT 1 form, but any? fill not hit the database again if the records are already loaded into memory.

semaphoreci.com

Comments