0% found this document useful (0 votes)
26 views

FILE 1 CONSTRAINTS

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

FILE 1 CONSTRAINTS

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

SQL Server PRIMARY KEY

in this tutorial, you will learn how to use the SQL Server PRIMARY KEY constraint to
create a primary key for a table.

Introduction to SQL Server PRIMARY KEY constraint

A primary key is a column or a group of columns that uniquely identifies each row in a
table. You create a primary key for a table by using the PRIMARY KEY constraint.

If the primary key consists of only one column, you can define use PRIMARY
KEY constraint as a column constraint:

CREATE TABLE table_name


(
pk_column data_type PRIMARY KEY,
...
);
Code language: SQL (Structured Query Language) (sql)

In case the primary key has two or more columns, you must use the PRIMARY
KEY constraint as a table constraint:

CREATE TABLE table_name


(
pk_column_1 data_type,
pk_column_2 data type,
...
PRIMARY KEY (pk_column_1, pk_column_2)
);
Code language: SQL (Structured Query Language) (sql)

Each table can contain only one primary key. All columns that participate in the
primary key must be defined as NOT NULL. SQL Server automatically sets the NOT
NULL constraint for all the primary key columns if the NOT NULL constraint is not
specified for these columns.

SQL Server also automatically creates a unique clustered index (or a non-clustered
index if specified as such) when you create a primary key.

SQL Server PRIMARY KEY constraint examples

The following example creates a table with a primary key that consists of one column:

CREATE TABLE sales.activities


(
activity_id INT PRIMARY KEY IDENTITY,
activity_name VARCHAR (255) NOT NULL,
activity_date DATE NOT NULL
);
Code language: SQL (Structured Query Language) (sql)

In this sales.activities table, the activity_id column is the primary key column. It means
the activity_id column contains unique values.
The IDENTITY property is used for the activity_id column to automatically generate
unique integer values.

The following statement creates a new table named sales.participants whose primary
key consists of two columns:

CREATE TABLE sales.participants


(
activity_id int,
customer_id int,
PRIMARY KEY(activity_id, customer_id)
);
Code language: SQL (Structured Query Language) (sql)

In this example, the values in either activity_id or customer_id column can be duplicate,
but each combination of values from both columns must be unique.

Typically, a table always has a primary key defined at the time of creation. However,
sometimes, an existing table may not have a primary key defined. In this case, you
can add a primary key to the table by using the ALTER TABLE statement. Consider the
following example:

The following statement creates a table without a primary key:

CREATE TABLE sales.events


(
event_id INT NOT NULL,
event_name VARCHAR(255),
start_date DATE NOT NULL,
duration DEC(5,2)
);
Code language: SQL (Structured Query Language) (sql)

To make the event_id column as the primary key, you use the following ALTER
TABLE statement:

ALTER TABLE sales.events


ADD PRIMARY KEY(event_id);
Code language: SQL (Structured Query Language) (sql)

Note that if the sales.events table already has data, before promoting
the event_id column as the primary key, you must ensure that the values in
the event_id are unique.

In this tutorial, you have learned how to use the SQL Server PRIMARY KEY constraint to
create a primary key for a table.

SQL Server FOREIGN KEY


In this tutorial, you will learn how to use the SQL Server foreign key constraint to
enforce a link between the data in two tables.

Introduction to the SQL Server foreign key constraint

Consider the following vendor_groups and vendors tables:


CREATE TABLE procurement.vendor_groups (
group_id INT IDENTITY PRIMARY KEY,
group_name VARCHAR (100) NOT NULL
);

CREATE TABLE procurement.vendors (


vendor_id INT IDENTITY PRIMARY KEY,
vendor_name VARCHAR(100) NOT NULL,
group_id INT NOT NULL,
);
Code language: SQL (Structured Query Language) (sql)

Each vendor belongs to a vendor group and each vendor group may have zero or
more vendors. The relationship between the vendor_groups and vendors tables is one-to-
many.

For each row in the vendors table, you can always find a corresponding row in
the vendor_groups table.

However, with the current tables setup, you can insert a row into the vendors table
without a corresponding row in the vendor_groups table. Similarly, you can also delete a
row in the vendor_groups table without updating or deleting the corresponding rows in
the vendors table that results in orphaned rows in the vendors table.

