r/SQL • u/No_Ambition8323 • Sep 03 '26
Discussion When does a SQL query become “too clever”?
I’ve come across queries that are extremely compact and technically efficient, but difficult for someone else to understand or modify later.
For example, a query might use nested window functions, multiple conditional expressions, and several transformations to solve something that could also be written as a few simpler steps.
Where do you personally draw the line between elegant SQL and over-engineered SQL?
Do you prioritize fewer lines, query performance, or maintainability when these three goals conflict?
52
Upvotes
128
u/Final-Quote-4064 Sep 03 '26
When you can't fix it
44
u/WheresTheSauce Sep 03 '26
Kind of subjective I guess, but if it takes longer to read than if it were a longer query
30
u/suubterr Sep 03 '26
When the purpose is obfuscated.
20
u/Wuthering_depths Sep 03 '26 edited Sep 03 '26
With the caveat that this is mainly only possible in stored procs or custom scripts--I usually will much prefer to break things up into pieces that I can run one bit at a time while troubleshooting. Use temp or real tables, populate and update those as you go. It may not be the most efficient, certainly not as fancy and impressive as one big query with lots of subqueries, but efficiency may not be quite the most important if it's say something that runs once overnight. ie, taking 20 seconds to run instead of 10 wouldn't bother me if it means that people can quickly maintain it and troubleshoot it later.
And to be fair, I've never noticed a big drop in speed anyway when using this approach, there's generally ways to get things working well if it's possible at all given the data.
I used to butt heads with another senior data person about this...to him, it was all about sparse efficiency at the cost of making it completely arcane to someone else coming in (from my way of thinking at least).
13
u/Jazzlike_Drawing_139 Sep 03 '26
Number of lines is far lower a priority than maintainability.
There’s no benefit to having a ‘clever’ compact query that is hard to understand quickly over a longer, well structured and commented query that means :
- others can understand what the query is doing (and why)
- if troubleshooting is required, the fixer can quickly identify and resolve the issue.
Query performance should be considered and prioritised proportionately, but has almost nothing to do with the number of lines. Again, if performance becomes an issue down the line, a well structured query will hugely help with optimising and identifying indexes.
7
u/Lurking_all_the_time Sep 03 '26
When it become more important to look cool/use cool keywords / logic over speed and maintainability.
Every bit of code is different, but if your code looks good, but is inefficient, it's too clever for it's own good.
6
u/oskaremil Sep 03 '26
When no-one wants to touch it.
6
u/DAVENP0RT Sep 03 '26
A DBA at my company made a schema-bound view with a unique constraint that negates a condition amongst three tables. Basically, it makes it so that you cannot insert a record into two tables if another record exists in another table, but only if certain values are present. The whole thing is only about 25 lines, but the first time I saw it, I stared at it for about 15 minutes just trying to make sense of it. Works great, though.
5
u/csjpsoft Sep 04 '26
I had a boss who loved to nest "where not exists" inside other "where not exists" - sometime 3 or 4 levels deep. That is not an unbad practice.
4
u/Justbehind Sep 03 '26
"Clever" queries rarely perform well. The optimizer looooves simplicity.
4
u/imtheorangeycenter Sep 04 '26
Writing code is hard
Debugging harder
Debugging someone else's code the hardest
3
u/Novida Sep 03 '26
I've wrote a couple where I finished with about 1am and would probably need to go back to 1am trying to figure it out again
3
u/rbobby Sep 03 '26 edited Sep 03 '26
Pick the coworker who you think generally doesn't do the job as well as you, or maybe even someone just barely hanging on to their job due to competency issues (not fired, but god only knows why... maybe a bit north of that). That's the person that has to understand the query. If you think your coworker will understand it in 12 months, when a subtle bug is found, then the query is not to clever.
Now you might say that I've picked a terrible standard... but I haven't. If your query is to complicated for him, then any normal maintenance task that ought to fall to him now falls to you. Forever. You now own this query until the day you leave. How clever do you think that is? Every time someone thinks about moving you into something new their thoughts will land on the clever queries and how tough things will be without you. You know what, Bob is the man for that directorship and we'll get someone to help a bit with your queries. Just the thing.
:)
3
u/Sexy_Koala_Juice DuckDB Sep 04 '26
When you start having to write detailed notes about parts of the query, because you’re doing some insane transformation using very niche syntax
3
u/Practical-Split4340 Sep 04 '26
I always prioritize maintainabiity over everything else unless there is a specific requirement otherwise.
2
u/spez_eats_nazi_ass Sep 03 '26
When the optimizer creates a query plan that is shit.
2
u/az987654 Sep 03 '26
I draw the line at "is this accurate #1, and is it as efficient as possible"
I don't care if it's 1 line to 2,000 lines.
Does it work, and does it have the proper indices, stats, plans, etc. to return as efficiently as possible.
2
u/HarveyDentBeliever Sep 03 '26
It's easier to do this the other way around. Start with the simplest/trivial solution and only increment complexity as needed.
2
u/TheLastRaza Sep 03 '26
when the next person to touch it can't tell you what it does without studying it for 20 minutes. if someone has to trace through nested subqueries and window functions just to confirm the numbers are right, you've gone past clever into fragile territory. in finance systems that's a real problem because queries get reused as templates, small changes break assumptions buried three layers deep, and nobody wants to be the person who can't explain how a report was built when the auditor asks. write it so a tired colleague at 5pm on a friday can still read it.
2
u/decrementsf Sep 03 '26
When the team members you would hand off to cannot understand it and make mistakes, that's when you return to simpler methods to do the same thing. Anecdotally have seen cycles of skill development with a couple tools where first got repetition to grow comfort in the tool, then became more advanced intuitively with that tool, and then the third level up was returning to simpler methods again when recognizing the time spent explaining what the solution did.
2
u/DaOgDuneamouse Sep 03 '26
It really just depends. I've written queries that were esoteric and may be hard to maintain but it needed to be that way. I've also had to rewrite a whole query because the other developer way over engineered it. The choice really comes down to a judgement call.
2
u/sandrrawrr Sep 03 '26
I make it a triangle of
The closer you get to those three branches, the more elegant your code will be, but I also believe that elegant code is something that anyone can pick up and make some minor fixes, while leaving the majority of the structure alone.
2
u/venkat_deepsql Sep 04 '26
When you don't understand the execution plans
2
u/znottaken Sep 06 '26
Making a query smaller without improving performance isn't worth it in my opinion. For the same reason, I dislike using alias/shortened cmdlets and variables in powershell.
3
u/kagato87 MS SQL Sep 03 '26
Performance first, maintainability second.
Number of lines is a "who cares?" Factor. I don't care how many pages it is, I care how it reads.
The query planner changes the execution anyway. And if yire "clever" you might lead it away from a better plan.
2
u/Philluminati Sep 03 '26
I work in a data engineering team who do vast "cleaning" of data by chaining SQL together, creating intermediate tables in the interim.
For instance:
create view dedupedCustomers as (select distinct(uuid), ... from customers group by uuid)create materialized view dedupedActiveCustomers as (select * from dedupedCustomers where lastActive > now() - THRESHOLD)create table dedupedActiveCustomersWithEmail....It's a very powerful technique you could try exploring yourself.
2
u/TeaEarlGrayHotSauce Sep 03 '26
AI is at a point where it can detangle these queries pretty well, I don’t really see this as an issue really if the query is performant
1
u/Glitch_In_The_Data Sep 03 '26
When it sees the poorly written query and just sends a link to the tutorial..
1
u/CaptSprinkls Sep 03 '26
Idk if mine is too clever or the opposite. But I have one I wrote like 2 years ago that is built to be used by an SSRS reports that needs to be exactly 10 columns wide that then repeats for like ~250 or so items. The problem is that a new item might be added at any point so the item list isn't static. Also with the limitations of SSRS, I need to have a column in my query to group on and a row to group on. Oh and also the items are ordered, but an item could be and a lot of the times is inserted in between two numbers. So its not always just a new item appended at the end after ordering.
Anyways, I have to do some annoying math where I take the floor of the row number and multiply by the max number of items and so on and so forth in order to calculate these totals. But whenever I look back at it, I have to state at it for like 10 minutes yo understand what is happening.
I also have to pull in historical monthly data. So I do this up to 12 times and then Union them all so I can also group of that column value in my SSRS report because it all has to fit on one excel workbook with different tabs for each month.
1
u/SELECTaerial Sep 03 '26
When it negatively impacts supportability and maintainability
1
u/fastsvo Sep 03 '26
I haven’t written one in over 10 years but paying attention to the explain plan and the “cost” to the DB when running your query used to be “top of mind” when building one of these.
1
u/Supremagorious Sep 03 '26
It's just about clarity. It's too clever when it takes too much time to parse for any tweaks/updates or to even understand what it's doing and the nuance of what records are and aren't included.
1
u/TheMagarity Sep 03 '26
You're the one who brought it up so please, I need to know, what fewer simpler steps can replace window functions?
1
u/BigFatCoder Sep 03 '26
It works beautifully and you don't understand.
1
u/MobileUser21 Sep 03 '26
It’s completely subjective.
Typically the person who wrote it will challenge you asking you “what’s so difficult about it?” Because of their own pride and ego.
1
u/ThrowAway24Okt Sep 03 '26
you could keep two versions of the same query.
One highly optimized version that utilizes some special properties of the data to achieve fast execution time.
Anther more readable version in case something needs changing.
1
u/aoteoroa Sep 03 '26
How often is it run? A report that is run once a day may not need to by hyper optimized.
A query inside a program that is run a hundred times per second, for example I once wrote a program for an online auction, needs to be optimized for every bit of performance that you can squeeze out of it.
1
u/munoodle Sep 03 '26
If it’s not documented it doesn’t matter how clever it is
1
u/munoodle Sep 03 '26
If it’s not documented it doesn’t matter how clever it is
1
u/GTS_84 Sep 03 '26
For over engineered, when someone spent more time testing it then it will ever spend running.
Don't spend hours tuning a query that is going to run once a month as part of a report. Those need to run well enough, not as perfectly as possible.
1
u/yeahsureYnot Sep 03 '26
The first sentence of this post makes no sense. A.I slop
1
u/imsunchip Sep 04 '26
Problem is not if query was over engineered or not. There was no documentation explaining the code or the why the choice was made, who made it. ALWAYS document.
1
u/RavenCallsCrows Sep 05 '26
Personally, I try to run under the assumption that the next person who looks at the code will not automatically follow my train of thought at the moment it was written. Present-me has confirmed this through reading queries past me wrote.
So, to combat it, there are a combination of things I do:
I absolutely abhor trying to puzzle out someone else's logic after the fact and "see ticket #24601" just makes me want to scream and throw things because it immediately interrupts my workflow and forces me to looking things up in another system, and gods forbid that the company has changed ticketing systems. Same applies to SharePoint/internal wikis etc.
1
u/wdm006 Sep 06 '26
I draw the line when the next person has to reverse engineer the author's cleverness before they can change a filter. Dense window function soup is fine if one person owns it forever, but most queries outlive that person. Three boring CTEs a tired teammate can edit at 5pm every time.
1
u/rakeshchaudhary3434 Sep 07 '26
For me, maintainability wins. A clever query is great until someone else has to debug it six months later. If breaking it into a few clear steps makes it easier to understand without hurting performance much, I’d choose clarity every time.
1
u/pduck820 Sep 09 '26
When it takes you more than a couple of minutes to realize what's going on
1
u/peccator2000 Sep 10 '26
Some queries can become completely incomprehensible if you take the possibility of NULLs into account. That's why I am always happy when I can put a NOT NULL constraint somewhere. Sometimes the NULLs come from something else, like an outer join, though.
1
u/This-Emergency8839 Sep 22 '26
When it's written on the assumption that it'll never need to be amended.
SQL is intended to be easy to read and understand intent by design.