Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server NULL constraint

Is is possible in SQL Server 2008 to create such a constraint that would restrict two columns to have NULL values at the same time? So that

Column1 Column2
NULL    NULL   -- not allowed
1       NULL   -- allowed
NULL    2      -- allowed
2       3      -- allowed
like image 909
Max Avatar asked Sep 30 '10 18:09

Max


People also ask

Is NULL () in SQL?

SQL Server ISNULL() FunctionThe ISNULL() function returns a specified value if the expression is NULL. If the expression is NOT NULL, this function returns the expression.

What is difference between unique and NOT NULL constraint?

A primary key must be unique and non-null, so they're the same from that standpoint. However, a table can only have one primary key, while you can have multiple unique non-null keys. Most systems also use metadata to tag primary keys separately so that they can be identified by designers, etc.

Which constraints will allow NULL?

Unlike PRIMARY KEY constraints, UNIQUE constraints allow for the value NULL. However, as with any value participating in a UNIQUE constraint, only one null value is allowed per column. A UNIQUE constraint can be referenced by a FOREIGN KEY constraint.

What is the difference between primary key and NOT NULL constraint?

Primary key will not accept NULL values whereas Unique key can accept NULL values. A table can have only one primary key whereas there can be multiple unique key on a table. A Clustered index automatically created when a primary key is defined whereas Unique key generates the non-clustered index.


1 Answers

ALTER TABLE MyTable WITH CHECK 
   ADD CONSTRAINT CK_MyTable_ColumNulls CHECK (Column1 IS NOT NULL OR Column2 IS NOT NULL)

As part of the create

CREATE TABLE MyTable (
 Column1 int NULL,
 Column2 int NULL,

 CONSTRAINT CK_MyTable_ColumNulls CHECK (Column1 IS NOT NULL OR Column2 IS NOT NULL)
)
like image 101
gbn Avatar answered Nov 15 '22 21:11

gbn