r/SQL • u/OnepieceKing2222 • Sep 16 '26
Discussion What SQL query optimization trick made the biggest difference for you?
I've been working with SQL for a while and recently started paying more attention to query performance rather than just getting the correct result.
What's one SQL optimization technique that made a noticeable difference for you?
For example:
- Indexing
- Avoiding unnecessary joins
- Window functions
- EXISTS vs IN
- Reading execution plans
- CTEs/subqueries
- Partitioning
Would be interested in hearing some real-world examples where a query went from slow to significantly faster.
119
Upvotes
104
u/hakathrones Sep 16 '26
Chatgpt đđ and this is the last thing i wanna admit
107
u/Jabuk-2137 Sep 16 '26
Reading execution plans, by a mile. With this you can find out where to use index, where to change your query or where you are as fast as possible and you can't squeeze much more.
15
u/Rex_Lee Sep 16 '26
Staging data in waterfall datasets in temp tables (not CTEs) your query so that by the time you do your heavy lifting logic you are touching the minimal number of records. indexing the bigger ones to speed the later datasets joins to them
14
u/Thisbymaster Sep 16 '26
Views. Knowing when and where to use views on complicated data sets has sped up calls that have taken +30 mins to less than a minute.
13
u/Better-Credit6701 Sep 16 '26
I remember walking into my new DBA job decades ago and quickly found out that they loved cursors, reading millions and millions of rows, one row at a time. Replacing those with temp tables brought the query down from 8 hours to 8 minutes
45
u/drinkmoredrano Sep 16 '26
Run truncate table first. After that queries against that table complete instantly.
21
u/Eleventhousand Sep 16 '26
Its difficult to say, because there are different issues for different times, different places.
For example, when I worked for Amazon, who had a large data volume on Redshift, moving away from CTEs and to temp tables helped immensely, because of the architecture of RedShift.
In the olden days, with SQL Server, one of the main saving graces was writing a script to replace and remove every call to a table variable in my entire data warehouse.
7
u/caveat_cogitor Sep 16 '26
Understand what predicate pushdown is, why it breaks differently under different SQL engines/query types, learning not to rely on it, and finally just learning to filter efficiently upstream.
Another one: Understand how your specific SQL engine works in terms of data storage and materialization down to the file system level and write ahead logging level or equivalent.
6
u/kagato87 MS SQL Sep 16 '26
Learning to read the query plan, and using the query store.
Sometimes it's a correlated subquery causing repeated scans.
Sometimes it's the cardinality estimator saying "1" and doing key lookups when it should have scanned on a different predicate. (Mstvf is a great way to cause this. That was a fast lesson.)
Sometimes it's two windows with conflicting sorts (there's a reason both lead and lag exist).
Sometimes it's bad data design, and indexed views to the rescue.
Sometimes the query is fine - nigh instant, but the application is making singleton calls in rapid succession and very high frequency.
The query plan and query store are how you get there.
6
u/burningburnerbern EXCEL IS NOT A DATABASE Sep 16 '26
Partitioning is by far the biggest improvement. Cut our bigquery bill in halfÂ
5
u/Optimal_Law_4254 Sep 16 '26
Becoming conscious of what causes table scans.
11
u/Thlvg Sep 16 '26
Proper data modelling ?
4
u/j_c_slicer Sep 17 '26
Using Dynamic SQL to optimize an existing "search everything by any combination of a zillion parameters" stored procedure.
3
u/adamjeff Sep 16 '26
Scalar subqueries
3
u/RavenCarver Sep 16 '26
CTEs along with the Oracle-specific /*+ MATERIALIZE */ hint got me a ton of optimization mileage in a database I used to work in a lot.
It started showing up in a lot of my code after that. My coworker started calling it "sparkle magic."
3
u/Time_Advertising_412 Sep 16 '26
The earliest one I learned was using a correlated subquery using exists rather than using IN with a horrendous subquery result.
3
u/ArielCoding Sep 16 '26
Once you open the execution plan the thing to check is estimated vs actual rows at each step, if they are way off, the db guessed wrong and pick a bad plan.
3
u/froctoso Sep 16 '26
Temporary tables, cut down our execution time from 18 secs - 0 secs. It had so much sub queries on a large database.
3
u/Joelle_bb Sep 16 '26
One of my more recent favorites: Option(recompile) and adjacent functions (think pass through queries and remote joins)
Why?
When hitting a linked server or executing something that gets timed out, it ignores pre-cached execution plans and builds a fresh one specific for the transaction.
No more time outs, no longer reliant on cached plans that end up being suboptimal (I'm a performance nut), and works on server or via linked server
Be warned: this isn't something to be used on queries requiring rapid/repeated executions. Think OLTP apps that need to query like 100 times a second, since its taxing on the server CPU. I use it strictly for heavier non-consecutive stuff that runs once/twice a day at most
3
u/brother_kenneth Sep 17 '26
After spending too many years writing SQL in Access (god help me), I finally got Azure Data Studio some years ago. CTEs were a real game changer. Beyond that, just learning early on to avoid unnecessary full table scans was pretty helpful.
3
u/Imaginary-poster Sep 17 '26
Apply has been a huge boost for me. CTEs were being over used and it was causing things to run really slow.
Also temp tables to handle non-index tables.
Gemini review my queries has been a wonder for learning to trim down these queries.
4
u/tommyfly Sep 16 '26
Break up complex queries into smaller parts. Find subsets of data, particularly from large tables, that can be stored in temp tables for later use in the query. Too many developers try to accomplish complex joins and case statements all in one step.
2
u/Mobile-Analyst-9617 Sep 16 '26
Query store hints
2
u/SimplyShifty Sep 16 '26
Partitions are the single biggest thing on the data I work with, I've seen a 100x increase before now and they consistently deliver. Although I did get a 150x improvement to an explain plan from using primary indices once, it's rare in my experience that the data fits a neat structure for that.
2
u/smyr0n Sep 16 '26
Yes. All of them. Starting with reading execution plans and then understanding how each one of the other items impact the execution plan.
In most of the queries Iâve optimized over the years, minimizing the number of IOs made the most impact. In my case IO was always the bottleneck.
2
u/No-Strategy-76 Sep 16 '26
indexed views
2
u/Complete-Fondant-202 Sep 16 '26
Goes without saying that execution plans are the first stop.
Use querystore Us sp_quickiestore
Things to look out for...
Linked Servers and therefore remote queries.
Joins involving the same CTE more than once, so materialise to tempt yable and use that
Temp table used more than once, consider indexing.
C I nside ro, page, columnstores on temp tables. Reduces memory pressure and lowers chance of tempdb hammering.
2
u/TrickyNerdlet Sep 16 '26
Understanding table statistics and how it impacts an incoming query plan. Keep your stats up to date if you make big changes
2
u/Einar_Son_of_Bjorn Sep 17 '26
Biggest single change: stop wrapping the indexed column in a function:
WHERE YEAR(created_at) = 2024 scans.
WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01' can use the index.Second, actually reading EXPLAIN.
I use MariaDB bcs if I want type and key, not vibes. ALL on a hot table is the bug. An extra join you âneeded for clarityâ is often the next one. U can find details in official open documents.
Window functions and CTE style almost never beat a missing index. Partitioning is last, not first.The query that moved for me: report by month on a status column. Function on the date plus SELECT * into a join. Range predicate + covering index on (status, created_at) and it dropped from seconds to milliseconds.
What engine are you use - MySQL, MariaDB, Postgres? The plan output is not the same dialect.
2
u/shine_on Sep 17 '26
One technique I use a lot is to process data in batches when I'm building a dataset. Either populate some columns to start with and leave the rest as NULLS, and then run a few UPDATE commands to fuill in the blanks, each update pulling data from a handful of other tables. I've found this to be quicker than having one query with dozens of joins trying to process everything all in one go.
It's also been beneficial to build some datasets on a month by month basis, setting up a loop to run through a calendar table and inserting data in 12 batches, one for each month, rather than for a whole year at once. Again, this is to reduce the memory requirement on the server and speeds up processing quite noticeably.
3
u/baldghoti Sep 16 '26
When it comes to taking over other peopleâs shitty code?
Getting rid of DISTINCT and replacing it with GROUP BY or ROW_NUMBER() for deduplication.
Fuck DISTINCT. All my homies hate DISTINCT.
2
u/Laspz Sep 16 '26
OPTION (RECOMPILE)
1
u/phunkmunkie Sep 16 '26
Knock the data set down with filters on indexed columns, CTEs and Temp tablesâŚ.
1
u/chocolateAbuser Sep 16 '26
i wouldn't call these "tricks", it's relatively common knowledge you have to study
for what i do optimization would usually reside at slightly higher livel
but anyway i would choose avoiding unnecessary joins and reading execution plans among these
1
u/supercoach Sep 17 '26
Dropping unnecessary indexes and just index performance in general. When I was greener, I'd slap an index onto any columns that might be used as a "where" qualifier without actually thinking about how indexes work or whether there was a better way.
That and vacuum/analyse optimisation for transaction heavy tables. If you've got hundreds of millions of records, then waiting until you hit twenty percent to auto vacuum is asking for trouble.
1
u/shadow__lord Sep 17 '26
Reading the query plan
1
u/shiningmatcha Sep 17 '26
Indexing based on access patterns
1
u/lalaluna05 Sep 17 '26
OPENQUERY. We frequently query across servers and this has sped it up significantly. I can query tables on another server then pull across only what I need and store it in a temp table.
1
u/Kingingu Sep 18 '26
filter early in cte before u join data
1
u/regal_ethereal7 Sep 18 '26
My team have had some significant performance improvements in recent weeks by applying some basic practice to be honest.
Rebuilding statistics on a large fact table after a rebuild.
In Synapse, changing a dim table distribution to REPLICATE so it exists in full on each node removed unnecessary data shuffle operations and reduced execution time by over 1000%.
1
u/Thatgiuknow Sep 18 '26
Can't go wrong with CTEs or Views. Recently inherited some projects at work that were mighty lengthy and am ever appreciative that they are structured will using these when applicable. When you don't have to create a whole new table's worth of data, then don't saves you a ton of time.
1
u/Streamer_Fenwick Sep 20 '26
Materialize cte or Materialized views postgres
1
u/Fine-Thanks-9905 Oct 03 '26
Most of the top answers here are really 'the index did it' lol. If you want the why: B+ trees stay wide and shallow so any lookup is 3-4 disk reads, and the linked leaves make range scans cheap. Made a 2 min animated explainer on how B-tree indexes actually work: https://www.youtube.com/shorts/HGNc4SrsSOE
1
u/Lost_Term_8080 Sep 16 '26
There are no "tricks," every optimization has to be the correct optimization.
Generally always start with indexing, then go on to either server level tuning or query tuning, but mediocre or poorly designed indexes won't be very effective at best, and may directly make performance worse at worst
-2
u/KanadaKid19 Sep 17 '26
Materialized CTEs have been a magic bullet in a few cases for me. No temp tables for me, thanks.