Why would someone use WHERE 1=1 AND
in a SQL clause (Either SQL obtained through concatenated strings, either view definition)
I\'ve
Why would someone use WHERE 1=1 AND
I've seen homespun frameworks do stuff like this (blush), as this allows lazy parsing practices to be applied to both the WHERE
and AND
Sql keywords.
For example (I'm using C# as an example here), consider the conditional parsing of the following predicates in a Sql query string builder
:
var sqlQuery = "SELECT * FROM FOOS WHERE 1 = 1"
if (shouldFilterForBars)
{
sqlQuery = sqlQuery + " AND Bars > 3";
}
if (shouldFilterForBaz)
{
sqlQuery = sqlQuery + " AND Baz < 12";
}
The "benefit" of WHERE 1 = 1
means that no special code is needed:
AND
is required. Since we already have at least one predicate with the 1 = 1
, it means AND
is always OK.WHERE
must be dropped. But again, we can be lazy, because we are again guarantee of at least one predicate.This is obviously a bad idea and would recommend using an established data access framework or ORM for parsing optional and conditional predicates in this way.