Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

How to return a boolean value on SQL Select Statement?

I tried this code:

SELECT CAST(1 AS BIT) AS Expr1

FROM [User]

WHERE (UserID = 20070022)

and only return TRUE value if the UserID exists on the table. I want it to return FALSE value if the UserID doesn't exist on the table. Thank you very much.

2 Answers

0 votes
by (40.7k points)

If the user doesn't exist, then they will return no row at all. 

Use the below code:

SELECT CASE WHEN EXISTS (

    SELECT *

    FROM [User]

    WHERE UserID = 20070022

)

THEN CAST(1 AS BIT)

ELSE CAST(0 AS BIT) END

0 votes
by (1.5k points)

To return a boolean value on SQL Select Statement, refer to the below query

SELECT 

    CASE 

        WHEN condition THEN 1  -- Represents TRUE

        ELSE 0                 -- Represents FALSE

    END AS BoolValue

FROM table_name;

Related questions

0 votes
1 answer
0 votes
1 answer
asked Dec 17, 2020 in SQL by Appu (6.1k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...