Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set bool value in SQL

Tags:

sql

sql-server

I have a column which is bool. How can I set true, false values for that? Here is my query :

Update [mydb].[dbo].[myTable]
SET isTrue =
(
CASE WHEN Name = 'Jason' THEN 1
END
)

I don't know what to write after THEN keyword. Should I write 1 or true or 1 AS BIT or something else?

like image 820
jason Avatar asked Jan 17 '17 10:01

jason


People also ask

How do you set a boolean value in SQL query?

You can insert a boolean value using the INSERT statement: INSERT INTO testbool (sometext, is_checked) VALUES ('a', TRUE); INSERT INTO testbool (sometext, is_checked) VALUES ('b', FALSE); When you select a boolean value, it is displayed as either 't' or 'f'.

How do I store a boolean value in SQL Server?

In SQL Server, a Boolean Datatype can be created by means of keeping BIT datatype. Though it is a numeric datatype, it can accept either 0 or 1 or NULL values only. Hence easily we can assign FALSE values to 0 and TRUE values to 1. This will provide the boolean nature for a data type.

How do you set true or false in SQL?

Use bit type 1 = true and 0 = false. You won't need to cast, but currently you'd be leaving "false results" as NULL . So add ELSE 0 to your CASE statement.

Is there boolean in SQL?

There is boolean data type in SQL Server. Its values can be TRUE , FALSE or UNKNOWN . However, the boolean data type is only the result of a boolean expression containing some combination of comparison operators (e.g. = , <> , < , >= ) or logical operators (e.g. AND , OR , IN , EXISTS ).


Video Answer


2 Answers

Sql server does not expose a boolean data type which can be used in queries.
Instead, it has a bit data type where the possible values are 0 or 1.
So to answer your question, you should use 1 to indicate a true value, 0 to indicate a false value, or null to indicate an unknown value.

Update [mydb].[dbo].[myTable]
SET isTrue =
CASE WHEN Name = 'Jason' THEN 
    1
ELSE 
    0
END
like image 51
Zohar Peled Avatar answered Sep 29 '22 12:09

Zohar Peled


The query you added will work fine, but it will you have to take care of "FALSE" part as well otherwise it will try to enter NULL in your column. Do you have any default value constrain on isTrue column?

Update [mydb].[dbo].[myTable]
SET isTrue =
(
   CASE WHEN Name = 'Jason' THEN 1 ELSE 0
END
)
like image 43
K D Avatar answered Sep 29 '22 13:09

K D