Using ‘.exists?’ in Rails

Recently I was asked by a team member what was better to use `.exists?(…)` or `.where(…).present?`. At one point I did actually think “Rails is super clever so surely the SQL generated would be the same… right?” — Very wrong it turns out! This is what Rails generates for each;

  • `.where(…).present?` will select all of the instances from the database then Rails will check if the returned relation has any objects present.
  • `exists?(…)` will only try to find 1 result from the database and return `1` if anything is found.

To show the differences in execution times I decided to create a simple Rails app which has movies and see for myself how long each query would take. The two queries are;

Movie.where(title: ‘Green Ninjas: The Dr. Reese Kunde Story’).present?
Movie.exists?(title: Green Ninjas: The Dr. Reese Kunde Story')

Here are the results:

Number of Movies | .where(…).present? | .exists?(…)
10000 | 1.9ms | 0.2ms
50000 | 19.1ms | 0.2ms
100000 | 50.1ms | 0.2ms

That is a dramatic difference in execution times!

Next time you need to check if something is present in the database make sure you use `.exists?(…)`.