8

Possible Duplicate:
Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

I am working on a code base that often has

where 1=1

Often, these queries are complex and difficult to read. So it's not always feasible to break down the query semantics purely for a refactor. My gut instinct is that this is always unecessary. Maybe there exists a requirement for a where clause similar to the requirement for a Group By clause when performing a SELECT with an aggregrate function alongside some column to group.

Is there ever a need for this?

Community
  • 1
  • 1
P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
  • 4
    Yes, it is very useful with sql injection prone web sites ;) – vc 74 Dec 02 '11 at 16:44
  • I've seen this exact question on SO once or twice, might want to pay more attention to the list of suggested questions that comes up when you type in your question title. – Bill K Dec 02 '11 at 16:46
  • where 1=1 is a 100% TRUE statement., so whatever you have in the SELECT statement will be returned no matter what if it has rows or not. – Shankar Narayana Damodaran Dec 02 '11 at 16:47

5 Answers5

16

It makes building dynamic WHERE clauses easier...

WHERE
  1=1
  AND condition1
  AND condition2

This way you don't have to work out if you need the AND or not as you add conditions. You always need the AND.

MatBailie
  • 83,401
  • 18
  • 103
  • 137
2

I've seen that done so that when building dynamic queries you didn't have to have to know where to start the AND clause since everything was after WHERE 1=1

hunter
  • 62,308
  • 19
  • 113
  • 113
2

Its useful if you dynamically add restrictions to your SQL, that way you never have to care about the 'WHERE' keyword and can use 'AND' at the beginning of every part where you add a restriction. (If you want I can code a small example explaining it.)

So, yeah, there are legit uses of 1=1.

Angelo Fuchs
  • 9,825
  • 1
  • 35
  • 72
1

I think it has something to do with being able to write long WHERE clauses without having to think about spurious AND statements. In other words it's just there to make the code look nicer. Pretty sure that gets optimized out. However if there's an OR in front, that's the smell of SQL injection :)

SELECT
...
WHERE 1=1
AND COND
AND ANOTHERCOND
AND THIRDCOND
-- AND COMMENTEDOUT
AND FIFTHCOND
Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
1

Most of the case developers using it for ease of commenting where conditions

Manoj
  • 19
  • 2