r/SQLServer • u/sanjay-kumar_ • Dec 09 '25
Discussion SQL Server performance tips beyond indexing? What actually makes a difference?
Hey everyone, I've been working with SQL Server for a while now (Nearly Two Years) and I keep hearing "just add an index" whenever queries run slow. (Especially when the table has few millions records or few Billions Records) But there's gotta be more to it than that, right?
What are some GOOD practices that actually speed things up? I'm talking about stuff that makes a real difference in production environments.
And what are the BAD practices I should avoid? Like, what are the things people do that absolutely kill performance without realizing it?
Also, if you've got experience with query tuning, what's something you wish you knew earlier? Any gotchas or common mistakes to watch out for?
I'm trying to level up my database game, so any advice from folks who've been in the trenches would be really helpful.
Teach me every thing possible as you teach and explain to a complete stranger.
Real-world examples are appreciated more than textbook answers!
Thanks in advance!
•
u/AutoModerator Dec 09 '25
After your question has been solved /u/sanjay-kumar_, please reply to the helpful user's comment with the phrase "Solution verified".
This will not only award a point to the contributor for their assistance but also update the post's flair to "Solved".
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
59
u/SQLDevDBA 3 Dec 09 '25 edited Dec 09 '25
I would start with Brent Ozar’s how to think like the engine series.
https://BrentOzar.com/go/engine
And then move into the Blitz package
https://brentozar.com/go/first-aid
It’s the most comprehensive start you’ll get, then you can move into areas where you feel it’s pertinent with resources like Erik Darling, Kendra Little, etc.
37
u/_mattmc3_ Dec 09 '25 edited Dec 09 '25
I'll leave it to others to share all the great Brent Ozar tips, indexing tips, fragmentation tips, hardware and disk layout tips - all these are essential and impactful and I could probably also go on all day about them. But once those are exhausted, the real world performance gains I've gotten are simple query and table design optimizations.
Even in shops with good DBAs and competent devs, people still do really dumb things in their queries. Here are my 4 Horsemen of the Query Apocalypse:
My first question is often - what does the execution plan say? SQL is really dumb (in the best way). What I mean by that is the way it answers your query is typically the way you would have guessed - it's rarely clever. If it isn't doing what you would have guessed, there's a good chance it's wrong and then learning how to make it right is most of the tuning effort.
Honorable mention goes to "improper/unnecessary use of DISTINCT". Use of DISTINCT is often a code smell in SQL that is used to smooth over misunderstandings of cardinality, bad table design, or poor understanding of results.
6
u/TheGenericUser0815 1 Dec 09 '25
There is the old saying "Database tuning is SQL tuning is SQL tuning is SQL tuning". Which is mostly true, but there are other factors like:
Do:
- fast storage so I/O is fast(er), especially important for db log files
- enough RAM for the instance, how much that is, depends on the requirements of the application, Express edition is limted!
- enough CPU for sort and calc, Express edition is limited to one socket (!)
- enough temp-db files and big enough temp db files
- keeping db statistics up to date, that's where the optimizer gets it's data from. This sould be a daily or weekl job
- setting recovery model to simple, where full logging is not required
- sizing of db files: better they are bigger and have 40-50% free space than too small and automatic growth fragments the files
Avoid:
- running db in compatibility mode to older versions where it's not required by the application
- using Express edition where more ressources are required
- shrinking db files on a regualar basis
As you asked for real life examples: what your database needs is so much dependent on your application, that there are no general recommendations regarding sizing and other ressources.
5
u/shine_on Dec 09 '25
With large tables, choosing the right data type for each column can make a big difference, even going from int to smallint or tinyint saves 2 or 3 bytes per row. Don't overdo the length of a varchar column, it can mess up SQL Server's memory estimates for a query. Don't include unnecessary columns in an index.
I've often found queries will run quicker if they're refactored into smaller units of work. Try not to have several layers of nested subqueries.
Avoid wildcard searches, and non-SARGable where clauses.
6
u/Hairy-Ad-4018 Dec 09 '25
Before doing anything , have you checked that costing indexes have a low fragmentation and that statistics are up to date ?
Have you reviewed the query execution plan to determine if an existing index is being used ? If the sp is efficient ?
Is there parameter sniffing ?
Is the table accidentally a heap table ? Is there a clustered index with an incrementing value ?
What is the page life expectancy value and how is it changing during the day ?
What is the disk I/o ? Measure during the day
Have you organised data into logical /physical drives so that data commonly read together are on the same disk?
Separate disk for tempdb?
Separate disk for the os
Sufficient memory ? What degree of parallelism is set?
Do sps have lock hints( you may be able to remove)
Etc etc
2
u/alexwh68 Dec 09 '25
Understand disks, specifically in relation to data and log files, logs files write sequentially, data files are read randomly, these days with solid state storage its less a problem but with older disk types mixing heavy sequential and random access on the same disks could cause bottlenecks. Looking at disk queue lengths and making sure they are low is key.
Back to indexes, its not just about indexing stuff so you are seeking data not scanning for it in big tables, sometimes the win is getting all the data you need from the index and not the data files, covering indexes can produce good gains here.
Keeping statistics up to date on systems where there is a lot of data being moved around can help, and as others have said index fragmentation is something to keep an eye on.
Understanding query plans is important.
You can have too many indexes on write heavy systems, keep your indexes under review, don’t just create them and leave them alone, review their usage.
2
u/Bright-Complex-5753 Dec 09 '25
Does the above apply to Azure SQL as well? Any specific resource for Azure SQL.
1
u/lanky_doodle 1 Dec 09 '25
Are you looking at this purely from a SQL engine performance pov (indexes, query, sprocs etc.)?
Are you happy with your SQL Server and parent OS hardware and software architecture principles?
I can help much less with the first one and much more with the second.
3
u/mcintg Dec 09 '25
Running stats is often more effective than index optimisation
2
u/voltswagner Dec 10 '25
I’m a sql novice. It’s my understanding that creating views can speed up queries by simplifying queries (moving complexity to the view).
Are views created to speed up queries?
Is this so basic that’s why nobody mentioned it?
2
u/bmaday12 Dec 11 '25
Have you explored settings related to parallelism? Having the right values for "Cost of Threshold" and "Max Degree of Parallelism" can make a huge difference.
2
u/agiamba Dec 16 '25
Good practices-
Audit queries with Query Store and other tools like Brent Ozar's scripts to see whats run most frequently and how they can be improved
Bad practices-
Years ago, I did an hour long presentation on how to keep your DB trim and performant: https://www.youtube.com/watch?v=lcgS7II5vQ8&list=FLEdp4QnRYl3U_6OK1rohf0Q I speak to the product I work on, but it's really applicable to any SQL Server DB and it's quite accessible. May be worth a watch
1
u/ElvisArcher Dec 09 '25
User defined functions. Syntactically you can create single-statement or multi-statement user defined functions, but you should try hard to never create and use a multi-statement user defined function.
Use of a multi-statement user defined function blocks the query analyzer from a proper analysis of how to proceed, so it always chooses the slowest (but most robust) method.
* Take with a grain of salt ... its been about a decade since I last worked with Sql Server and things may have changed.
** As a software engineer, you should always defer to the resident Sql expert(s) when tuning. They've forgotten more than you will ever know on the subject.
*** If you don't have a resident Sql expert, try to make some friends over at sqlservercentral. And if anybody mentions DBCC TIMEWARP, you can trust that (a) they might know what they are talking about, and (b) they have a sense of humor.
1
u/g3n3 Dec 09 '25
Perf for what? Selects? I mean how much memory you got? How can you get to the key with a b-tree? Put all db in memory and have a query return one row and seek on the key. Now you are super fast…oh you want to return 100,000 rows or more to the client? Oh, oh…well good luck…try pagination…
1
u/imk Dec 09 '25
I have a Personnel system that I made which a colleague wanted to add payroll records to. He took the records from a download from another older system. The records were badly in need of reformatting and a bunch of other things. He handled these needs by creating a query which included all the various functions that cleaned up the data and made it usable.
That query slowed my app down enormously. When I saw the query that he had written, I flipped. Payroll records are pretty static, so the obvious answer was to get the records from the other system, then do all the reformatting and clean-up in one go and then stick that data in another table. Then you can index the cleaned up data. I did that extra step and then it flew.
I work in humble surroundings. My experience is that there is a lot that you need to look at before you even get to things like indexing. You got to give the SQL Server Engine the chance to do its thing. You can't have every field in a query having FORMAT or LEFT(RIGHT()) and similar. Some times you have to take measures.
1
u/kartmanden Dec 09 '25
This helped me at some point:
https://learn.microsoft.com/en-us/sql/relational-databases/indexes/columnstore-indexes-overview?view=sql-server-ver17
1
u/Lost_Term_8080 Dec 09 '25
Few really common recommendations already posted. Here are some more antipatterns:
Too many indexes are bad; each index adds writing and locking overhead. A very basic guideline is to not to create more than 5 indexes that are more than 5 columns wide. Columns in an index should not be wider than 200 bytes - and preferably less. You will frequently need more but if you are facing a performance issue that is creating other performance issues you will know whether the index was medicine or poison. With really well-designed indexes you can go higher than this but you will need experience to get there.
Reorganizing indexes is almost always bad: If you are on enterprise edition, its always bad. The only case reorgs help are in organizations that use SQL standard with large indexes and no maintenance window long enough to rebuild them offline and an application that is sensitive to page density that the reorg can mitigate. These combination of factors is an edge case. Otherwise if you are reorganizing you are making your performance worse.
Rebuilding indexes is usually bad: SQL Server last only somewhat cared about logical fragmentation since SQL 2000. Low page density can be a problem, but this accumulates slowly over time. If you get a performance increase from an index rebuild, it is almost certainly because of the statistics updates that came with the rebuild as a side effect, not the rebuild itself.
CTEs are not magic and using them without reason can introduce major performance problems. CTEs can be very powerful for performance and functionality, but they don't inherently improve performance on their own, the design of the query is what improves performance. If you don't have a technical reason to use one, don't use it. Visual appeal of code is not a valid reason to implement CTEs; At certain scales, CTEs can reach a tipping point where adding just one more join or one more column to an existing query, or even a tip in data distribution, can very suddenly cause a major performance regression. Excessive use of CTEs is very quickly becoming the new NOLOCK "trick" of novice SQL developers.
Business Logic goes in the application, not the database. SQL is good at filtering, aggregating and sorting. Heavy conditional logic, loops, etc will use up a lot of SQL resources not only impacting itself, but also impact the rest of the server.
1
u/gevorgter Dec 09 '25
my main advice is to learn to see and understand Estimated Execution Plan (Cntrl+L)
1
u/Barsonax Dec 10 '25
Avoid over fetching. Only select what you need.
1
u/willyam3b Dec 11 '25
Over-indexing. It's so incredibly common as I've moved around picking up legacy databases. I seem to see it a bunch when dealing with someone who ported something over from Oracle, etc. Or, more often, an entire team of people in the comments over years. The most common thing people know is "index speeds things up" so they get added. And then another. And another. Suddenly that OLTP becomes twice as big as it needs to be, then you see reporting queries that run once a month getting index objects specific to their single run. As mentioned below the Brent Ozar's SQLblitz will show all of that really well. Sometimes EMBARASSINGLY well lol. Every object that's part of a table also gets updated when that table does, and I've run across 15+ indexes on one hotspot table. It happens.
1
u/Thespck Dec 11 '25
Not sure why I haven’t seen this, but something very important that people miss are the primary joins. I just changed all major joins from DateAssetID as varchar(200) to INT. We used to join “2025-12-11-123456” per row with multiple joins, now the join executes on INT = INT (20251211123456” and also we perform major merges on hashes rather than checking over every column. Whenever you can, make the primary key an INT.
1
u/slash_gnr3k Dec 11 '25 edited Dec 11 '25
The biggest performance killer I see is always the quality of queries:
-Table variables
-Scalar Functions
-MSTVFs
-Non sargable predicates
-Doing CPU heavy stuff like Shredding JSON or a case statement trying to parse free text
-Weird join clauses using ORs, functions, likes
-Correlated subqueries
-Queries which are just massive - like thousands of lines in length which the optimiser has no chance of coming up with a decent execution plan for
-Stacked CTEs
-Reusing CTEs
-Linked server queries
-Nested views containing complex code
-Queries which should really be broken down into a few simpler queries
-Queries selecting full tables
-Left joins on 1=1
-Cross joins
And many weird things
Obviously there are other things that affect performance but I'd say poorly written queries are usually the biggest bottleneck
Also, performance is relative, some developers will write a query and say "it only takes two seconds to run" in isolation that is fine but if that query is to run thousands of times a minute, that accumulates CPU and bring an instance to a crawl
0
u/Outrageous-Fruit3912 Dec 09 '25
Check out the hallengree pot plans