Skip to Main Content
  • Questions
  • Can we use 'exists' condition in the Decode function?

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Sai.

Asked: February 03, 2016 - 10:41 pm UTC

Last updated: February 04, 2016 - 5:56 am UTC

Version: 11g

Viewed 10K+ times! This question is

You Asked

Hi Tom,

I would like to use 'Decode' function with 'exists' condition. But i'm unsure what value does the 'exists' condition evaluates to, so that i can put that in the 'search' clause to return a hard coded value.

This is what i wrote and it erred out.
Example :Decode(exists(select 1 from emp e where e.empid =t.id),true,10003,10004).

I'm sorry i couldn't provide the entire context.
I just wanted to know the following things:
1. Can we use exists in the decode function?
2. What 'exists' evaluates to ? Can i treat it as a boolean result and put 'true/false' in the search of the decode?

Thanks
Sai

and Connor said...

You can achieve the same with a count, or use a CASE statement instead

SQL> select decode(
  2            ( select count(*) from user_tables where table_name = 'T' and rownum = 1 ),
  3            1, 'YES', 'NO') from dual;

DEC
---
YES

SQL> select
  2    case
  3      when exists
  4            ( select 1 from user_tables where table_name = 'T' ) then 1 else 0 end flag
  5  from dual;

      FLAG
----------
         1



Is this answer out of date? If it is, please let us know via a Comment