55

A)

select decode(count(*), 0, 'N', 'Y') rec_exists
from (select 'X'
      from dual
      where exists (select 'X'
                    from sales
                    where sales_type = 'Accessories'));

B)

select decode(count(*), 0, 'N', 'Y') rec_exists
from (select 'X'
      from sales
      where sales_type = 'Accessories'); 

C) Something else (specify)

EDIT: It was hard to pick the "correct" answer, as the best approach depends on what you want to do after checking if the value exists, as pointed out by APC. I ended up picking the answer by RedFilter, since I had originally envisioned this check as a function by itself.

2
  • (Very old question, I know...) Sometimes I need to do a simple check for "is this a valid ID number" (that is, does it already exist) from a server-side program (PHP), so I end up doing a simple SQL query: SELECT null FROM table_name WHERE id = :id (using prepared statements, :id). If any rows were returned, the answer is yes. Otherwise, no. The actual returned data is irrelevant. Nov 11, 2015 at 13:50
  • Very old response to an even older question, but still...haha...I'm pretty sure SELECT count(*) FROM table_name WHERE id = :id will always be faster than SELECT null FROM table_name WHERE id = :id
    – PAULUS
    Jan 14, 2021 at 0:44

11 Answers 11

98
select case 
            when exists (select 1 
                         from sales 
                         where sales_type = 'Accessories') 
            then 'Y' 
            else 'N' 
        end as rec_exists
from dual;
3
  • 5
    You're missing a FROM dual. Aug 9, 2010 at 2:53
  • if you are like me, and wish to use this in a Stored Procedure as a resulting variable, replace AS with INTO, example: select case when exists (select 1 from sales where sales_type = 'Accessories') then 'Y' else 'N' end INTO rec_exists from dual;
    – dian jin
    Nov 17, 2020 at 10:20
  • Any comments on my answer :)
    – Shaiju T
    Jan 2 at 16:51
17

What is the underlying logic you want to implement? If, for instance, you want to test for the existence of a record to determine to insert or update then a better choice would be to use MERGE instead.

If you expect the record to exist most of the time, this is probably the most efficient way of doing things (although the CASE WHEN EXISTS solution is likely to be just as efficient):

begin
    select null into dummy
    from sales
    where sales_type = 'Accessories'
    and rownum = 1;

    --  do things here when record exists
    ....        

exception
    when no_data_found then
        -- do things here when record doesn't exists
        .....
end;

You only need the ROWNUM line if SALES_TYPE is not unique. There's no point in doing a count when all you want to know is whether at least one record exists.

2
  • 1
    +1 Nice answer. I use this check frequently in different circumstances... that's why I was wondering what was the best way to do it. Sometimes I just want to return a flag to the front end. Other times, I do something different, like return a value if it exists, and if not, return the next value of a sequence. I guess you're right - the best way might depend on the situation.
    – Zesty
    Aug 8, 2010 at 13:47
  • Any comments on my answer :)
    – Shaiju T
    Jan 2 at 16:49
11
select count(1) into existence 
   from sales where sales_type = 'Accessories' and rownum=1;

Oracle plan says that it costs 1 if seles_type column is indexed.

5
  • 7
    This is the method I usually use, but count(1) really ought to be count(*) -- there's nothing special about count(1) and count(*) is the standard syntax. May 30, 2013 at 8:20
  • 1
    count(1) means that we count just existence nothing else. It's easier to read, I think.
    – tyger
    Jun 3, 2013 at 5:30
  • 1
    That is what count(*) means. In this context "*" does not mean "all columns" in the sense that it does in "select * from " Jun 3, 2013 at 6:47
  • @DavidAldridge just because "there's nothing special about count(1)" doesn't mean it can't be used, nor does it imply that "count(*) should be used". Jan 21, 2015 at 7:50
  • 5
    For future readers an answer to these old comments: count(*) means count records. count(1) means count records for which 1 is not null. So both get the same result (and most if not all DBMS will simply perform a count(*) in both cases), but count(*) is the straight-forward way to do it and should be preferred. May 19, 2016 at 13:46
4

here you can check only y , n if we need to select a name as well that whether this name exists or not.

select name , decode(count(name),0, 'N', 'Y')
  from table
 group by name;

Here when it is Y only then it will return output otherwise it will give null always. Whts ths way to get the records not existing with N like in output we will get Name , N. When name is not existing in table

2

Simply get a count of the record(s) you're looking for. If count > 0 then record(s) exist.

    DECLARE
    rec_count NUMBER := 0;

    BEGIN

    select count(*) 
    into rec_count  
    from EMPLOYEETABLE  
    WHERE employee_id = inEMPLOYEE_ID  
    AND department_nbr = inDEPARTMENT_NBR;  


    if rec_count > 0 then  
       {UPDATE EMPLOYEETABLE}
    else  
       {INSERT INTO EMPLOYEETABLE}  
    end if;  

    END;
