Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Is there any way in a simple query to return a Boolean value using an SQL EXISTS statement without using a WHERE clause?

All of the 2008 R2 SQL Server Books Online examples show another WHERE clause and two tables. Website examples show either a WHERE or an IF-THEN-ELSE in a procedure.

I was hoping to do the following on one table:

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

The SELECT statement works fine and returns the ID. I just want to add EXISTS to return a BOOLEAN, but the syntax above is not valid.

Can I do something like this? If so, what am I missing syntax-wise? If not, what other technique may work?

Please advise. Thanks.

like image 568
blarson Avatar asked Jun 15 '12 00:06

blarson


People also ask

Can a SQL query return a boolean?

Details of sql differ. SQL Server does not support a Boolean type e.g. SELECT WHEN CAST(1 AS BIT) THEN 'YES' END AS result -- results in an error i.e. CAST(1 AS BIT) is not the same logical TRUE.

How do you set a boolean value in SQL query?

You can update boolean value using UPDATE command. If you use the BOOLEAN data type, MySQL internally convert it into tinyint(1). It can takes true or false literal in which true indicates 1 to tinyint(1) and false indicates 0 to tinyint(1).

Can we use not in WHERE clause in SQL?

The SQL NOT condition (sometimes called the NOT Operator) is used to negate a condition in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.

What type of results can a Boolean expression have in SQL?

A Boolean expression is a logical statement that is either TRUE or FALSE . Boolean expressions can compare data of any type as long as both parts of the expression have the same basic data type. You can test data to see if it is equal to, greater than, or less than other data.


2 Answers

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?
like image 96
ryenus Avatar answered Oct 09 '22 12:10

ryenus


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' 

?

like image 41
500 - Internal Server Error Avatar answered Oct 09 '22 11:10

500 - Internal Server Error