r/SQL • u/Effective_Ocelot_445 • Jul 30 '26
MySQL How do you optimize SQL queries without making them harder to maintain?
As databases grow, performance becomes more important, but overly complex queries can be difficult to maintain. How do you balance query optimization with readability in production environments?
16
Upvotes
8
u/lalaluna05 Jul 31 '26 edited Jul 31 '26
I build very modularly so that changes and updates are straightforward. Copious notes. Clear formatting.
I have restructured soooo many of our sprocs purely because I couldn’t stand the frankencoding that got cobbled together over the years and the hours it took.
3
u/cwjinc Aug 01 '26
I sometimes convert very complicated queries into a series of CTEs.
This can make them considerably easier to read.
A good database engine will take care of folding it back up into an efficient plan.
2
u/Erasmus_Tycho Jul 31 '26
Breaking steps out into CTEs to increase readability is something I've observed people doing though honestly that often leads to bigger overall queries. I just try to leave comments to help explain the steps and tables involved. No hard coding dates or values.
2
u/thatOMoment Jul 31 '26
There are a some optimizations that make them more maintainable.
Such as removing distinct from a query with joins where you aren't selecting the columns and replacing them with EXISTS
Or correllated subqueries into LATERAL/APPLY.
Sometimes, it just do have to be ugly unless you are able to change service layer as well.
2
u/Informal_Pace9237 Aug 04 '26
Read many comments and see most think CTE is a magic bullet for readability and execution. It may be a magic bullet for readability but never for execution.
Here is a article covering different DBMS
https://www.linkedin.com/pulse/ctesubquery-factoring-optimization-raja-surapaneni-jyjie/
1
u/carlovski99 Jul 31 '26
Been going through this recently. Application used a massive piece of SQL that had been tweaked and added to over the years. Had become quite suboptimal, repeated scans of the same tables, functions being used which invalidated indexes etc. And eventually got to a state where the optimiser struggled to produce a stable or optimal plan. Caused huge performance problems in production. We are splitting it up into separate, much simpler queries. Technically it's suboptimal - getting the data on one hit would be more efficient, with the right query. But it's going to allow for easier testing, optimising each part and should be more stable. So real world performance will be better.
So it's not just 'SQL' you need to look at, it's the whole architecture, if it's part of an application.
1
u/singletWarrior Jul 31 '26
Not always but most of the time they get difficult either by optimising for speed or for correctness and both are almost always due to layout issues… the correct way to fix is usually not prioritised by the business so it stay uncorrected till whole new stack of technology doing similar things hit the same roadblocks by other means or till the demand dies out
1
u/AnAcceptableUserName Jul 31 '26
Yes. Remove complexity.
I don't see these as conflicting ends needing balanced. Often you can get both the same way
Identify your complex operations and decompose them until all that you're left with is simple component steps, then optimize those.
1
u/theriot78 Jul 31 '26
You ask AI to do it. I would have given you a very different answer a year or two ago.
1
u/AntLost4161 Aug 02 '26
The way I deal with things is that unless it really needs to be as quick as possible and you're not using tons of cross joins or other really compute heavy things, readability is most important. Break down different tasks into different CTEs, add the odd note where you think the logic isn't immediately visible, then you have code that can be maintained and adjusted in the future.
A lot of people go into either extreme, either to write tons of notes and have readability be the only focus, or they scrap all ease of adjustments and just make something instantly as optimal as possible. The truth is that we typically aren't doing anything worth immediate results, so taking things a bit slower isn't always a bad idea.
1
u/Marthurio Aug 03 '26
Depends really. Which parts do you find complex?
1
u/venkat_deepsql Aug 03 '26
Complex queries means we are pushing more the query computation to the query engine. This is not bad. If we try to break the complex query into pieces and patch them up, then we are not really utilizing the super powers of database. Query engines like Oracle (which I worked before) are known for transalting large complex queries (even 10 page queries) to efficient query execution tree.
However, there may be cases where data flows can be parallel. And many query engines doesn't support parallel execution (mysql). In these cases, two queries should be executed in parallel and stitched them in application layer.
So, one should understand the true potential of their DBMS and make these decisions.
1
u/mu_SQL Aug 03 '26
I use stores procedures and temtables to make smaller batches and gain performance. Unlike CTE, temptables are indexable.
1
u/Informal_Pace9237 Aug 04 '26
Readability is on the reader. If one cannot read a query then they have a lot to learn and come back to read. IMO.
1
u/many_hats_on_head 1d ago
A while I ago I would have suggested using CTEs, splitting the query up, formatting etc, but these days I would suggest using a proper AI tool if accuracy and simplicity is a concern to you (99% of the AI-powered SQL generators severely underperform, so beware). I would suggest using the "Deep Analysis" mode on this SQL optimizer.
1
u/Creepy_Delay_6077 Jul 30 '26
I prefer a clear CTE-based query with the correct indexes over a shorter but heavily nested query. After optimization, I compare execution time, rows scanned, memory usage, and output accuracy to ensure performance improved without reducing maintainability.
1
u/jshine13371 Jul 31 '26
Typically the more complex the query, the less performant it is. So there's a somewhat congruence in performance tuning that should result in the query becoming simpler / easier to read & maintain. A lot of performance tuning techniques involve taking a larger single batch of statements and breaking them down into multiple batches (steps) that give the query optimizer breathing room between steps, typically via materializing the data at each step. Or straight up re-architecting the process implementation to be simpler.
0
u/ravi0087 Aug 01 '26
EXPLAIN) and proper indexes (composite/covering), leaving the SQL clean and readable.Avoid Common Anti-Patterns:
DISTINCTforEXISTS/INon joins.WHEREclauses (maintain sargability).SELECT *.28
u/[deleted] Jul 31 '26
[removed] — view removed comment