Problem Statement
A heavy GROUP BY with a wide table is slow. Suggest two approaches to reduce work without changing results.
Explanation
Project only needed columns before the GROUP BY using a subquery so fewer bytes flow through sort or hash. If the grouping key has an index that matches the order, use an index-ordered scan to avoid a full sort.
Pre-aggregate upstream where possible, or use partial aggregation by partition key. In some engines, materializing to a temporary table and indexing the group keys first reduces spills and memory pressure.
Code Solution
SolutionRead Only
SELECT k, SUM(v) FROM ( SELECT key AS k, value AS v FROM big_table WHERE dt>=:d ) s GROUP BY k;
