Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select true/false based on column value?

Tags:

sql-server

I have a table with the following columns: EntityId, EntityName, EntityProfile, .................

I want to select the Id and Name and true/false column based on the value of entity profile, for example a returned result set like below, would mean that entities 1&2 have profiles while 3 not.

1 Name1 True 2 Name2 True 3 Name3 False etc..... 

I know I can do it using a function that return true/false based on the profile value like this: SELECT EntityId, EntityName, dbo.EntityHasProfile(EntityId) AS HasProfile FROM Entities

but I'm returning a large no. of records and with this function call for each record, the query is very slow, and when I remove the function call the query execution time drops significantly.

So is there another way of doing this? Thanks

like image 605
Yasmine Avatar asked Mar 07 '10 16:03

Yasmine


People also ask

How do you select True False in SQL?

Answers. True or False are not reserved in SQL. Most often when programming you would use a bit and 0 = False while 1 = True.

Is group by clause use for creating group of same column values True or false?

The GROUP BY Clause SQL is used to group rows with same values. The GROUP BY Clause is used together with the SQL SELECT statement. The SELECT statement used in the GROUP BY clause can only be used contain column names, aggregate functions, constants and expressions.

How do you select a Boolean in SQL?

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.


1 Answers

Use a CASE. I would post the specific code, but need more information than is supplied in the post - such as the data type of EntityProfile and what is usually stored in it. Something like:

CASE WHEN EntityProfile IS NULL THEN 'False' ELSE 'True' END 

Edit - the entire SELECT statement, as per the info in the comments:

SELECT EntityID, EntityName,         CASE WHEN EntityProfile IS NULL THEN 'False' ELSE 'True' END AS HasProfile FROM Entity 

No LEFT JOIN necessary in this case...

like image 86
froadie Avatar answered Sep 28 '22 07:09

froadie