Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bit type : default to '0' instead of NULL

Tags:

sql-server

By default sql server assigns boolean fields a NULL value. How can I tell it to use '0' as default? I tried setting the default value to ((0)) but it still persists on the NULL.

like image 977
user763539 Avatar asked May 16 '17 08:05

user763539


People also ask

What is the default value of bit?

Bookmark this question. Show activity on this post. By default sql server assigns boolean fields a NULL value.

Can bit data type be NULL?

Multiple bit datatypes in a table are collected into bytes. For example, 7 bit columns fit into 1 byte; 9 bit columns take 2 bytes. Columns with a datatype of bit cannot be NULL and cannot have indexes on them.

How do I add a bit type to a column in SQL Server?

To insert a new value to the BIT column, use INSERT statement: INSERT INTO table_name (bit_column) VALUES (1); You can also use TRUE and FALSE as the inputs for the BIT columns, SQL Server will automatically convert them as follow: TRUE will be converted to 1.


2 Answers

Here's a sample with a non nullable bit column with the default specified, just run the below in Management Studio:

CREATE TABLE #temp     (       id INT ,       myBit BIT NOT NULL DEFAULT 0  -- not null with default of false     );  INSERT  INTO #temp         ( id )  -- only insert to id col, the default will set itself VALUES  ( 123 );  INSERT INTO #temp         ( id, myBit ) VALUES  ( 456, 1 )  -- this insert adds a true value to override the default  SELECT  * FROM    #temp;  DROP TABLE #temp; 

Produces:

id  myBit 123 0 456 1 
like image 150
Tanner Avatar answered Sep 19 '22 13:09

Tanner


ALTER TABLE [table name] ADD [column name] BIT NOT NULL DEFAULT 0; 
like image 36
Alexey Varentsov Avatar answered Sep 19 '22 13:09

Alexey Varentsov