5

If I set a Record in Sql with a Default constraint like

[Publicbit] BIT DEFAULT ((0)),

Do I need to set the NULL/NOTNULL Constraint?

Edit: I am using a boolean but please expand your answer to other datatypes.

asked Aug 28, 2013 at 17:24
2
  • @marc_s Guessing SQL Server given the brackets and BIT type. Commented Aug 28, 2013 at 17:27
  • 1
    @marc_s thanks for the reply I am using MSSQL Commented Aug 28, 2013 at 17:27

4 Answers 4

4

You never need the Null constraints, but the default value won't guard your table against explicit NULL's. So you should use a NOT NULL constraint if you want to enforce this condition.

use tempdb
go
CREATE TABLE example
(
 id BIT DEFAULT (0)
)
INSERT example (id) VALUES (null)
SELECT * FROM example
answered Aug 28, 2013 at 17:30

1 Comment

Hint: I would always recommend to explicitly name your (default) constraints: id BIT CONSTRAINT DF_Example_ID DEFAULT (0) so that you'll have an well-known name for your constraint if you ever need to disable and/or drop it.
3

You should specify NOT NULL, to protect against a NULL from getting into this record. It sounds like the only valid values you want are 0 and 1. If someone (or you in the future) writes a record (or code) passing in a NULL for this column, then it will be allowed unless you specified NOT NULL.

By specifying a DEFAULT, you are only protecting against a NULL value if the SQL INSERT statement doesn't include that column.

answered Aug 28, 2013 at 17:29

Comments

2

No, they are optional.

column_name 
 ...
 [ NULL | NOT NULL ]

You shouldn't expect a NULL when your options are 0/1.

answered Aug 28, 2013 at 17:26

2 Comments

what about other datatypes such as NVARCHAR and Ints?
@FloodGravemind It depends on your data requirements. I don't want to say there's a general rule, but given that those attributes are optional then I suggest that you don't need these attributes.
1

These are just optional. It is up to you if you want to specify it or not

From MSDN:

Determines whether null values are allowed in the column. NULL is not strictly a constraint but can be specified just like NOT NULL.

answered Aug 28, 2013 at 17:26

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.