1

I have a huge query and I am wondering if it is in Oracle possible to get the result of a case-when-statement and use it for comparison? My CASE-STATEMENT is declared in the Select-Statement and it looks like this.

SELECT........
  (CASE
     WHEN (Select 1 from DUAL) = 1 THEN 'TEST'
     ELSE 'TEST2'
  END) AS TEST;

Now I want to get the result of this case-statement and use it in the where part? Is it possible? (Sry this may be a dumb question)

1
  • 1
    The exact way you ask in your question is not possible. If you define the expression which you labeled (aliased) as TEST in the SELECT clause, the name TEST is not visible in the WHERE clause of the same SELECT query, because WHERE is processed before SELECT. If you don't want to repeat the same (possibly very long) CASE expression in the WHERE clause, you are better off defining TEST in a subquery, then select and use it in the WHERE clause in an outer query. (You can do that with a WITH clause.) Better for future code maintenance, too. Commented Mar 7, 2017 at 16:34

2 Answers 2

2

If you define your CASE statement in either an inline-view or a common table expression (aka WITH clause), you can refer to it by whatever alias you give it.

For example (inline-view):

SELECT ...
FROM   ( SELECT .....
         (CASE
             WHEN (Select 1 from DUAL) = 1 THEN 'TEST'
             ELSE 'TEST2'
          END) AS TEST
         FROM...
       ) v
WHERE  v.test = 'TEST2';

As a common table expression, it would be:

WITH cte AS ( SELECT........
                (CASE
                   WHEN (Select 1 from DUAL) = 1 THEN 'TEST'
                   ELSE 'TEST2'
                END) AS TEST
              FROM ... )
SELECT ...
FROM   cte
WHERE  test = 'TEST2';
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a case statement in the where clause, for eg.:

select * from table
where table.field = (CASE
                      WHEN (Select 1 from DUAL) = 1 THEN 'TEST'
                      ELSE 'TEST2'
                     END)

This will compare the value returned from the case statement with the table field.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.