O
6

Rant: My coworker told me my SQL queries were a mess and I hated hearing it

Last month a senior dev pulled me aside after a code review and said my queries were 'spaghetti with extra joins'. I thought I was being efficient by nesting subqueries everywhere but he showed me I was slowing down the database by a good 15-20 percent on our reporting dashboard. He suggested I use CTEs and temp tables instead to break things into clear steps. At first I was annoyed but after I rewrote one query for our quarterly sales report it ran in 3 seconds instead of 12. Has anyone else had someone point out a bad habit you didn't know you had?
2 comments

Log in to join the discussion

Log In
2 Comments
olivia_allen
Did you ever push back on the CTE suggestion at first? I was exactly the same way. I used to think nested subqueries looked clever and compact, like showing off. But then I timed one of my reports against a coworker's version that used CTEs and mine took 8 seconds longer on a simple monthly data pull. That shut me up real fast. I still write messy stuff sometimes but I always refactor it now before anyone sees it.
6
jenny_coleman
Read somewhere that SQL Server actually processes CTEs differently under the hood compared to subqueries. Something about how the optimizer can materialize the CTE result set which sometimes lets it reuse data instead of recalculating everything. Made me realize those 8 seconds you saw weren't just about readability.
1