r/learnSQL • u/BigZealousideal9190 • 17h ago
what finally got you from copying old T-SQL patterns to understanding SQL server properly?
I write T-SQL every single day at work. A lot of it I couldn't explain to you.
I have a folder of old scripts I copy from. When I need to dedupe something I grab the ROW_NUMBER() OVER (PARTITION BY ...) one and swap the column names. I could NOT tell you what changes if I mess with the ORDER BY inside the OVER.
A proc that always ran in a couple seconds started taking minutes, with zero code changes. Our DBA said "parameter sniffing," ran a recompile, and it was fast again.
I want to know how SQL Server builds a plan for my query and why it picks a different one some days.
5
u/Ok_Knowledge2026 17h ago
SQL is an engine. Checkout Brent Ozar and Erik Darling
2
u/SQLDevDBA 15h ago
Brent Ozar’s (FREE) how to think like the engine is the perfect starting point.
Here’s the direct page with video and handouts.
https://www.brentozar.com/training/think-like-sql-server-engine/
2
u/Available_Safe1818 10h ago
Why do you care what plan it picks for you? That's different than not knowing what changes happen if you change the query itself.
1
u/Familiar-Shoulder976 17h ago
The order by inside over decides which row gets rn=1 and where rn=1 keeps it. If value ties, SQL server can pick either row, so adding unique ID as a tiebreaker makes the result consistent
1
u/BobDogGo 16h ago
These do a great job of explaining param sniffing and how to fix/avoid it
https://www.sqlshack.com/query-optimization-techniques-in-sql-server-parameter-sniffing/
https://www.brentozar.com/archive/2013/12/recompile-hints-and-execution-plan-caching/
1
u/AnnaLeeCoop 6h ago
Turning on Actual Execution Plans (
Ctrl+Min SSMS) andSET STATISTICS IO ONfor everything I wrote is what finally broke my copy-paste habit. Once you start comparing Estimated vs. Actual row counts on the arrows, parameter sniffing stops feeling like black magic: SQL Server cached a plan built for a parameter that returned 10 rows, then reused it for one that returned 500,000. For yourROW_NUMBER()script, theORDER BYinsideOVER()just decides which duplicate gets labeled1, like keeping the newest timestamp vs. the oldest.And if you want something to make the optimizer click, Brent Ozar's free "How to Think Like the SQL Server Engine" videos helped me more than any textbook did.