18

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?

40

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. – ern0 Jan 25 '11 at 11:07
  • 3
    it'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. – araqnid Jan 26 '11 at 1:58
  • 1
    I'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. – Avery Payne Sep 13 '12 at 23:33
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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.