To enforce the link between data in the vendor_groups and vendors tables, you need to
establish a foreign key in the vendors table.

A foreign key is a column or a group of columns in one table that uniquely identifies a
row of another table (or the same table in case of self-reference).

To create a foreign key, you use the FOREIGN KEY constraint.

The following statements drop the vendors table and recreate it with a FOREIGN
KEY constraint:

DROP TABLE vendors;

CREATE TABLE procurement.vendors (


vendor_id INT IDENTITY PRIMARY KEY,
vendor_name VARCHAR(100) NOT NULL,
group_id INT NOT NULL,
CONSTRAINT fk_group FOREIGN KEY (group_id)
REFERENCES procurement.vendor_groups(group_id)
);
Code language: SQL (Structured Query Language) (sql)

The vendor_groups table now is called the parent table that is the table to which the
foreign key constraint references. The vendors table is called the child table that is
the table to which the foreign key constraint is applied.

In the statement above, the following clause creates a FOREIGN KEY constraint
named fk_group that links the group_id in the vendors table to the group_id in
the vendor_groups table:

CONSTRAINT fk_group FOREIGN KEY (group_id) REFERENCES


procurement.vendor_groups(group_id)
Code language: SQL (Structured Query Language) (sql)
SQL Server FOREIGN KEY constraint syntax

The general syntax for creating a FOREIGN KEY constraint is as follows:

CONSTRAINT fk_constraint_name
FOREIGN KEY (column_1, column2,...)
REFERENCES parent_table_name(column1,column2,..)
Code language: SQL (Structured Query Language) (sql)

Let’s examine this syntax in detail.

First, specify the FOREIGN KEY constraint name after the CONSTRAINT keyword. The
constraint name is optional therefore it is possible to define a FOREIGN KEY constraint as
follows:

FOREIGN KEY (column_1, column2,...)


REFERENCES parent_table_name(column1,column2,..)
Code language: SQL (Structured Query Language) (sql)

In this case, SQL Server will automatically generate a name for the FOREIGN
KEY constraint.

Second, specify a list of comma-separated foreign key columns enclosed by


parentheses after the FOREIGN KEY keyword.

Third, specify the name of the parent table to which the foreign key references and a
list of comma-separated columns that has a link with the column in the child table.

SQL Server FOREIGN KEY constraint example

First, insert some rows into the vendor_groups table:

INSERT INTO procurement.vendor_groups(group_name)


VALUES('Third-Party Vendors'),
('Interco Vendors'),
('One-time Vendors');
Code language: SQL (Structured Query Language) (sql)

Second, insert a new vendor with a vendor group into the vendors table:

INSERT INTO procurement.vendors(vendor_name, group_id)


VALUES('ABC Corp',1);
Code language: SQL (Structured Query Language) (sql)

The statement worked as expected.

Third, try to insert a new vendor whose vendor group does not exist in
the vendor_groups table:

INSERT INTO procurement.vendors(vendor_name, group_id)


VALUES('XYZ Corp',4);
Code language: SQL (Structured Query Language) (sql)

SQL Server issued the following error:


The INSERT statement conflicted with the FOREIGN KEY constraint
"fk_group". The conflict occurred in database "BikeStores", table
"procurement.vendor_groups", column 'group_id'.
Code language: SQL (Structured Query Language) (sql)

In this example, because of the FOREIGN KEY constraint, SQL Server rejected the insert
and issued an error.

Referential actions

The foreign key constraint ensures referential integrity. It means that you can only
insert a row into the child table if there is a corresponding row in the parent table.

Besides, the foreign key constraint allows you to define the referential actions when
the row in the parent table is updated or deleted as follows:

FOREIGN KEY (foreign_key_columns)


REFERENCES parent_table(parent_key_columns)
ON UPDATE action
ON DELETE action;
Code language: SQL (Structured Query Language) (sql)

The ON UPDATE and ON DELETE specify which action will execute when a row in the
parent table is updated and deleted. The following are permitted actions : NO
ACTION, CASCADE, SET NULL, and SET DEFAULT

Delete actions of rows in the parent table

If you delete one or more rows in the parent table, you can set one of the following
actions:

 ON DELETE NO ACTION: SQL Server raises an error and rolls back the delete action on the
