by codeflo · 3y ago · 0 comments
Here’s a cheat code, in case you need to write a database query and don’t remember all the fancy join tricks: Problems like this often have a very straightforward solution with subselects. In this case, the main select gets the departments, and a subselect (with limit 1) fetches the top employee for each department.
That’s a very natural, compositional way of thinking. Granted, it’s not the most optimized way to do it, but more often then not, the resulting query plan is perfectly fine.
Depending on the details, the query plan might be exactly the same. I remember once (in SQL Server 2000, so long time ago) writing the same query in 3 completely different ways, only to see the DB generate the same plan for each one.
It would surprise most people how sophisticated the query transformations databases can do.
More recently, I've found that mysql sometimes behaves poorly with subselects, so I tend to avoid them out of habit.
It usually is the exactly same. (MySQL has a potato for a query optimizer tho.)
The biggest case it is suboptimal is when you need to produce multiple fields from the sub-select. Because then you need multiple sub-selects.
The nice thing about lateral joins is that they're very easy to understand conceptually once you get over the weird syntax.
It would be nice to have this feature; its a handy hammer for the right type of nail.
I've discovered a small number of queries actual do become faster when switching a column to a subselect.