I've found it very weird that simple code like this is not valid:
select * from table where field=true
The alternative apparently being
select * from table where field='true'
Ok, guess I can live with that. For one reason or another I needed to do something like this recently:
select true as somefield,...
The alternative to get types and everything right was much more ugly though:
select cast('true' as bit) as somefield,...
Am I missing something? Is there actually some built in way to get a true or false value as a boolean without casting?
I want to add to all current answers only one more method to get a
boolean
without casting in SQL Server:Bits are the datatype most commonly used to represent a boolean in TSQL. I typically do something like this
Sql Server doesn't have a boolean datatype you can store in a table, but it does contain a bit data type you can store.
However, the
true
keyword you see IS a boolean value. Sql Server only uses the boolean data type for results for its Comparison Operators, which can return three values, TRUE, FALSE, and UNKNOWN.It is important to know the distinction between the two.
To store boolean values in a table, use the bit datatype. Use
1 for true
,0 for false
, andNull for unknown
.Use 1 or 0, assuming your field is of type bit.
The values 'TRUE' and 'FALSE' are special strings that can be implicitly converted to variables of type bit. This extract is from the MSDN documentation for bit.
Note that these values appear to be case insensitive.
This is why the where clause in your second code snippet works (I assume that field is defined as a bit).
select * from table where field='true'
Without specifying a target type of bit in any way, 'TRUE' and 'FALSE' are no longer treated as special values and remain simple string values. This is why the cast was required in your third snippet.
MSDN states that bit literals (or constants as they are referred to there) are the numbers 0 and 1.
This information may help in some cases but be aware that the literal values 0 and 1 are interpreted as ints rather than bits. The following statements both return 'int' which demonstrates this.