row in the parent table.
 ON DELETE CASCADE: SQL Server deletes the rows in the child table that is
corresponding to the row deleted from the parent table.
 ON DELETE SET NULL: SQL Server sets the rows in the child table to NULL if the
corresponding rows in the parent table are deleted. To execute this action, the foreign
key columns must be nullable.
 ON DELETE SET DEFAULT SQL Server sets the rows in the child table to their default
values if the corresponding rows in the parent table are deleted. To execute this action,
the foreign key columns must have default definitions. Note that a nullable column has
a default value of NULL if no default value specified.

By default, SQL Server applies ON DELETE NO ACTION if you don’t explicitly specify any
action.

Update action of rows in the parent table

If you update one or more rows in the parent table, you can set one of the following
actions:

 ON UPDATE NO ACTION: SQL Server raises an error and rolls back the update action on
the row in the parent table.
 ON UPDATE CASCADE: SQL Server updates the corresponding rows in the child table
when the rows in the parent table are updated.
 ON UPDATE SET NULL: SQL Server sets the rows in the child table to NULL when the
corresponding row in the parent table is updated. Note that the foreign key columns
must be nullable for this action to execute.
 ON UPDATE SET DEFAULT: SQL Server sets the default values for the rows in the child
table that have the corresponding rows in the parent table updated.

In this tutorial, you have learned how to use the SQL Server foreign key constraint to
enforce the referential integrity between tables.

SQL Server CHECK Constraint


in this tutorial, you will learn how to use the SQL Server CHECK constraint to enforce
domain integrity.

Introduction to SQL Server CHECK constraint

The CHECK constraint allows you to specify the values in a column that must satisfy a
Boolean expression.

For example, to require positive unit prices, you can use:

CREATE SCHEMA test;


GO

CREATE TABLE test.products(


product_id INT IDENTITY PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
unit_price DEC(10,2) CHECK(unit_price > 0)
);
Code language: SQL (Structured Query Language) (sql)

As you can see, the CHECK constraint definition comes after the data type. It consists
of the keyword CHECK followed by a logical expression in parentheses:

CHECK(unit_price > 0)
Code language: SQL (Structured Query Language) (sql)

You can also assign the constraint a separate name by using the CONSTRAINT keyword
as follows:

CREATE TABLE test.products(


product_id INT IDENTITY PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
unit_price DEC(10,2) CONSTRAINT positive_price CHECK(unit_price > 0)
);
Code language: SQL (Structured Query Language) (sql)

The explicit names help classify the error messages and allow you to refer to the
constraints when you want to modify them.

If you don’t specify a constraint name this way, SQL Server automatically generates a
name for you.

See the following insert statement:


INSERT INTO test.products(product_name, unit_price)
VALUES ('Awesome Free Bike', 0);
Code language: SQL (Structured Query Language) (sql)

SQL Server issued the following error:

The INSERT statement conflicted with the CHECK constraint


"positive_price". The conflict occurred in database "BikeStores", table
"test.products", column 'unit_price'.
Code language: SQL (Structured Query Language) (sql)

The error occurred because the unit price is not greater than zero as specified in
the CHECK constraint.

The following statement works fine because the logical expression defined in
the CHECK constraint evaluates to TRUE:

INSERT INTO test.products(product_name, unit_price)


VALUES ('Awesome Bike', 599);
Code language: SQL (Structured Query Language) (sql)
SQL Server CHECK constraint and NULL

The CHECK constraints reject values that cause the Boolean expression evaluates
to FALSE.

Because NULL evaluates to UNKNOWN, it can be used in the expression to bypass a


constraint.

For example, you can insert a product whose unit price is NULL as shown in the
following query:

INSERT INTO test.products(product_name, unit_price)


VALUES ('Another Awesome Bike', NULL);
Code language: SQL (Structured Query Language) (sql)

Here is the output:

(1 row affected)
Code language: SQL (Structured Query Language) (sql)

SQL Server inserted NULL into the unit_price column and did not return an error.

To fix this, you need to use a NOT NULL constraint for the unit_price column.

CHECK constraint referring to multiple columns

A CHECK constraint can refer to multiple columns. For instance, you store a regular and
discounted prices in the test.products table and you want to ensure that the discounted
price is always lower than the regular price:

