Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plsql conditional where clause

I'd like to perform a conditional where in a sql statement, and use two different criteria, e.g. in pseudo code:

procedure(..., bool_value IN boolean default false) is
....
begin

select * from mytable mt
where 
     if bool_value = true then mt.criterion_1 = value
     else
        mt_.criterion_2 = value; -- if boolean value is set, use criterion_1 column, otherwise use criterion_2 column

end

Suppose it's possible, What's the best way to do it?

Thanks

like image 875
Carmellose Avatar asked Dec 05 '25 19:12

Carmellose


2 Answers

Try this:

bool_value_string varchar2(5)

bool_value_string = case when bool_value then 'true' else 'false' end;

select * from mytable mt
where 
(bool_value_string = 'true' and mt.criterion_1 = value)
or
(bool_value_string = 'false' and mt.criterion_2 = value)

Basically, convert your when...then idiom to an either...or one. Either the boolean field is non-null and true, meaning filter has to be by the first criterion, or it isn't, meaning filter by the second one.

like image 156
shree.pat18 Avatar answered Dec 07 '25 16:12

shree.pat18


Basically, your condition gets translated as:

 if bool_value = true 
       then mt.criterion_1 = value
 else if bool_value = false
       then mt_.criterion_2 = value; 

Since you cannot directly use boolean value in select statements (Refer comments), use as below: (Change bool_value from boolean to varchar2 or a number)

procedure(..., bool_value IN varchar2(10) default 'FALSE') is
....
begin

   select * from mytable mt
    where  
      (case 
          when (bool_value = 'TRUE' and mt.criterion_1 = value) then (1)
          when (bool_value = 'FALSE' and mt_.criterion_2 = value) then (1)
          (else 0)
      end) = 1;

OR

      select * from mytable mt
      where 
      (bool_value = 'TRUE' and mt.criterion_1 = value)
       or
      (bool_value = 'FALSE' and mt.criterion_2 = value)


end

ORIGINAL ANSWER

You can also use case statement in where clause as below:

select * from mytable mt
where  
  (case 
      when (bool_value = true and mt.criterion_1 = value) then (1)
      when (bool_value = false and mt_.criterion_2 = value) then (1)
      (else 0)
  end) = 1;

In oracle, you can use below Query also.

  select * from mytable mt
  where 
  (bool_value = true and mt.criterion_1 = value)
   or
  (bool_value = false and mt.criterion_2 = value)

Note: Since default of bool_value = false, is null condition need not be checked.

like image 45
Nishanthi Grashia Avatar answered Dec 07 '25 15:12

Nishanthi Grashia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!