Need BOOLEAN Result from SQL EXISTS Statement without using a WHERE Clause

The issue is that EXISTS is only valid syntax in certain grammar constructs. I am not aware the formal rules (which means I should go RTFM :-?), but EXISTS can be wrapped in case which will work when used as an expression:

set @r = case when exists (...) then 1 else 0 end

return case when exists (...) then 1 else 0 end

e.g.

return case when exists (SELECT 1 -- because it's as good as anything else
    FROM fdd.admissions_view as cx  
    WHERE cx.id=1111 and cx.campus='MEXI')
  then 1 else 0 end

How about something like

select case when count(cx.id) > 0 then 1 else 0 end 
 FROM fdd.admissions_view as cx  
 WHERE cx.id=1111 and cx.campus='MEXI'

?


Not totally sure what you mean by "return", but here are some ideas.

DECLARE @return BIT = 0;
IF EXISTS( SELECT  cx.id
    FROM fdd.admissions_view as cx  
    WHERE cx.id=1111 and cx.campus='MEXI' ) SET @return = 1;

Or:

IF EXISTS( SELECT  cx.id
    FROM fdd.admissions_view as cx  
    WHERE cx.id=1111 and cx.campus='MEXI' ) SELECT 1 AS returnValue

Here is one which uses EXISTS with CASE WHEN ... THEN .. ELSE ... END, tested with MySQL and Oracle:

SELECT 
  CASE WHEN EXISTS 
    (SELECT  cx.id
     FROM fdd.admissions_view as cx  
     WHERE cx.id=1111 and cx.campus='MEXI')
  THEN 1 
  ELSE 0 
  END 
FROM DUAL

Update:

Found some related Q/A:

  • Optimizing SELECT COUNT to EXISTS
  • is it possible to select EXISTS directly as a bit?