CREATE TABLE test.products(


product_id INT IDENTITY PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
unit_price DEC(10,2) CHECK(unit_price > 0),
discounted_price DEC(10,2) CHECK(discounted_price > 0),
CHECK(discounted_price < unit_price)
);
Code language: SQL (Structured Query Language) (sql)

The first two constraints for unit_price and discounted_price should look familiar.

The third constraint uses a new syntax which is not attached to a particular column.
Instead, it appears as a separate line item in the comma-separated column list.

The first two column constraints are column constraints, whereas the third one is a
table constraint.

Note that you can write column constraints as table constraints. However, you cannot
write table constraints as column constraints. For example, you can rewrite the above
statement as follows:

CREATE TABLE test.products(


product_id INT IDENTITY PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
unit_price DEC(10,2),
discounted_price DEC(10,2),
CHECK(unit_price > 0),
CHECK(discounted_price > 0),
CHECK(discounted_price > unit_price)
);
Code language: SQL (Structured Query Language) (sql)

or even:

CREATE TABLE test.products(


product_id INT IDENTITY PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
unit_price DEC(10,2),
discounted_price DEC(10,2),
CHECK(unit_price > 0),
CHECK(discounted_price > 0 AND discounted_price > unit_price)
);
Code language: SQL (Structured Query Language) (sql)

You can also assign a name to a table constraint in the same way as a column
constraint:

CREATE TABLE test.products(


product_id INT IDENTITY PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
unit_price DEC(10,2),
discounted_price DEC(10,2),
CHECK(unit_price > 0),
CHECK(discounted_price > 0),
CONSTRAINT valid_prices CHECK(discounted_price > unit_price)
);
Code language: SQL (Structured Query Language) (sql)
Add CHECK constraints to an existing table

To add a CHECK constraint to an existing table, you use the ALTER TABLE ADD
CONSTRAINT statement.
Suppose you have the following test.products table:

CREATE TABLE test.products(


product_id INT IDENTITY PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
unit_price DEC(10,2) NOT NULL
);
Code language: SQL (Structured Query Language) (sql)

To add a CHECK constraint to the test.products table, you use the following statement:

ALTER TABLE test.products


ADD CONSTRAINT positive_price CHECK(unit_price > 0);
Code language: SQL (Structured Query Language) (sql)

To add a new column with a CHECK constraint, you use the following statement:

ALTER TABLE test.products


ADD discounted_price DEC(10,2)
CHECK(discounted_price > 0);
Code language: SQL (Structured Query Language) (sql)

To add a CHECK constraint named valid_price, you use the following statement:

ALTER TABLE test.products


ADD CONSTRAINT valid_price
CHECK(unit_price > discounted_price);
Code language: SQL (Structured Query Language) (sql)
Remove CHECK constraints

To remove a CHECK constraint, you use the ALTER TABLE DROP CONSTRAINT statement:

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;
Code language: SQL (Structured Query Language) (sql)

If you assign a CHECK constraint a specific name, you can refer the name in the
statement.

However, in case you did not assign the CHECK constraint a particular name, then you
need to find it using the following statement:

EXEC sp_help 'table_name';


Code language: SQL (Structured Query Language) (sql)

For example:

EXEC sp_help 'test.products';


Code language: SQL (Structured Query Language) (sql)

This statement issues a lot of information including constraint names:


The following statement drops the positive_price constraint:

ALTER TABLE test.products


DROP CONSTRAINT positive_price;
Code language: SQL (Structured Query Language) (sql)
Disable CHECK constraints for insert or update

To disable a CHECK constraint for insert or update, you use the following statement:

ALTER TABLE table_name


NOCHECK CONSTRAINT constraint_name;
Code language: SQL (Structured Query Language) (sql)

The following statement disables the valid_price constraint:

ALTER TABLE test.products


NO CHECK CONSTRAINT valid_price;
Code language: SQL (Structured Query Language) (sql)

In this tutorial, you have learned how to use the SQL Server CHECK constraint to limit
the values that can be inserted or updated to one or more columns in a table.

SQL Server UNIQUE Constraint


in this tutorial, you will learn how to use the SQL Server UNIQUE constraint to ensure
the uniqueness of data contained in a column or a group of columns.

