People use it because they're inherently lazy when building dynamic SQL queries. If you start with a "where 1 = 1"
then all your extra clauses just start with "and"
and you don't have to figure out.
Not that there's anything wrong with being inherently lazy. I've seen doubly-linked lists where an "empty" list consists of two sentinel nodes and you start processing at the first->next
up until last->prev
inclusive.
This actually removed all the special handling code for deleting first
and last
nodes. In this set-up, every node was a middle node since you weren't able to delete first
or last
. Two nodes were wasted but the code was simpler and (ever so slightly) faster.
The only other place I've ever seen the "1 = 1" construct is in BIRT. Reports often use positional parameters and are modified with Javascript to allow all values. So the query:
select * from tbl where col = ?
when the user selects "*"
for the parameter being used for col
is modified to read:
select * from tbl where ((col = ?) or (1 = 1))
This allows the new query to be used without fiddling around with the positional parameter details. There's still exactly one such parameter. Any decent DBMS (e.g., DB2/z) will optimize that query to basically remove the clause entirely before trying to construct an execution plan, so there's no trade-off.