FILE 1 CONSTRAINTS
FILE 1 CONSTRAINTS
in this tutorial, you will learn how to use the SQL Server PRIMARY KEY constraint to
create a primary key for a table.
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:
In case the primary key has two or more columns, you must use the PRIMARY
KEY constraint as a table constraint:
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.
The following example creates a table with a primary key that consists of one column:
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:
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:
To make the event_id column as the primary key, you use the following ALTER
TABLE statement:
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.
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).
The following statements drop the vendors table and recreate it with a FOREIGN
KEY constraint:
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_constraint_name
FOREIGN KEY (column_1, column2,...)
REFERENCES parent_table_name(column1,column2,..)
Code language: SQL (Structured Query Language) (sql)
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:
In this case, SQL Server will automatically generate a name for the FOREIGN
KEY constraint.
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.
Second, insert a new vendor with a vendor group into the vendors table:
Third, try to insert a new vendor whose vendor group does not exist in
the vendor_groups table:
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:
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
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.
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.
The CHECK constraint allows you to specify the values in a column that must satisfy a
Boolean expression.
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:
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.
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:
The CHECK constraints reject values that cause the Boolean expression evaluates
to FALSE.
For example, you can insert a product whose unit price is NULL as shown in the
following query:
(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.
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:
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:
or even:
You can also assign a name to a table constraint in the same way as a column
constraint:
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:
To add a CHECK constraint to the test.products table, you use the following statement:
To add a new column with a CHECK constraint, you use the following statement:
To add a CHECK constraint named valid_price, you use the following statement:
To remove a CHECK constraint, you use the ALTER TABLE DROP CONSTRAINT statement:
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:
For example:
To disable a CHECK constraint for insert or update, you use the following statement:
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 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:
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:
The statement works as expected. However, the following statement fails due to the
duplicate email:
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:
The following are the benefits of assigning a UNIQUE constraint a specific name:
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.
The following statement inserts a row whose value in the email column is NULL:
Now, if you try to insert one more NULL into the email column, you will get an error:
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:
Similarly, the following statement adds a UNIQUE constraint to the phone column:
To define a UNIQUE constraint, you use the ALTER TABLE DROP CONSTRAINT statement as
follows:
The following statement removes the unique_phone constraint from the hr.person table:
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.
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:
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.
To add the NOT NULL constraint to an existing column, you follow these steps:
UPDATE table_name
SET column_name = <value>
WHERE column_name IS 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)
To remove the NOT NULL constraint from a column, you use the ALTER TABLE ALTER
COLUMN statement as follows:
For example, to remove the NOT NULL constraint from the phone column, you use the
following statement:
In this tutorial, you have learned how to use the SQL Server NOT NULL constraint to
enforce a column not accept NULL.