Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to select EXISTS directly as a bit?

I was wondering if it's possible to do something like this (which doesn't work):

select cast( (exists(select * from theTable where theColumn like 'theValue%') as bit)

Seems like it should be doable, but lots of things that should work in SQL don't ;) I've seen workarounds for this (SELECT 1 where... Exists...) but it seems like I should be able to just cast the result of the exists function as a bit and be done with it.

like image 463
jcollum Avatar asked Sep 27 '22 11:09

jcollum


People also ask

How do you use exists in select statement?

The result of EXISTS is a boolean value True or False. It can be used in a SELECT, UPDATE, INSERT or DELETE statement. Syntax: SELECT column_name(s) FROM table_name WHERE EXISTS (SELECT column_name(s) FROM table_name WHERE condition);

What is the use of exists ()?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

How do you use exists in SQL instead of in?

EXISTS is used to determine if any values are returned or not. Whereas, IN can be used as a multiple OR operator. If the sub-query result is large, then EXISTS is faster than IN. Once the single positive condition is met in the EXISTS condition then the SQL Engine will stop the process.


2 Answers

No, you'll have to use a workaround.

If you must return a conditional bit 0/1 another way is to:

SELECT CAST(
   CASE WHEN EXISTS(SELECT * FROM theTable where theColumn like 'theValue%') THEN 1 
   ELSE 0 
   END 
AS BIT)

Or without the cast:

SELECT
   CASE
       WHEN EXISTS( SELECT 1 FROM theTable WHERE theColumn LIKE 'theValue%' )
            THEN 1 
       ELSE 0 
   END
like image 306
Alex K. Avatar answered Oct 06 '22 12:10

Alex K.


SELECT CAST(COUNT(*) AS bit) FROM MyTable WHERE theColumn like 'theValue%'

When you cast to bit

  • 0 -> 0
  • everything else -> 1
  • And NULL -> NULL of course, but you can't get NULL with COUNT(*) without a GROUP BY

bit maps directly to boolean in .net datatypes, even if it isn't really...

This looks similar but gives no row (not zero) if no matches, so it's not the same

SELECT TOP 1 CAST(NumberKeyCOlumn AS bit) FROM MyTable WHERE theColumn like 'theValue%'
like image 55
gbn Avatar answered Oct 06 '22 13:10

gbn