user2622662 user2622662 - 1 month ago 9
SQL Question

Whats the exact meaning of having a condition like where 0=0?

I'm having a bit confusion in using a statement like "where 0=0" in Oracle procedures? Can someone please clarify it? Even though we do it for dynamic selection, why do we add this statement even though we append the actual condition in the query? Will this where condition make any difference to the result set?..
I went through
How can I Select all rows where column contain any words of a string?
but I dint exactly understand the reason for using "where 0=0".
Can some one please give me the proper reason for using such a condition?..

Thanks in Advance..;)

Answer

When using dynamic sql, extra clauses may need to be added, depending upon certain conditions being met. The 1=1 clause has no meaning in the query ( other than it always being met ), its only use is to reduce the complexity of the code used to generate the query in the first place.

E.g. This pseudo code

DECLARE
v_text VARCHAR2(2000) := 'SELECT * FROM table WHERE 1=1 ';
BEGIN

    IF condition_a = met THEN
    v_text := v_text ||' AND column_1 = ''A'' ';
    END IF;

    IF condition_b = also_met THEN
    v_text := v_text ||' AND column_2 = ''B'' ';
    END IF;

execute_immediate(v_text);

END;

is simpler than the pseudo code below, and as more clauses were added, it would only get messier.

DECLARE
v_text VARCHAR2(2000) := 'SELECT * FROM table  ';
BEGIN

    IF condition_a = met THEN
    v_text := v_text ||' WHERE column_1 = ''A'' ';
    END IF;

    IF condition_b = also_met AND 
       condition_a != met THEN
    v_text := v_text ||' WHERE column_2 = ''B'' ';
    ELSIF condition_b = also_met AND 
       condition_a = met THEN
    v_text := v_text ||' AND column_2 = ''B'' ';
    END IF;

execute_immediate(v_text);

END;
Comments