tags:

views:

854

answers:

3

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
+13  A: 

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
+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
I suspected this to be the case. This client actually has non-dynamic queries like this too. They're really lazy:)
Blanthor
A: 

Did they build this statement from substrings? It may be a way to build a query 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, just wondering :-)

John Barrett
+3  A: 

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;

Jim Hudson