I am wondering why the following fails:
SELECT price<500 as PriceIsCheap
and forces you to do the following:
SELECT CASE WHEN (price<500) THEN 1 ELSE 0 END as PriceIsCheap
When, as per the answer to this related question, the conversion table says that an implicit conversion should occur.
You can use the CONVERT operator. CAST or CONVERT will work. Show activity on this post. 1 is the display for a true bit.
If there are 8 or fewer bit columns in a table, the columns are stored as 1 byte. If there are from 9 up to 16 bit columns, the columns are stored as 2 bytes, and so on. The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.
SQL Server BIT data type is an integer data type that can take a value of 0, 1, or NULL . SQL Server optimizes storage of BIT columns. If a table has 8 or fewer bit columns, SQL Server stores them as 1 byte. If a table has 9 up to 16 bit columns, SQL Server stores them as 2 bytes, and so on.
1 Answer. Show activity on this post. Bits in SQL Server are always stored as 1 or 0 in a bitmap. The "Edit Table" option in SSMS just translates this to True or False for presentation purposes, this is nothing to do with how it is actually stored.
There is no boolean data type in SQL, BIT
is kind of a hack, but the main problem is that due to the SQL concept of NULL
true boolean logic is impossible (for example, what would your query return if price
was NULL
?)
Note that I'm not saying that there are not possible ways to implement boolean logic that "mostly" work (for example, you could say that TRUE OR NULL
is NULL
or whatever) just that the people who designed the SQL standard couldn't decide on The One True Representation for boolean logic (for example, you could also argue that TRUE OR NULL
is TRUE
, since TRUE OR <anything>
is TRUE
).
The boolean expressions (=, <=, >=, etc) are only valid in certain places (notably, WHERE
clauses and CASE
labels) and not in any other place.
Well you'll also find you can't if you have a bit column called IsCheap
do SELECT * FROM STUFF WHERE IsCheap
, you have to do WHERE IsCheap=1
.
The reason is simple, the data type is a bit, not a bool. True, it's basically the only use you'll put it to and it's implicitly converted by almost any data access framework, but it's still technically a bit with 0 or 1 rather than a bool with true or false. There's an obvious connection we can all see, but SQL wasn't written with this assumption in it so we have to provide the logic to convert true/false to 1/0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With