SQL Server Management Studio - Yes/No value type - sql-server

So in Access you can choose the column data type "Yes/No" and it will ask you while typing in the information the option "Yes" and "No". Yet, I do not see any of that on SQL Server Management Studio from Microsoft, I've searched around and seen that "bit" is the type, but when I put bit and I go to add information it appears as a normal column to type information. Or should I know myself to put either 0 or 1?
Also, is 0 true or false?

SQL Server doesn't have a boolean data type. The closest approximation is the bit. But that is a numeric type, not a boolean type. In addition, it only supports 2 values - 0 or 1 (and one non-value, NULL).
However, SQL (standard SQL, as well as T-SQL dialect) describes a Three valued logic - TRUE, FALSE and UNKNOWN. So bit isn't actually the best if you need all 3 states.
When using it, you cannot use that value directly in an if statement for example:
IF CONVERT(bit, 0)
BEGIN
print 'Ok'
END
would not parse and end up in error. So, you would need to write it as below;
IF CONVERT(bit, 0) = 0

In MS SQL bit is equivalent to a boolean.
https://msdn.microsoft.com/en-us/library/ms177603.aspx
Here you can read more about.
1 would be the equivalent of Yes
0 would be the equivalent of No
NULL would be the equivalent of Undefined ( if that exists in Access )

in SQL Server the equivalent to boolean datatype is Bit. Bit can take values 0(false) or 1 (true). If you want to set a default value to your Bit field on creating the table you can set:
...
myBoolean Bit, default 1,
..

Related

Is it possible to un-localize MSSQL-results in VBS?

Sorry if I'm using the wrong terminology - I'm not into MSSQL or VBScript.
I have a given script implementing a SQL query containing
.. AND (rep.is_primary_replica is null or rep.is_primary_replica = ''True'' or rep.is_primary_replica = ''False'') ..
which returns no results on a German server only because rep.is_primary_replica seems to contain ''Wahr'' and ''Falsch'' instead of ''True'' and ''False''
This question is about an at least similar problem.
Unfortunately there is no wtf flag.
Is there a way to do that correctly?
Can I disable localization of string conversions? (in MS SQL Server? VBS?)
Don't let printed values in the script confuse you. There is an implicit conversion from original value to string which depends on the client's (VBScript in your case I think) locale.
Type of the field is_primary_replica here must be bit if the rep is an instance of sys.dm_hadr_database_replica_states view.
If this is the case, it's pointless to check a bit field is Null, or its value equal to True or False, there's no other possibility anyway.
It appears that you can safely remove this condition from the query.
If you insist to include it, use number literals instead.
AND (rep.is_primary_replica is null or rep.is_primary_replica = 1 or rep.is_primary_replica = 0)
This is the proper way to query a bit field. With this way the server's or client's locale configuration won't cause any problems.

SQL Server - Bit data type matches String 'True' and 'False'

I'm not sure if something special has been done with the database that I am working with, but while optimizing old code, I came across the following (sanitized) query:
SELECT Code
FROM GovernmentThing
WHERE IsGovernment = 'True'
I checked the data type for IsGovernment, assuming that it was a varchar(5) or something similar, only to discover that it was a bit field.
I then assumed that the code was bad, and checked by running a query returning the IsGovernment field. To my great surprise, I discovered that the query was returning only rows where IsGovernment was set to 1! Since I then wondered what a check against a string literal 'False' would return, I tested, just to find that only zero values were returned!!
It is possible that I missed something somewhere in the TSQL updates, or that there is some tricky configuration that makes this work, but... I've never heard of this before.
Can someone please enlighten me - is this documented somewhere, or ???
SQL Server 2012
Here's the excerpt from the bit data type documentation that describes this behavior:
The string values TRUE and FALSE can be converted to bit values: TRUE
is converted to 1 and FALSE is converted to 0.

Convert IS NULL to BIT

