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?
Asked
Active
Viewed 7,374 times
19
goric
- 1,646
- 3
- 18
- 25
4 Answers
41
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'.
BenV
- 4,923
- 7
- 40
- 38
5
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
H. Pauwelyn
- 930
- 6
- 18
- 35
ern0
- 151
- 3
4
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.
SchwartzE
- 339
- 1
- 7
0
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
Marc
- 1