3

This question arose from me doing 2 types of performance tweaks:

  • changing a lot of my where().present? statements to where().exists?
  • changing a lot of my where().first to find_by()

Sitting at the intersection of this is situations where I had previously written .where().first.present? and I'm wondering what would be more performant to change it to: .find_by().present? or .where().exists?

james
  • 3,989
  • 8
  • 47
  • 102

1 Answers1

3
  • Changing where().present? to where().exists?

where().present? or find_by().present? will always fetch the complete user record from the table:

SELECT * FROM xyz WHERE xyz.name = 'Deepesh'

whereas where().exists? or where().any? will run this query:

SELECT 1 FROM xyz WHERE xyz.name = 'Deepesh' LIMIT 1

So obviously exists? or any? would be better in terms of performance until you need that record you are checking to fetch some information or use it somewhere, for example:

user = User.find_by(name: 'Deepesh')
user.do_something if user.present?

so here you need to perform some action on that user if the record is present then using present? would be sensible.

Note: The time we would save using exists? would be the initialization of the ActiveRecord object, present? would initialize one, and exists will not. Read more here: https://stackoverflow.com/a/30192978/4207394

Deepesh
  • 6,138
  • 1
  • 24
  • 41
  • To clarify: so you're saying if you DO need to use the record found, use `.find_by().present?`; if you do NOT need to use the record found, use '.where().exists?`, correct? – james May 15 '22 at 05:17
  • Yes, because if you need to use that record below in the code then you will have to run two queries with `exists?`, one which will check if the record exists or not and one which would fetch the row from DB. So if you need to use the record below just fetch the record and check if it is present or not – Deepesh May 15 '22 at 05:19