r/learnSQL • • 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.

7 Upvotes

7 comments sorted by

5

u/Ok_Knowledge2026 17h ago

SQL is an engine. Checkout Brent Ozar and Erik Darling

4

u/BobDogGo 16h ago

Brent Ozar is a great resource and his query tuning classes were worth the expense 

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/AnnaLeeCoop 6h ago

Turning on Actual Execution Plans (Ctrl+M in SSMS) and SET STATISTICS IO ON for 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 your ROW_NUMBER() script, the ORDER BY inside OVER() just decides which duplicate gets labeled 1, 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.