6

I'm working with a client that starts almost all of their WHERE clauses in Oracle with 1=1. Forgive my ignorance, but isn't this a no-op? Are there any negative consequences of this usage?

Here's a scrubbed example:

SELECT   gpz.zname
         ,gpp.pname
FROM     table1 gpp INNER JOIN table2 gpz ON gpz.p_id = gpp.p_id
WHERE    1=1
         AND gpp.active = 1
         AND gpz.active = 1
Adam Paynter
  • 46,244
  • 33
  • 149
  • 164
Blanthor
  • 2,568
  • 8
  • 48
  • 66

3 Answers3

21

It's done to simplify dynamic SQL generation. Basically each condition can be added as AND <condition> without treating the first condition as special (it's preceded by WHERE not AND) or even worrying if there should be a WHERE clause at all.

So just write it off as easy of use or, arguably, laziness.

cletus
  • 616,129
  • 168
  • 910
  • 942
  • 1
    +1 for the laziness, simplifying the PL/SQL by one or two lines and inflicting this kind of SQL on the database is pretty poor. Too bad if for some reason they need to set cursor_sharing=FORCE - not sure but I think the CBO would then be confronted with "WHERE :1 = :2 AND..." and optimise it accordingly! Be interesting to find out... – Jeffrey Kemp Jul 02 '09 at 12:59
  • I suspected this to be the case. This client actually has non-dynamic queries like this too. They're really lazy:) – Blanthor Jul 03 '09 at 12:30
  • @JeffreyKemp According to [T-SQL 1=1 Performance Hit](http://stackoverflow.com/q/1049512), the DBMS doesn't take a performance hit by using this pattern. – Danny Beckett Jun 27 '13 at 01:31
  • @Danny I was talking about Oracle. Which, BTW, the OP was too. – Jeffrey Kemp Jun 28 '13 at 06:13
  • @JeffreyKemp "Same is true for Oracle, MySQL and PostgreSQL". – Danny Beckett Jun 28 '13 at 20:11
3

If they are building the query dynamically, you should check whether they're using bind variables. Building the query from literals requires extra parsing, potentially limiting scalability, and also can greatly increase the risk of SQL Injection attacks.

where 1 = 1 and my_id = :b1;

(and then defining the value of the bind variable)

is generally much better than:

where 1 = 1 and my_id = 123456;
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Jim Hudson
  • 7,959
  • 2
  • 23
  • 15
0

They may have built the query from substrings.

It may be a way to build it with just ANDs, depending on the business rule match, so you don't really have to care which is your first condition.

Wouldn't do it that way myself.

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
John Barrett
  • 545
  • 4
  • 9