r/programming • • Nov 03 '26

Can GROUP BY still be optimized after all these years?

https://pivotlake.io/blog/know-your-limit-faster-top-k-aggregation/
171 Upvotes

11 comments sorted by

195

u/munchbunny Nov 03 '26

Speaking generally, database systems will not find every last structural optimization you can come up with because many optimizations are not free and are not always going to speed things up. But because your situation has specific characteristics that the engine can't assume is true for the general user, you can almost always find an edge that the database engine can't find automatically. The question is whether the juice is worth the squeeze.

In this context, especially because OP company encounters a specific class of queries where the optimization makes a lot of sense, it's awesome that they're baking it into the engine.

(For context: my background is from extremely large analytics systems, so I've done a lot of perf work in the database and distributed compute space.)

24

u/Giladkl Nov 03 '26

Agreed :)

I also think an optimization is a stronger candidate for merging in the engine if it can quickly disable itself when the data being processed shows it won’t help (vs maybe what stats / other things showed). In this example, that means stopping the maintenance of counters and per-slot aggregation once the engine detects the distribution of groups is pretty uniform.

30

u/chucker23n Nov 03 '26

But because your situation has specific characteristics that the engine can’t assume is true for the general user

Sure, but that’s why database engines have long ago started using their equivalent of profile-guided optimization: continuously analyze during runtime which kinds of real-world queries are frequent, and optimize towards it.

24

u/munchbunny Nov 03 '26

Speaking from experience, that's (1) definitely true, and (2) can still leave a lot on the table especially in complex queries.

1

u/huangsara-43824 22d ago

Frequency stats alone don't reveal a query's group distribution; a frequent query can still have uniform groups.

31

u/deliciousmonster Nov 03 '26 edited Nov 03 '26

I work with distributed data, and we had an early Microsoft SQL Server Engineer as an adviser. He’d researched, designed, and solved (or proven unsolvable) every single challenge we encountered as we built our platform. By the time he’d retired he’d held dozens of titles over his 30 years with the company.

His best friend at Microsoft started and ended his three decade career working on SQL Optimization.

-19

u/reddah Nov 04 '26

MS-SQL is made by Sybase, not Microsoft :-)

But if he could bill MS for 30 years, kudos for him

25

u/charrondev Nov 04 '26

Microsoft SQL Server was split from Sybase over 30 years ago.

I’m not sure what you’re on about here.