Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle case inside where clause

This is a simple question, I've read some details about using CASE in WHERE clause, but couldn't able to make a clear idea how to use it. The below is my sample query:

1    SELECT * FROM dual
2    WHERE (1 =1)
3     AND (SYSDATE+1 > SYSDATE)
4     AND (30 > 40)
5     AND (25 < 35);

I have a procedure i_value as in parameter. I need to ignore the 4th line if i_value is 'S' and I need to ignore the 5th line if i_value is 'T'.

Thanks in advance.

like image 645
ajmalmhd04 Avatar asked Jul 11 '13 04:07

ajmalmhd04


People also ask

Can we use case in WHERE clause in Oracle?

You can use a CASE expression in any statement or clause that accepts a valid expression. For example, you can use the CASE expression in statements such as SELECT , UPDATE , or DELETE , and in clauses like SELECT , WHERE , HAVING , and ORDDER BY .

Can you use case when in a WHERE clause?

CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.

Can we use case inside WHERE clause in SQL?

Another way to use the Case Statement is within the WHERE clause. There, it may be utilized to alter the data fetched by a query based on a condition. Within that context, the Case Statement is ideally suited to both static queries, as well as dynamic ones, such as those that you would find inside a stored procedure.

Can we have nested WITH clause in Oracle?

no,you can't nest them.


1 Answers

I think this is the best way to solve your problem:

select *
from dual
where (1 = 1)
      and (sysdate + 1 > sysdate)
      and case
            when i_value = 'S'
              then
                case
                  when (25 < 35)
                    then 1
                    else 0
                end
            when i_value = 'T'
              then
                case
                  when (30 > 40)
                    then 1
                    else 0
                end
          end = 1;

Of course, you could use Dynamic SQL, but it'd be more difficult and less effective.

like image 68
sergdenisov Avatar answered Oct 02 '22 15:10

sergdenisov