Introduction to SQL Server UNIQUE constraint

SQL Server UNIQUE constraints allow you to ensure that the data stored in a column, or
a group of columns, is unique among the rows in a table.

The following statement creates a table whose data in the email column is unique
among the rows in the hr.persons table:

CREATE SCHEMA hr;


GO

CREATE TABLE hr.persons(


person_id INT IDENTITY PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE
);
Code language: SQL (Structured Query Language) (sql)

In this syntax, you define the UNIQUE constraint as a column constraint. You can also
define the UNIQUE constraint as a table constraint, like this:
CREATE TABLE hr.persons(
person_id INT IDENTITY PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255),
UNIQUE(email)
);
Code language: SQL (Structured Query Language) (sql)

Behind the scenes, SQL Server automatically creates a UNIQUE index to enforce the
uniqueness of data stored in the columns that participate in the UNIQUE constraint.
Therefore, if you attempt to insert a duplicate row, SQL Server rejects the change and
returns an error message stating that the UNIQUE constraint has been violated.

The following statement inserts a new row into the hr.persons table:

INSERT INTO hr.persons(first_name, last_name, email)


VALUES('John','Doe','[email protected]');
Code language: SQL (Structured Query Language) (sql)

The statement works as expected. However, the following statement fails due to the
duplicate email:

INSERT INTO hr.persons(first_name, last_name, email)


VALUES('Jane','Doe','[email protected]');
Code language: SQL (Structured Query Language) (sql)

SQL Server issued the following error message:

Violation of UNIQUE KEY constraint 'UQ__persons__AB6E616417240E4E'.


Cannot insert duplicate key in object 'hr.persons'. The duplicate key
value is ([email protected]).
Code language: Shell Session (shell)

If you don’t specify a separate name for the UNIQUE constraint, SQL Server will
automatically generate a name for it. In this example, the constraint name
is UQ__persons__AB6E616417240E4E, which is not quite readable.

To assign a particular name to a UNIQUE constraint, you use the CONSTRAINT keyword as
follows:

CREATE TABLE hr.persons (


person_id INT IDENTITY PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255),
CONSTRAINT unique_email UNIQUE(email)
);
Code language: SQL (Structured Query Language) (sql)

The following are the benefits of assigning a UNIQUE constraint a specific name:

 It easier to classify the error message.


 You can reference the constraint name when you want to modify it.
UNIQUE constraint vs. PRIMARY KEY constraint

Although both UNIQUE and PRIMARY KEY constraints enforce the uniqueness of data, you
should use the UNIQUE constraint instead of PRIMARY KEY constraint when you want to
enforce the uniqueness of a column, or a group of columns, that are not the primary
key columns.

Different from PRIMARY KEY constraints, UNIQUE constraints allow NULL.


Moreover, UNIQUE constraints treat the NULL as a regular value, therefore, it only allows
one NULL per column.

The following statement inserts a row whose value in the email column is NULL:

INSERT INTO hr.persons(first_name, last_name)


VALUES('John','Smith');
Code language: SQL (Structured Query Language) (sql)

Now, if you try to insert one more NULL into the email column, you will get an error:

INSERT INTO hr.persons(first_name, last_name)


VALUES('Lily','Bush');
Code language: SQL (Structured Query Language) (sql)

Here is the output:

Violation of UNIQUE KEY constraint 'UQ__persons__AB6E616417240E4E'.


Cannot insert duplicate key in object 'hr.persons'. The duplicate key
value is (<NULL>).
Code language: SQL (Structured Query Language) (sql)
UNIQUE constraints for a group of columns

To define a UNIQUE constraint for a group of columns, you write it as a table constraint
with column names separated by commas as follows:

CREATE TABLE table_name (


key_column data_type PRIMARY KEY,
column1 data_type,
column2 data_type,
column3 data_type,
...,
UNIQUE (column1,column2)
);
Code language: SQL (Structured Query Language) (sql)

The following example creates a UNIQUE constraint that consists of two


columns person_id and skill_id:

CREATE TABLE hr.person_skills (


id INT IDENTITY PRIMARY KEY,
person_id int,
skill_id int,
updated_at DATETIME,
UNIQUE (person_id, skill_id)
);
Code language: SQL (Structured Query Language) (sql)
Add UNIQUE constraints to existing columns

