r/SQL • u/No_Ambition8323 • Sep 22 '26
Discussion When should you stop optimizing a SQL query?
It's easy to keep optimizing a SQL query once you start looking at execution plans, indexes, joins, and scans. But at some point, the improvement may not be worth the extra effort.
For example, if a query takes 10 seconds and you reduce it to 2 seconds, that's a big improvement. But would you spend another few hours trying to reduce it from 2 seconds to 1.5 seconds?
How do you decide when a query is “fast enough”?
Do you consider:
- Query execution time
- Number of users running it
- Frequency of execution
- CPU/memory usage
- Data volume and future growth
- Business requirements or SLA
Where do you personally draw the line between useful optimization and over-optimization?
27
Upvotes
60
u/Blecki Sep 22 '26
Until it's fast enough.
14
u/Kant8 Sep 22 '26
if query is constantly executed by some app it should be optimized to the point where it doesn't scan unnecessary data
9
u/BigBlue_72 Sep 22 '26
When it is no longer the squeaky wheel. We always have more problems than time. Don't waste time on problems that are not high priority to the customer.
4
u/Imaginary__Bar Sep 22 '26
Like every similar post, the answer is "it depends".
Fast enough is fast enough (usually). Can it get faster? Sure.
Would you spend a lot of time on the query? Maybe not.
Would you materialise a view instead? Probably.
3
u/dbxp Sep 22 '26
You should be considering these things before you start optimisation not when you're already part way through. There's no point in speeding something up which doesn't need to be faster
3
u/tommyfly Sep 22 '26
As with all DB questions, it depends. Someone else mentioned this already but context matters. Is it a nightly report, did you get it from 10 minutes to 30 seconds? Probably good enough. Is it a query that runs thousands of times a minute with high concurrency a must have? Work on it until you get as good as you can.
3
u/ArielCoding Sep 22 '26
Optimizing is also about keeping the code easy to maintain , a query with a bunch of clever tricks to save half a second can end up fragile and confusing to the next person that has to touch it.
2
u/atrifleamused Sep 22 '26
If you are shaving seconds off queries you have to decide why. It's it a query where a user is waiting or an over night process? If a report refreshes in 5 seconds instead of 10 seconds but it took a days effort, have you achieved anything?
It's not always measurable.
5
u/you_are_wrong_tho Sep 22 '26
No such thing as overly optimized. My lobster too buttery my steak too juicy.
If you have unlimited time to optimize something to its absolute full potential then you should. Logical reads being as low as possible is generally what I shoot for.
But, usually you don’t have unlimited time and resource, so sometimes good enough is good enough.
1
u/Healthy_Coconut1636 Sep 22 '26
Always strive for perfect optimization. The biggest factor is time. Given unlimited time, you should always try to make it perfect. Since time is limited its up to each dev to decide bassd on their work load when to leave something alone. For me Om always going back and reviewing my sql, model, dax, reports whenever I have 15 mins to spare. Databases and projects are always in a state of entropy. The more you do to clean it up the better to can help ensure the entropy stays under control.
1
u/North-Macaron-861 Sep 22 '26
When it runs
1
u/crippling_altacct Sep 22 '26
It really depends on what it's being used for. Is this a daily job? Is this a monthly job? Is it an ad hoc where this will never be used again?
1
u/jrblockquote Sep 22 '26
Does your company have an SLA? If so and your query executes within the SLA, then you're all set. In my experience (20+ years enterprise), unless it's something egregious, then you're probably fine.
1
u/magicaltrevor953 Sep 22 '26 edited Sep 22 '26
I'm a data analyst so I am limited by the architecture I am given in terms of what optimisations I can do, but when I am writing queries I usually start off from the perspective of making it "not complete dogshit".
Then how much time I am willing to put in to making it 'perfect' depends on:
Lastly, if I were to optimise it, roughly what benefits would actually be achievable i.e. if I squeeze out a bit more performance and the query goes from 5 minutes to 3, that is a lot different to going from 30 down to 10. The original 5 minutes may be perfectly acceptable. Its unlikely without significant rework that I would be going from 40 minutes down to 2, if I didn't write complete shit in the first place. Being close to the data I have an idea of how well our platform generally performs in different scenarios so you get an idea of what is achievable.
Generally speaking my queries are simple enough (although they can still get pretty complex) that I can follow some DB-specific best practises and get myself 90% of the way there, whether the remaining 10% is worth it will depend on the above points. I try not to be running shit code when possible, but occasionally need to accept non-perfect code in the interests of speed. Code templates and macros help quite a bit to avoid spending time writing boiler-plate, and that time saving means I can spend a bit more ensuring that what I am writing is at least 'good'.
Our DBAs are never moaning that my codes are not optimised enough, but I am sure in some cases I could push things further.
1
u/SP3NGL3R Sep 22 '26
Get it from "this doesn't make sense" to "yea that's about right", then go to the next slowest query that doesn't make sense and get it to about right. Rinse repeat until the pipeline can be run every 15 minutes (or as business needs or appropriate frequency per query purpose). All the while filtering in and possibly prioritizing new requests.
1
u/This-Emergency8839 Sep 22 '26
What most others have said.
Once per 24 hours and runs overnight? So long as it's not eating resources, good enough is fine.
I have some queries that get hit all day and I'll obsess over shaving a second off.
1
u/TheKerui Sep 22 '26
I want that query plan to show me nothing but seeks. Row estimations being off is something I'll chase if runtime is still a concern after all I see is seek seek seek seek join join write.
1
u/Joelle_bb Sep 22 '26
Depends on its use case/application
1
u/boring_accountant Sep 22 '26
Depends what's the use. Produce a daily report during the night when nobody is expecting the report until tomorrow morning ? Difference between a minute, 10 seconds and 1 second is irrelevant. Now maybe it's part of a broader chain of executions that needs to be compressed then maybe optimizing becomes relevant. Multiple factors to take into account but generally optimizing with no target or real reason for doing so is a waste of time.
1
u/kagato87 MS SQL Sep 22 '26
When it's good enough for the use.
Is this some nightly report? 10 seconda is fine.
Is this an interactive report? Still fine if it's being cached in the front end, but worth a tuning pass.
Is this for a widget on your website? 2s is kinda slow still.
1
u/ThetaLife Sep 22 '26
When it stops being a problem.
1
u/redditor3900 Sep 23 '26
Until it runs in negative time
1
u/Gwaptiva Sep 23 '26
When nobody complains, do not optimize. If folk complain enough, do a bit. Measure before, during, after. When better, stop and go back to start
1
u/weezeelee Sep 23 '26
This is what separates Senior from Junior DBAs. Performance tuning is like cooking: you don't use a scale to measure every gram, you stop when your ancestors tell you to stop.
1
u/zbignew Sep 23 '26
User experience is the only metric.
I prefer Linus’ metric from when he was creating Git: If it’s something that a user does once per day, it should take 1 second. If they do it more frequently, it should be faster than that. Less frequently than once per day, maybe it can be slower.
If that’s not possible for a query with your current schema, fix the schema. Cache things. Pre-calculate.
1
u/Sneilg Sep 23 '26
Hi AI bot. Probably when it takes less time than it takes me to go for a smoke. If it’s still running when I get back it’s too slow.
1
u/Zenithixv Sep 24 '26
Depends heavily on context, need to weigh how much it impacts usability for users, how much more complicated it gets to maintain, how long you have to spend to optimize it further, etc
1
u/Imaginary-poster Sep 25 '26
My goal is less than 1 min or less than 2 mins for larger queries with <30 secs being the ideal. Mind you I'm working in a org that is probably small my most measures. So its relatively easily achieved.
1
u/jshine13371 Sep 22 '26
Execution time is not the only reason to optimize a query. The fastest executing query could still being a ton of needless work under the hood, causing unnecessary resource contention and blocking. Conversely, longer executing queries aren't necessarily a bad thing either. It all depends on use case.