From be46acce8ff90afefefd004fbfc30a79713d1f12 Mon Sep 17 00:00:00 2001 From: Bianca Nenciu Date: Tue, 9 Jan 2024 02:19:37 +0200 Subject: [PATCH] PERF: Prefer subquery instead of two queries (#25167) The query that is now a subquery could return a long list of category IDs, which slowed down the query considerably. This improvement reduces the execution time from over 2 seconds down to about 100ms. --- app/models/category_list.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/models/category_list.rb b/app/models/category_list.rb index 6240256c265..108645b63e9 100644 --- a/app/models/category_list.rb +++ b/app/models/category_list.rb @@ -58,10 +58,9 @@ class CategoryList if SiteSetting.fixed_category_positions categories.order(:position, :id) else - allowed_category_ids = categories.pluck(:id) << nil # `nil` is necessary to include categories without any associated topics categories .left_outer_joins(:featured_topics) - .where(topics: { category_id: allowed_category_ids }) + .where("topics.category_id IS NULL OR topics.category_id IN (?)", categories.select(:id)) .group("categories.id") .order("max(topics.bumped_at) DESC NULLS LAST") .order("categories.id ASC")