When you add a UNIQUE constraint to an existing column or a group of columns in a


table, SQL Server first examines the existing data in these columns to ensure that all
values are unique. If SQL Server finds the duplicate values, then it returns an error
and does not add the UNIQUE constraint.

The following shows the syntax of adding a UNIQUE constraint to a table:

ALTER TABLE table_name


ADD CONSTRAINT constraint_name
UNIQUE(column1, column2,...);
Code language: SQL (Structured Query Language) (sql)

Suppose you have the following hr.persons table:

CREATE TABLE hr.persons (


person_id INT IDENTITY PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255),
phone VARCHAR(20),
);
Code language: SQL (Structured Query Language) (sql)

The following statement adds a UNIQUE constraint to the email column:

ALTER TABLE hr.persons


ADD CONSTRAINT unique_email UNIQUE(email);
Code language: SQL (Structured Query Language) (sql)

Similarly, the following statement adds a UNIQUE constraint to the phone column:

ALTER TABLE hr.persons


ADD CONSTRAINT unique_phone UNIQUE(phone);
Code language: SQL (Structured Query Language) (sql)
Delete UNIQUE constraints

To define a UNIQUE constraint, you use the ALTER TABLE DROP CONSTRAINT statement as
follows:

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;
Code language: SQL (Structured Query Language) (sql)

The following statement removes the unique_phone constraint from the hr.person table:

ALTER TABLE hr.persons


DROP CONSTRAINT unique_phone;
Code language: SQL (Structured Query Language) (sql)
Modify UNIQUE constraints

SQL Server does not have any direct statement to modify a UNIQUE constraint,
therefore, you need to drop the constraint first and recreate it if you want to change
the constraint.
In this tutorial, you have learned how to use the SQL Server UNIQUE constraint to make
sure that the data contained in a column or a group of columns is unique.

SQL Server NOT NULL Constraint


in this tutorial, you will learn how to use the SQL Server NOT NULL constraint to ensure
data contained in a column is not NULL.

Introduction to SQL Server NOT NULL constraint

The SQL Server NOT NULL constraints simply specify that a column must not assume
the NULL.

The following example creates a table with NOT NULL constraints for the
columns: first_name, last_name, and email:

CREATE SCHEMA hr;


GO

CREATE TABLE hr.persons(


person_id INT IDENTITY PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(20)
);
Code language: SQL (Structured Query Language) (sql)

Note that the NOT NULL constraints are always written as column constraints.

By default, if you don’t specify the NOT NULL constraint, SQL Server will allow the
column to accepts NULL. In this example, the phone column can accept NULL.

Add NOT NULL constraint to an existing column

To add the NOT NULL constraint to an existing column, you follow these steps:

First, update the table so there is no NULL in the column:

UPDATE table_name
SET column_name = <value>
WHERE column_name IS NULL;
Code language: SQL (Structured Query Language) (sql)

Second, alter the table to change the property of the column:

ALTER TABLE table_name


ALTER COLUMN column_name data_type NOT NULL;
Code language: SQL (Structured Query Language) (sql)

For example, to add the NOT NULL constraint to the phone column of the hr.persons
table, you use the following statements:

First, if a person does not have a phone number, then update the phone number to
the company phone number e.g., (408) 123 4567:
UPDATE hr.persons
SET phone = "(408) 123 4567"
WHER phone IS NULL;
Code language: SQL (Structured Query Language) (sql)

Second, modify the property of the phone column:

ALTER TABLE hr.persons


ALTER COLUMN phone VARCHAR(20) NOT NULL;
Code language: SQL (Structured Query Language) (sql)
Removing NOT NULL constraint

To remove the NOT NULL constraint from a column, you use the ALTER TABLE ALTER
COLUMN statement as follows:

ALTER TABLE table_name


ALTER COLUMN column_name data_type NULL;
Code language: SQL (Structured Query Language) (sql)

For example, to remove the NOT NULL constraint from the phone column, you use the
following statement:

ALTER TABLE hr.pesons


ALTER COLUMN phone VARCHAR(20) NULL;
Code language: SQL (Structured Query Language) (sql)

In this tutorial, you have learned how to use the SQL Server NOT NULL constraint to
enforce a column not accept NULL.

You might also like