Article originally published here : https://alsohelp.com/blog/where-one-equals-one-in-sql
After more than 5 years of writing SQL, I found this thing in a colleague's code.
At first, I didn’t see the point.
Juniors are often baffled when they see this condition in their colleagues’ code.
(Personally, the first time I saw it, I thought it was some trick to optimize a join’s performance in certain conditions...)
In reality, it’s just a handy tip.
It’s used to quickly test query results with and without certain conditions.
Here, if we wanted to test the query without the condition work = 'c-level', we’d have to move degree = 'master' next to WHERE (and remove the AND keyword).
That’s tedious...
The 1=1 trick simply avoids that, saving a bit of time when testing queries. :)
SELECT *
FROM people
WHERE 1 = 1
-- AND degree="master"
AND work="c-level"
Top comments (2)
Personally, I use "WHERE 1=1" in embedded SQL all the time. Reason, I often build SQL statements inline depending on query params, user selected values, ...
It's much easier to test a condition and append an "and =". Otherwise, I'd need to determine if this is the first and requires the "WHERE" or not and gets an "AND".
Just FYI, we roll with TRUE too—yeah, one extra char, but whatevs :-P