Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a boolean value from a query during condition evaluation?

I need something like this:

select (len(someLongTextColumn)=0) as isEmpty;

The above doesn't work,

any alternatives?

like image 964
shealtiel Avatar asked Aug 02 '11 07:08

shealtiel


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 I return a true or false function in SQL?

CREATE OR REPLACE FUNCTION fun_tiene_cita (id_paciente number, fecha_cita date) return number is begin if (exists(select id_paciente from citas where id_paciente = 500 and fecha_cita = 03/03/2020)) then return 'true'; else return 'false'; end if; END fun_tiene_cita; Obviously, it isn't working, so, what could I do?

How do you add an if else condition in SQL query?

This is why you can nest IF ELSE in SQL query statements. It is demonstrated below: DECLARE @age INT; SET @age = 60; IF @age < 18 PRINT 'underage'; ELSE BEGIN IF @age < 50 PRINT 'You are below 50'; ELSE PRINT 'Senior'; END; In this example, the code will print underage if the value of @age is below 18.

Can we use if condition in SQL query?

IF condition in SQL IF() function is passed with two parameters, one for true and other for false. The function returns one value if a condition is TRUE, and another value if the condition is FALSE.


2 Answers

SQL Server:

SELECT CONVERT(BIT, 1) -- true
SELECT CONVERT(BIT, 0) -- false
like image 185
Kimchi Man Avatar answered Nov 16 '22 01:11

Kimchi Man


If you cast to bit, then most client code can read it as boolean directly (SQL Server doesn't have a boolean type)

SELECT
    CAST(
        CASE
           WHEN len(someLongTextColumn) = 0 THEN 1 ELSE 0
        END AS bit
        ) as isEmpty;

if you have many in one go, use bit variables like this: Imply bit with constant 1 or 0 in SQL Server

like image 44
gbn Avatar answered Nov 16 '22 02:11

gbn