Why use WHERE 1 or WHERE 1=1?

Basically it is just for programmer convenience since you can just add additional conditions with AND... after that and it has no impact on execution time.

Check out these links to Stackoverflow:

  • Why would someone use WHERE 1=1 AND in a SQL clause?
  • “where 1=1” statement

Note that WHERE 1 is identical to WHERE 1=1; both mean WHERE TRUE but the former is rejected by many database management systems as not really being boolean.


My main use is that it makes it easier to comment out stuff during development of queries. I lead with ,'s and and's:

SELECT
     A
--  ,B
    ,C
    ,D
--  ,E
FROM TABLE
WHERE 1=1
--  and B='This'
    and C='That'
--  and D is not null

Also makes it easier to programmatically tack stuff unto the end.

this  = "SELECT * "
this += "FROM TABLE "
this += "WHERE 1=1 "
if user chooses option a then this += "and A is not null "
if user chooses option b then this += "and B is not null "
if user chooses option b then this += "and C is not null "
if user chooses option b then this += "and D is not null "

Otherwise you'd have to qualify the first option... and have each following option check the previous options. What if the user only chose Option D in the previous example? You'd have to make sure that if A, B and C aren't chosen then use WHERE else use and. With = at the start, you can just slap the qualifiers to the end of the statement.


Why we do so?

Dynamic code generation written by not too competent programmers comes to my mind.

Generates SELECT.... WHERE and then you have to have SOMETHING.... so instead of adding the WHERE only when needed, they add a non-limiting condition when none is there. Seen that - responsible for firing the "specialist".

Or the guy just things WHERE is mandatory ;)

Anything else I fail to see.

Tags:

Mysql 5.1