This might be a very basic question but I just came over it while writing a query.
Why can't SQL Server convert a check for NULL to BIT? I was thinking about something like this:
DECLARE #someVariable INT = NULL;
-- Do something
SELECT CONVERT(BIT, (#someVariable IS NULL))
The expected outcome would then be either 1 or 0.
Use case:
SELECT CONVERT(BIT, (CASE WHEN #someVariable IS NULL THEN 1 ELSE 0 END))
Or use IIF (a little more readable than CASE):
CONVERT(BIT, IIF(#x IS NULL, 0, 1))
not a direct cast
select cast(isnull(#null,1) as bit)
In SQL the language, NULLs are not considered data values. They represent a missing/unknown state. Quoting from Wikipedia's article on SQL NULL:
SQL null is a state (unknown) and not a value. This usage is quite different from most programming languages, where null means not assigned to a particular instance.
This means that any comparison against that UNKNOWN value can only be UNKNOWN itself. Even comparing two NULLs can't return true: if both values are unknown, how can we say that they are equal or not?
IS NULL and IS NOT NULL are predicates that can be used in conditional expressions. That means that they don't return a value themselves. Therefore, they can't be "cast" to a bit , or treated as a boolean.
Basic SQL comparison operators always return Unknown when comparing anything with Null, so the SQL standard provides for two special Null-specific comparison predicates. The IS NULL and IS NOT NULL predicates (which use a postfix syntax) test whether data is, or is not, Null.
Any other way of treating nulls is a vendor-specific extension.
Finally, BIT is not a boolean type, it's just a single-bit number. An optional BOOLEAN type was introduced in SQL 1999 but only PostgreSQL implements it correctly, ie having TRUE, FALSE or UNKNOWN values.
Without a BOOLEAN type you can't really calculate the result of a conditional expression like A AND B or x IS NULL. You can only use functions like NULLIF or COALESCE to replace the NULL value with something else.

What to use when not using Boolean type?

Ok this might be a brain dead question but I am curious.
I often find I have a situation where I need to store 1 of 3 values in a database. For example if my application asks "Is this house for sale?", the user needs to be able to say "yes", "no" but sometimes the user doesn't know. So there is also "I don't know".
I am always tempted to set my data type as Boolean, but of course that only gives me yes or no and usually this is set to no for default.
I am curious as to what data type is set as common practice in this scenario?
I could use an integer and store "1", "2" or "3". Or I could store a string value, or , or ,or.
This is probably a silly question and there maybe a million ways that this is done. but if anyone knows a best practices method and why that would be helpful. Thanks.
In a database a boolean value can actually expresses three states - true, false, and NULL (provided you allow NULL in the column).
Use NULL for "I don't know".
(And probably set the default for the column to NULL as well)
EDIT: Thinking about this for a moment though, this can be problematic depending on your use case. Some high level languages (Java, for one) would end up converting the NULL to false in the query result set.
::shrug:: Use a varchar(1) ('t','f','u') or the smallest integer value available (for space considerations) ... either is fine.
Using an enum is another option, but be aware that it isn't portable (Oracle being the notable problem child).
You could use NULL for "I don't know". You should still be able to have TRUE and FALSE for your boolean type column.
Also you can use
ENUM('first','second','third')
it's can be helpful not just with integer numbers, and with string values too
I'd advise against using NULL for "I don't know" for the following reasons:
In code, you typically check the value of a bool by asking something like this:
IF myBool THEN...
Or
IF NOT myBool THEN...
...as such, you can't tell the difference between false and 'i don't know'
Additionally, I've found it to be a best-practice for my own situation to always have a default value (false) for bools in my database. One direct effect of nulls in a bool field can be errors in 3rd-party tools (such as MS Access making an ODBC connection to a SQL-Server backend) that can't handle nulls in bool fields gracefully / accurately.
So as for what I do recommend -- I'd say find your smallest number data type (like a tinyint in TSQL) and go with that. Then you can have 0 = false, 1 = true, 2 = IDK.
This depends on what data types the server supports. Every data type that is 1 byte can hold up to 255 different values. In MySQL for example, you can use TINYINT. Define numeric constants in your code and use the smalled integer representation possible.

How are NULLs stored in a database?

I'm curious to know how NULLs are stored into a database ?
It surely depends on the database server but I would like to have an general idea about it.
First try:
Suppose that the server put a undefined value (could be anything) into the field for a NULL value.
Could you be very lucky and retrieve the NULL value with
...WHERE field = 'the undefined value (remember, could be anything...)'
Second try:
Does the server have a flag or any meta-data somewhere to indicate this field is NULL ?
Then the server must read this meta data to verify the field.
If the meta-data indicates a NULL value and if the query doesn't have "field IS NULL",
then the record is ignored.
It seems too easy...
MySql uses the second method. It stores an array of bits (one per column) with the data for each row to indicate which columns are null and then leaves the data for that field blank. I'm pretty sure this is true for all other databases as well.
The problem with the first method is, are you sure that whatever value you select for your data won't show up as valid data? For some values (like dates, or floating point numbers) this is true. For others (like integers) this is false.
On PostgreSQL, it uses an optional bitmap with one bit per column (0 is null, 1 is not null). If the bitmap is not present, all columns are not null.
This is completely separate from the storage of the data itself, but is on the same page as the row (so both the row and the bitmap are read together).
References:
http://www.postgresql.org/docs/8.3/interactive/storage-page-layout.html
The server typically uses meta information rather than a magic value. So there's a bit off someplace that specifies whether the field is null.
-Adam
IBM Informix Dynamic Server uses special values to indicate nulls. For example, the valid range of values for a SMALLINT (16-bit, signed) is -32767..+32767. The other value, -32768, is reserved to indicate NULL. Similarly for INTEGER (4-byte, signed) and BIGINT (8-byte, signed). For other types, it uses other special representations (for example, all bits 1 for SQL FLOAT and SMALLFLOAT - aka C double and float, respectively). This means that it doesn't have to use extra space.
IBM DB2 for Linux, Unix, Windows uses extra bytes to store the null indicators; AFAIK, it uses a separate byte for each nullable field, but I could be wrong on that detail.
So, as was pointed out, the mechanisms differ depending on the DBMS.
The problem with special values to indicate NULL is that sooner or later that special value will be inserted. For example, it will be inserted into a table specifying the special NULL indicators for different database servers
| DBServer | SpecialValue |
+--------------+--------------+
| 'Oracle' | 'Glyph' |
| 'SQL Server' | 'Redmond' |
;-)

Resources