I came across a view in our database today where the first statement in the where clause was where 1 = 1
. Shouldn't this return true for every record? Why would someone write this if it isn't filtering any records?
-
Answered here: dba.stackexchange.com/questions/667/…– GaiusCommented Jan 21, 2011 at 17:43
-
3Because they want to hack sombodys website ;-)– Tim SchmelterCommented Jan 22, 2011 at 0:12
4 Answers
Some dynamic query builders include this condition so that any "real" conditions can be added with an AND
without doing a check like if (first condition) 'WHERE' else 'AND'
.
-
It sounds strange that a query builder can't determine wheter a condition is the first in a line, but I think also, you're right.– ern0Commented Jan 25, 2011 at 11:07
-
3it's often the case when the "query builder" is someone writing code to concatenate onto the SQL statement by hand. sometimes introducing a more formal query building library eliminates it.– araqnidCommented Jan 26, 2011 at 1:58
-
1I've had to deal with "old" code like this, and it's very true. When you're assembling the entire SQL statement into a single string, there will be bunches of if/then or case statements that may or may not trigger. Because you never know if any of those code paths are taken, BUT you have an AND embedded in your WHERE clause (due to a clause that is consistently part of the string), you need to either (a) remove the offending AND or (b) simply pass it a logical truism. Adding "1=1" is easier than redacting the string correctly. Commented Sep 13, 2012 at 23:33
If you have many SQL statement building points in your program which generate similar queries, you can mark the examined one by this trick. If the sentence is about counting, you may use code below so you can grep out 42
from a SQL log.
select count(42) from table
It provides a situation that is always true, so it doesn't affect the results, but you know there is one item in the WHERE clause already.
It helps me with my test queries that I use often and have multiple condition that I add and remove
Note in oracle you can comment a line with --
SELECT
tablea.*,
--tableb.*,
tablec.*
from dual
,tablea
--,tableb
,tablec
where 1=1
--and tablea.a = tableb.a
and tablea.a = tablec.a
and tablea = :value
I can easily add or remove tableb from the query