Is there a logical reason to use 1 = 1 in the where clause?

Possible duplicate:
Why does someone use WHERE 1 = 1 AND <conditions> in an SQL statement?

I am working on a code base that often has

where 1=1

Often these queries are complex and difficult to read. Therefore, it is not always possible to break the semantics of a query solely into refactoring. My gut instinct is that it is always necessary. There may be a requirement for the where clause, similar to the requirement for the Group By SELECT when executing a SELECT with an aggregation function next to some column for grouping.

Is there a need for this?

+8
sql
source share
5 answers

This makes it easy to create dynamic WHERE clauses ...

 WHERE 1=1 AND condition1 AND condition2 

This way you don't need to work if you need AND or not when you add conditions. You always need AND.

+16
source share

I saw that this was done so that when building dynamic queries you do not need to know where to start the AND clause, since everything was after WHERE 1=1

+2
source share

Useful if you dynamically add constraints to your SQL, so you never have to worry about the β€œWHERE” keyword and use β€œAND” at the beginning of each part where you add the constraint. (If you want, I can write a small example explaining this.)

So yes, there is a legitimate use of 1 = 1.

+2
source share

I think this has something to do with writing long WHERE clauses without thinking about false AND statements. In other words, it's just to make the code look better. Pretty sure it's optimized. However, if there is OR ahead, then the smell of SQL injection :)

 SELECT ... WHERE 1=1 AND COND AND ANOTHERCOND AND THIRDCOND -- AND COMMENTEDOUT AND FIFTHCOND 
+1
source share

Most application developers use it for convenience of commenting, where conditions

+1
source share

All Articles