Return Boolean Value on SQL Select Statement - sql

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 it only returns TRUE if the UserID exists on the table. I want it to return FALSE if the UserID doesn't exist on the table.

What you have there will return no row at all if the user doesn't exist. Here's what you need:
SELECT CASE WHEN EXISTS (
SELECT *
FROM [User]
WHERE UserID = 20070022
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END

Possibly something along these lines:
SELECT CAST(CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END AS BIT)
FROM dummy WHERE id = 1;
http://sqlfiddle.com/#!3/5e555/1

Given that commonly 1 = true and 0 = false, all you need to do is count the number of rows, and cast to a boolean.
Hence, your posted code only needs a COUNT() function added:
SELECT CAST(COUNT(1) AS BIT) AS Expr1
FROM [User]
WHERE (UserID = 20070022)

Use 'Exists' which returns either 0 or 1.
The query will be like:
SELECT EXISTS(SELECT * FROM USER WHERE UserID = 20070022)

select CAST(COUNT(*) AS BIT) FROM [User] WHERE (UserID = 20070022)
If count(*) = 0 returns false. If count(*) > 0 returns true.

I do it like this:
SELECT 1 FROM [dbo].[User] WHERE UserID = 20070022
Seeing as a boolean can never be null (at least in .NET), it should default to false or you can set it to that yourself if it's defaulting true. However 1 = true, so null = false, and no extra syntax.
Note: I use Dapper as my micro orm, I'd imagine ADO should work the same.

For those of you who are interested in getting the value adding a custom column name, this worked for me:
CAST(
CASE WHEN EXISTS (
SELECT *
FROM mytable
WHERE mytable.id = 1
)
THEN TRUE
ELSE FALSE
END AS bool)
AS "nameOfMyColumn"
You can skip the double quotes from the column name in case you're not interested in keeping the case sensitivity of the name (in some clients).
I slightly tweaked #Chad's answer for this.

Notice another equivalent problem: Creating an SQL query that returns (1) if the condition is satisfied and an empty result otherwise. Notice that a solution to this problem is more general and can easily be used with the above answers to achieve the question that you asked. Since this problem is more general, I am proving its solution in addition to the beautiful solutions presented above to your problem.
SELECT DISTINCT 1 AS Expr1
FROM [User]
WHERE (UserID = 20070022)

DECLARE #isAvailable BIT = 0;
IF EXISTS(SELECT 1 FROM [User] WHERE (UserID = 20070022))
BEGIN
SET #isAvailable = 1
END
initially isAvailable boolean value is set to 0

Related

WHERE from CASE result

I have a statement - simplified
SELECT UserID,
CASE WHEN UserName = 'xxx' THEN 1 ELSE 0 AS Deleted
FROM User
WHERE Deleted = 0;
but this doesn't work because Deleted can't be used.
Is there a workaround? I can't solve it this way WHERE UserName <> 'xxx' , because in my real statement it's a huge sub select.
Wrap your original query up in a derived table. (Since column aliases aren't available in the same query's where clause.)
select *
from
(
SELECT UserID,
CASE WHEN UserName = 'xxx' THEN 1 ELSE 0 END AS Deleted
FROM User
) dt
WHERE dt.Deleted = 0;
We can use like below without sub queries.
SELECT *
FROM [User]
WHERE (CASE WHEN UserName = 'xxx' THEN 1 ELSE 0 END)=0

How to Short-Circuit SQL Where Clause

I am trying to perform the following query in SQL server:
declare #queryWord as nvarchar(20) = 'asdas'
SELECT * FROM TABLE_1
WHERE (ISDATE(#queryWord) = 1)
AND TABLE_1.INIT_DATE = CONVERT(Date, #queryWord)
This obviously causes an error because 'asdas' cannot be converted to Date. Although, I was expecting a different behavior. That is, because ISDATE(#queryWord) = 1 is false, I was expecting SQL to not check the second condition, but apparently, it does.
I know there are some other ways to perform this query but this is not my question. I wonder if there is some way to do not check the second condition is the first one does not satisfy. I am curious because I thought that SQL already did this.
SQL Server does not do short-circuiting (nor should it).
If you need it to not try something under some circumstances, you need to force that in the way that you write your query.
For this query the easiest fix would be to use a CASE expression in your WHERE clause.
declare #queryWord as nvarchar(20) = 'asdas'
SELECT * FROM TABLE_1
WHERE TABLE_1.INIT_DATE = (CASE WHEN ISDATE(#queryWord) = 1
THEN CONVERT(Date, #queryWord)
ELSE NULL END)
Off-hand, CASE and query-nesting are the only two supported ways that I can think of to force an order of evaluation for dependent conditions in SQL.
I Guess you could do it in 2 passes:
declare #queryWord as nvarchar(20) = 'asdas'
select
*
from
(
SELECT * FROM TABLE_1
WHERE (ISDATE(#queryWord) = 1) ) t1
where t1.INIT_DATE = CONVERT(Date, #queryWord)
So your inner query runs the first test and the outer query the second. In a single query, I don't believe there is any way to force any order of evaluating conditions.
Why not do a CASE in the WHERE condition?
DECLARE #tester TABLE (
theDate DATE,
theValue INT
)
INSERT INTO #tester VALUES ('2013-10-17', 35)
INSERT INTO #tester VALUES ('2013-10-16', 50)
INSERT INTO #tester VALUES ('2013-10-15', 2)
declare #queryWord as nvarchar(20) = 'asdas'
SELECT *
FROM #tester
WHERE theDate =
CASE
WHEN ISDATE(#queryWord) = 1 THEN CONVERT(Date, #queryWord)
ELSE theDate
END
SET #queryWord = '2013-10-17'
SELECT *
FROM #tester
WHERE theDate =
CASE
WHEN ISDATE(#queryWord) = 1 THEN CONVERT(Date, #queryWord)
ELSE theDate
END
It can be "simulated" with a CASE statement. But you have to make the first condition giving a TRUE value to avoid checking of the 2nd condition :
declare #queryWord as nvarchar(20) = 'asdas'
SELECT *
FROM TABLE_1
WHERE (CASE
WHEN ISDATE(#queryWord) = 0 THEN 0
WHEN TABLE_1.INIT_DATE = CONVERT(Date, #queryWord) THEN 1
ELSE 0 END) = 1
There is no defined evaluation order in a SQL statement -- except in the case of case expressions, and even there the order isn't so much defined as the result guaranteed. The conditions in your where clause could theoretically be done in parallel or alternating order.
Case expressions differ not by having a defined order, but by having a guaranteed result. IOW, case when 1=1 then 0 When longrunningfunction() = 1 then 2 end is guaranteed to return zero, but there is no promise not to run the longrunningfunction.

Return Bit Value as 1/0 and NOT True/False in SQL Server

I have a Table in SQL Server 2000 with BitValue Column. But, it is being displayed as True/False in SQL Server Management Studio. When I do a Select * from Tablename it returns the BitValue Column values as True/False.
How do I force it to return the value as bits (1/0) instead of True/False?
Any Help will be really appreciated?
Try with this script, maybe will be useful:
SELECT CAST('TRUE' as bit) -- RETURN 1
SELECT CAST('FALSE' as bit) --RETURN 0
Anyway I always would use a value of 1 or 0 (not TRUE or FALSE). Following your example, the update script would be:
Update Table Set BitField=CAST('TRUE' as bit) Where ID=1
Modify your query to generate the output that you want.
Try casting them to int:
select cast(bitFlag as int)
Or, if you like, use case:
select (case when bitFlag = 0 then 0 else 1 end)
This can be changed to 0/1 through using CASE WHEN like this example:
SELECT
CASE WHEN SchemaName.TableName.BitFieldName = 'true' THEN 1 ELSE 0 END AS 'bit Value'
FROM SchemaName.TableName
Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME
in your query for only true or false column
just you pass this things in your select query. using CASE
SELECT
CASE
WHEN gender=0 THEN 'Female'
WHEN gender=1 THEN 'Male'
END
as Gendership from Tablename;

<> operator in SQL

I have a table like this
ID Name IsDeleted
1 Yogesh Null
2 Goldy 1
Now when I run this query
select *
from tableName
where IsDeleted <> 1
I should get ID 1 record, But I am not getting it,
But when I run this
select *
from tableName
where IsDeleted is null
I get ID 1 record,
Why am I facing this behavior ??
Isn't NULL <> 1 is a true statement in SQL ??
IsDeleted is a bit type field with Allow Null true
select * from table
where COALESCE(IsDeleted, 0) <> 1
-- or ISNULL instead of COALESCE.
--ISNULL seems to be better in subqueries, but it's not ANSI SQL.
or
select * from table
where IsDeleted <> 1 or IsDeleted IS NULL
Comparing something with null will always result in unknown. That is why you need to use the is operator to compare null or use functions like COALESCE or isnull to replace null
select *
from tableName
where isnull(IsDeleted,0) <> 1
you compare different types. in this case its an other type (unknown) and not comparable
use the or statement to compare each type seperate
WHERE IsDeleted <> 1 OR IsDeleted is null
Learn about NULL - a comparison with NULL (in standard SQL) yields UNKNOWN, which is not true nor false (and the reason why your expectation is not met).
Try this:
PRINT CASE
WHEN 1 = NULL THEN '1 = NULL'
WHEN 1 <> NULL THEN '1 <> NULL'
ELSE '1 is neither = NULL nor <> NULL'
END
You can either first make sure that you don't have a NULL value (for instance by using the ISNULL or COALESCE functions), or use a condition with the operator IS NULL or IS NOT NULL.
Normal practice would dictate that if you had a column that essentially was a true false, yes no type of field then you should use a bit field with the default value set to 0.
So in your case above you could just run this:
select *
from tableName
where IsDeleted = 0
But in answer to your above question, if the Null is a true NULL value in the table then this will work for you:
select *
from tableName
where IsDeleted is null
or
select *
from tableName
where isnull(IsDeleted,0) = 0
to get record 1 and
select *
from tableName
where IsDeleted is not null
to get record 2
Good luck
Paul.

SQL Query - Return Text based on numeric value

I am trying to work out a query where the query will perform a count (total) on a specific column. If the count is greater than 0, I want to display YES and display NO if the returned count is zero.
So, if I a query as this:
SELECT COUNT(ProblemID)
FROM dbo.ProblemInfo
WHERE (ProblemID IN (100,101,309,305,205,600,500)) AND (DEPID = '10866')
that will actually be a subquery, how do I get the subquery to display "YES" when the returned count is greater than 0 and NO if the count is 0?
I appreciate any insight and help.
select isnull(
SELECT MAX('YES')
FROM dbo.ProblemInfo
WHERE ProblemID IN (100,101,309,305,205,600,500)
AND DEPID = '10866'),
'NO')
This is a trick to return either YES if there's at least one matching row, or null if not.
The wrapping isnull call then turns a null into a NO
Here's an alternate way of querying that.
IF EXISTS(
SELECT *
FROM dbo.ProblemInfo
WHERE (ProblemID IN (100,101,309,305,205,600,500))
AND (DEPID = '10866')
)
BEGIN
SELECT 'Yes'
END
ELSE
BEGIN
SELECT 'No'
END
What I like about this method is that, for enormous data-sets, it should be noticeably faster.
try
SELECT CASE
WHEN (SELECT COUNT(ProblemID) FROM dbo.ProblemInfo WHERE (ProblemID IN (100,101,309,305,205,600,500)) AND (DEPID = '10866')) > 0
THEN 'YES'
ELSE 'NO' END
FROM YourTable
you can use case when.
SELECT
case
when COUNT(ProblemID) = 0 then 'NO'
else 'YES'
end
FROM dbo.ProblemInfo WHERE (ProblemID IN (100,101,309,305,205,600,500)) AND (DEPID = '10866')