1
select decode(count(*), 0, 'N', 'Y') rec_exists 
      from sales 
      where sales_type = 'Accessories'; 
0
select NVL ((select 'Y' from  dual where exists
   (select  1 from sales where sales_type = 'Accessories')),'N') as rec_exists
from dual

1.Dual table will return 'Y' if record exists in sales_type table 2.Dual table will return null if no record exists in sales_type table and NVL will convert that to 'N'

1
  • Please add some explanation to your answer to support your code.
    – Rachcha
    Mar 31, 2014 at 6:04
0

The most efficient and safest way to determine if a row exists is by using a FOR-LOOP... You won't even have a difficult time if you are looking to insert a row or do something based on the row NOT being there but, this will certainly help you if you need to determine if a row exists. See example code below for the ins and outs...

If you are only interested in knowing that 1 record exists in your potential multiple return set, than you can exit your loop after it hits it for the first time.

The loop will not be entered into at all if no record exists. You will not get any complaints from Oracle or such if the row does not exist but you are bound to find out if it does regardless. Its what I use 90% of the time (of course dependent on my needs)...

EXAMPLE:

DECLARE

v_exist varchar2(20);

BEGIN
   FOR rec IN
   (SELECT LOT, COMPONENT 
   FROM TABLE
   WHERE REF_DES = (SELECT REF_DES FROM TABLE2 WHERE ORDER = '1234') 
   AND ORDER = '1234')
  LOOP

      v_exist := "IT_EXISTS"

   INSERT INTO EAT_SOME_SOUP_TABLE (LOT, COMPONENT) 
   VALUES (rec.LOT, rec.COMPONENT);**

   --Since I don't want to do this for more than one iteration (just in case there may have been more than one record returned, I will EXIT;

   EXIT;
   END LOOP;



IF v_exist  IS NULL

    THEN

            --do this

END IF;

END;

--This is outside the loop right here The IF-CHECK just above will run regardless, but then you will know if your variable is null or not right!?. If there was NO records returned, it will skip the loop and just go here to the code you would have next... If (in our case above), 4 records were returned, I would exit after the first iteration due to my EXIT;... If that wasn't there, the 4 records would iterate through and do an insert on all of them. Or at least try too.

By the way, I'm not saying this is the only way you should consider doing this... You can

SELECT COUNT(*) INTO v_counter WHERE ******* etc...

Then check it like

if v_counter > 0
      THEN
         --code goes here
   END IF;

There are more ways... Just determine it when your need arises. Keep performance in mind, and safety.

0
select CASE 
when exists (SELECT U.USERID,U.USERNAME,U.PASSWORDHASH
FROM  TBLUSERS U WHERE U.USERID =U.USERID 
AND U.PASSWORDHASH=U.PASSWORDHASH) 
then 'OLD PASSWORD EXISTS' 
else 'OLD PASSWORD NOT EXISTS' 
end as OUTPUT
from DUAL;
0

Another solution:

There are lot of solutions I saw in SO, which are good, count(1) or count(*) , when exists, where exists, left join, loop with no data exception..

I prefer below options, hope this is performant in large data, didn't check though :) :

Return 1 or 0 ( Can be used if you have checks with a number variable )

 SELECT NVL(MIN(1),0)
 FROM SALES 
 WHERE SALES_TYPE = 'ACCESSORIES' AND ROWNUM = 1

Return Y or N ( Can be used if you have checks with a string variable )

 SELECT DECODE(MIN(1),1, 'Y', 'N')
 FROM SALES 
 WHERE SALES_TYPE = 'ACCESSORIES' AND ROWNUM = 1

There are multiple options, Kindly do a performance test for your scenario and choose the best option.

-3
SELECT 'Y' REC_EXISTS             
FROM SALES                       
WHERE SALES_TYPE = 'Accessories'

The result will either be 'Y' or NULL. Simply test against 'Y'

7
  • 3
    The result will be 'Y' if one record exists. If multiple records exist it will be a TOO_MANY_ROWS exception. If no records exist it will be a NO_DATA_FOUND exception.
    – APC
    Aug 8, 2010 at 13:37
  • @APC: Not unless you SELECT INTO a single variable. The query as written is pure SQL and does not raise any exceptions. Aug 8, 2010 at 13:40
  • 3
    @ObiWanKenobi - how do you test for a value unless you select it into a variable?
    – APC
    Aug 8, 2010 at 15:01
  • @APC: Maybe you put the SQL statement in a cursor and loop through it, or maybe you run the SQL from a client program and iterate through a record set (yes, I know the question is about PL/SQL). Or maybe you add PL/SQL exception handlers. Not the most efficient implementation, to be sure, but it's not wrong per se. Aug 10, 2010 at 5:59
  • What aspect of the question implies pl/sql?
    – EvilTeach
    Mar 31, 2014 at 13:08

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.