All Articles

Rails avoids queries when performing calculations on contradictory relation

Previously, relation calculations such as count would make a query even when passed a contradiction, contradiction relation means passing an empty array for eg:-

  User.where(id: []).count

It does not make sense to call a database for such contradictory relations.

Before

So, before Rails 7 was introduced, the database was called if the relation used for count, sum, average, minimum and maximum would be contradictory.

  => Product.where(title: []).count
  Product Count (4.7ms)  SELECT COUNT(*) FROM "products" WHERE 1=0
  => 0 


  => Product.where(title: []).sum(:price)
  Product Sum (17.5ms)  SELECT SUM("products"."price") FROM "products" WHERE 1=0
  => 0 


  => Product.where(title: []).average(:price)
  Product Average (3.5ms)  SELECT AVG("products"."price") FROM "products" WHERE 1=0
  => nil 


  => Product.where(title: []).minimum(:id)
  Product Minimum (5.0ms)  SELECT MIN("products"."id") FROM "products" WHERE 1=0
  => nil 


  => Product.where(title: []).maximum(:id)
  Product Minimum (5.0ms)  SELECT MAX("products"."id") FROM "products" WHERE 1=0
  => nil 

As it can be seen, it would make a query to the database even when passed a contradiction.

After

Now after Rails 7, it avoids making a query to the database.

  => Product.where(title: []).count
  => 0 


  => Product.where(title: []).sum(:price)
  => 0 


  => Product.where(title: []).average(:price)
  => nil 


  => Product.where(title: []).minimum(:id)
  => nil 


  => Product.where(title: []).maximum(:id)
  => nil  

Check out the PR for more details.