r/SQL • u/shdw_0x0 • Sep 07 '26
PostgreSQL When does SQL become too clever?
I’ve noticed that as queries get more complex, there’s often a temptation to keep everything inside SQL—CTEs, window functions, nested subqueries, conditional logic, etc. It can be impressive, but at some point the query becomes harder to understand than the original problem.
Where do you personally draw the line? Is a 300-line SQL query perfectly fine if it’s well structured, or do you prefer moving some of the logic into dbt/Python/application code once the SQL becomes too complex?
I’m curious how others balance SQL performance, readability, and maintainability in real projects.
14
u/WBT67 Sep 07 '26
Nothing more annoying than inheriting someone else’s “clever” SQL; simple and readable beats clever
5
u/big_poppa_man Sep 07 '26
Personally I like CTEs. I do not like nested sub queries as that quickly becomes unreadable.
5
u/alinroc SQL Server DBA Sep 07 '26
I think this bot forgot that it already asked this question 4 days ago. https://old.reddit.com/r/SQL/comments/1w674y9/when_does_a_sql_query_become_too_clever/
2
u/Glitch_In_The_Data Sep 07 '26
When you can’t understand what it does
2
u/Last0dyssey Sep 07 '26
I prefer temp tables over CTEs. Easier to debug, read, and validate imo. As long as I can follow your logic and you have clearly labeled steps and comments then it's fine.
1
u/jeffcgroves Sep 07 '26
Possibly helpful link to PL/SQL: https://en.wikipedia.org/wiki/PL/SQL
1
u/TheGr8Tate Sep 07 '26
I'm working with Databricks and I've seen and even created myself SQL scripts with multiple thousand lines (biggest script had 3.5k lines).
Readability and maintainability are very subjective. I personally prefer short scripts and I keep them short by moving repeated logic into SQL/Python UDFs and Python string manipulation via Pyspark. I have colleagues who actually prefer the big scripts (which is the reason why I even have created those monstrosities in the first place)...
1
u/fraser_altimate Oct 23 '26
300 lines is fine if each cte has one job and a clear grain. it's too clever when you can't tell a cte's grain from its name. quick test: run each cte alone and check the row count. if you can't predict it, split it. in dbt, power user runs any cte with a row count from a button (i work on it)