Re:SQL Tips and Tricks
by egeozcan on Wednesday September 25, 2024 @01:24AM
(#41643945)
I remember doing the "WHERE 1=1" trick in my last job and it causing a... let's say "unproductive", discussion in the pull-request.
[ Parent
| on HN ]
What about `WHERE true`?
Re:SQL Tips and Tricks
by abrookewood on Wednesday September 25, 2024 @04:06AM
(#41644953)
I don't understand the point at all. If you need to add some condition later on, why not just add it then? What benefit is there to just marking out the spot where you might add the condition at some point in the future?
It is a bit silly but I think it just helps with code readability some people.
I personally don't use it too, but I think it's origins are not just readability, but from developing queries in a REPL like environment.
As you develop and are constantly creating / debugging queries where you often add new and or or clauses as a whole line, that becomes much faster to add and remove those same lines as they're a single shortcut away in nearly all text editors.
Re:SQL Tips and Tricks
by paperplatter on Wednesday September 25, 2024 @12:16PM
(#41649021)
Yeah, so often do I have an EXPLAIN ANALYZE query.txt file I'm repeatedly editing in one window and piping into psql in another to try and make something faster. So I put WHERE true at the top.
For their one here it's just the ability to rapidly comment/uncomment conditions in a query editor while exploring the data or debugging the query, and not having to worry about the leading AND or OR.
I've also seen it in code with iterative adds, for example:
for crit in criteria:
sql += " AND " + crit
No needed to add a sentinel or other logic to skip the first AND. I saw it a lot before people got used to " AND ".join(criteria).That's right - it's just a quicker way of being able to comment/uncomment conditions when doing EDA or debugging.
Yeah. Especially when I'm trying to see what makes some query slow.
I believe some database engines can be configured to error if you do that, and 1=1 doesn't trigger the safeguard.