Loading

Microsoft SQL Server

What is Constraints in SQL Server?. The Complete Microsoft SQL Server Developer Course 2023 [Videos].

In this article, I am going to discuss Constraints in SQL Server with examples. Please read our previous article where we discussed SQL Server Data Types in detail. As part of this article. we are going to discuss the following things in detail.

  1. What is Data Integrity?
  2. What are SQL Server constraints?
  3. Why do we need SQL Server constraints?
  4. Different types of constraints in SQL Server?
  5. Understanding NULL in SQL Server
  6. What is Default, Not Null, Unique and Check Constraint in SQL Server?
  7. How to Impose Constraint on Table.
  8. Imposing Constraint on Column.
  9. What are composite constraints? 

What is Data Integrity in SQL Server?

Data integrity means the data contained in the database is accurate, consistent, and reliable. To provide data integrity, RDBMS provides us a set of integrity constraints that ensures that the data entered into the database is going to be accurate, consistent, and reliable. This is the reason why the end-user can trust the data.

What is a Constraint in SQL Server?

We can define the SQL Server Constraint as a property that can be assigned to a column or columns of a table. The SQL Server Constraints are mainly used to maintain data integrity. 

Why do we need SQL Server Constraints?

The SQL Server Constraints are used to restrict the insertion of unwanted data in any columns i.e. they are mainly used to maintain data integrity. We can create the constraint on single or multiple columns of a table in SQL Server.

What are the different types of SQL Server Constraints available?

SQL Server supports six types of constraints for maintaining data integrity. They are as follows

  1. Default Constraint
  2. UNIQUE KEY constraint
  3. NOT NULL constraint
  4. CHECK KEY constraint
  5. PRIMARY KEY constraint
  6. FOREIGN KEY constraint.

Note: Constraints are imposed on columns of a table.

Before going to understand the constraints in SQL Server, first, we need to understand NULL in SQL Server.

Understanding NULL in SQL Server:

NULL represents the absence of data or value. Its neither ZERO nor EMPTY. In order to understand this, let us create the following Employee table. Here, EmployeeID is an int data type and it is not null. On the other hand, Name and Code fields are NULL types means they accept a NULL value.

Understanding Empty in SQL Server

Once you create the above Employee table, let us add some data as shown below.

Understanding zero in SQL Server

As you can see for employee id 2, the code is 0 and for employee id 3, the name is empty and the code is 0. Here, zero and empty do not represent NULL, You need to consider them as values.

Whenever you dont have any value, then you need to put it as Null. For example, let say we have an employee whose code is not yet generated and supposed to come in later. Then, in that case, you can put a NULL in the code as shown below which means the code is absent at the moment.

Understanding NULL in SQL Server

Note: When you need to tell that the data is not present or absent, then you need to put NULL. The short-cut key to put NULL is (CTRL + 0). 

Once we understand what exactly NULL is, now let us proceed to constraints.

Default Constraint in SQL Server

The Default constraint in SQL Server is used to fill the column with a default value that is defined during the creation of a table if the user does not supply any value while inserting the data. In simple words, we can say that Default constraints enable the SQL Server to insert a default value to a column when the user doesnt specify a value.

Note: IDENTITY and timestamp columns cant be associated with the default constraint.

Let us understand Default Constraint with an example. In order to understand this, first, create the Employee table by executing the following SQL Script. 

CREATE TABLE Employee (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT "Mumbai",
DateOfBirth date DEFAULT GETDATE(),
Salary DECIMAL (18, 2) DEFAULT 5000.00
)

As you can see in the above create table statement, here, we created the City, DateOfBirth, and Salary columns with the Default Constraint. So, while inserting the data into the Employee table, if the user does not specify the values for City, DateOfBirth, and Salary columns, then the default values we specified here are going to be stored in the store City, DateOfBirth, and Salary columns.

Lets insert a record into the Employee table by executing the following Insert statement.

As you can see, in the above insert statement, we have not specified the values for the City, DateOfBirth, and Salary columns, so they should the default values. In order to make sure, it takes the default values, let issue a select query as shown below.

Select * from Employee

Once you execute the above Select query. It gives us the below output and you can see the City, DateOfBirth, and Salary columns are filled with the default values.

SQL Server Constraints - Data in SQL

NOT NULL Constraint in SQL Server:

When you want a column not to accept NULL then you need to apply the NOT NULL constraint to that column. That means this constraint is used to avoid NULL values but it accepted duplicate values into a column.

A table can contain any number of NOT NULL Constraints. We can apply the NOT NULL constraint on any data type column such as integer, character, money, etc.

Let us understand this with an example. To understand this concept, first, let us create the Customer table by executing the following SQL Script. As you can see, we applied the NOT NULL constraint to all three fields of the Customer table.

CREATE TABLE customer
(
id INT NOT NULL,
name VARCHAR(30) NOT NULL,
mobno CHAR(10) NOT NULL
)

Once you create the above Customer table, now try to execute the following SQL statements. The first, two statements are executed as expected as they dont have any null values.


But when you try to execute the third insert statement, it will give you the below error.

SQL Server Constraints

Note: When we INSERT a null value into a column on which the NOT NULL constraint is imposed. The execution of the insert statement is terminated by displaying a user-friendly message telling the reason for termination and also specifies the database, the table and the column where the problem got occurred.

UNIQUE Constraint in SQL Server:

When you want a column or columns not to accept any duplicate values, then you need to apply UNIQUE Constraint to that column or columns. That means the UNIQUE constraint is used to avoid duplicate values but it accepts a single NULL value in that column.

A table can contain any number of UNIQUE constraints. We can apply the UNIQUE constraint on any data type column such as integer, character, money, etc.

Syntax: CREATE TABLE<TABLE NAME>(<COLUMN NAME><DATA TYPE><CONSTRAINTKEY>……)

Let us understand Unique Constraint with an example. In order to understand Unique Constraint, first, create the Customer table by executing the following SQL Script. As you can see, here, we applied the UNIQUE constraint to all three columns. It means none of the columns is going to accept the duplicate value.

CREATE TABLE Customer
(
Id INT UNIQUE,
NAME VARCHAR(30) UNIQUE,
Emailid VARCHAR(100) UNIQUE
)

Once you created the above table, now try to execute the below Insert statements.



When we execute the above statement, it executed as expected. Now, try to execute the below SQL Statement.


When we try to execute the above statement we will get the following error. This is because we are trying to insert duplicate values into the columns.

SQL Server Constraints

Again try to execute the below SQL Statements.


When we execute the above query, the third insert statement will give us the below error

SQL Server Constraints

If we insert a duplicate value into a column that contains UNIQUE constraint, the statements get terminated by displaying an error message but that error message will not contain the column name where the violation got occurred, it only displays the constraint name, the table name, and the value that we want to insert into the unique column as shown in the above error message.

Note: UNIQUE constraint will accept only 1 NULL value.


UNIQUE KEY, PRIMARY KEY, CHECK, and FOREIGN KEY in SQL Server:

UNIQUE KEY, PRIMARY KEY, CHECK, and FOREIGN KEY Constraints are independent objects under the database on which they are created and linked with the column of the table. That means they have their own identity or name. This is the reason why if these four constraints are violated they will never tell the column where the violation occurred. They only display the constraint name, table name, and the value that we want to insert.

Actually, you should define the constraint name while creating the table. If you have not specified the constraint name while creating the table, then the SQL server will give a random name to that constraint which is not user-friendly. So it is always advisable to provide your own constraint name while creating the table for easy identification. The naming convention something like below.

 <columnname>_<constraint type>

Creating Constraint with own name:

Let us understand how to provide our own constraint name with an example. In order to understand this, please execute the below SQL Script which will create the Customer table. If you further notice, here we created two unique constraints by giving our own names such as cid_unique and email_unique.

CREATE TABLE customer
(
Id INT CONSTRAINT cid_unique UNIQUE,
NAME VARCHAR(30),
Emailid VARCHAR(100) CONSTRAINT email_unique UNIQUE
)

In the above create table statement we are explicitly providing the name for the constraints. Once you created the table you can find the constraint in the keys folder as shown below

SQL Server Constraints - Constraint Location

Imposing Constraint in SQL Server:

We can impose constraints on a table in two different ways

  1. Imposing constraints on Column level
  2. Imposing constraints on Table level

In the first case, we need to provide the constraint information inside the column only whereas in the second case we first define all the columns, and then we need to define the constraints on the columns.

Note: We cannot impose NOT NULL constraint in table level. It is possible only for the rest of the four constraints.

Imposing Constraint on Column Level:

As you can see in the following Create Table statement, we have specified the cid_unique and email_unique unique constraints directly at the column level i.e. next to the column name.

CREATE TABLE customer
(
Id INT CONSTRAINT cid_unique UNIQUE,
NAME VARCHAR(30),
Emailid VARCHAR(100) CONSTRAINT email_unique UNIQUE
)
Imposing Constraint on Table Level:

As you can see in the following Create Table statement, first, we created all the columns and then we created the cid_unique and email_unique unique constraints and while creating the constraint we explicitly specified the column name to which the constraint belongs.

CREATE TABLE customer
(
Id INT,
NAME VARCHAR(30),
Emailid VARCHAR(100),
CONSTRAINT cid_unique UNIQUE(Id),
CONSTRAINT email_unique UNIQUE(Emailid)
)

Note: There is no difference in behavior whether the constraint is imposed at the table level or at the column level but if a constraint is imposed at the table level, then we have the advantage of imposing composite constraints. 

What are Composite Constraints in SQL Server?

Whenever a constraint is created based on more than one column then it is called Composite Constraints in SQL Server. Let us understand the composite constraint with an example.

As you can see in the following Create table statement, we have imposed the city_bc_unique unique constraint at the table level and here we specified the City and Branchcode column. That means this constraint is a composite constraint as it is created based on two columns (City and Branchcode).

CREATE TABLE BranchDetails
(
City VARCHAR(50),
Branchcode VARCHAR(10),
Branchlocation VARCHAR (30),
CONSTRAINT city_bc_unique UNIQUE(City, Branchcode)
)

Now insert some data to the BranchDetails table by executing the following insert statements.


When we execute the third statement,  it will give us the following error. This is because the combination of xyz and pqr in the column Branchcode and Branchlocation already exists and is considered as duplicate values.

SQL Server Constraints

Note: The drawback with a NOT NULL constraint is it will allow duplicate values whereas in the case of a UNIQUE constraint it allows null values.

Check Constraint in SQL Server:

The Check Constraint is used to enforce domain integrity. Domain integrity ensures that the values going to store in a column must follow some defined rules such as range, type, and format.

In simple words, we can say that the Domain Integrity constraint enforces the valid entries for a given column value by restricting the type of the value, the format of the data, or the range of possible values. Lets understand this with an example.

CREATE TABLE Employee
(
Emp_id INT NOT NULL CHECK(Emp_id BETWEEN 0 AND 1000),
Emp_name VARCHAR(30) NOT NULL,
Entered_date DATETIME NOT NULL CHECK(Entered_date <= CURRENT_TIMESTAMP),
Dept_no INT CHECK(Dept_no > 0 AND Dept_no < 100)
)

We need to use the Check Constraints in the SQL server to limit the range of possible values of a column.

The check constraints can be created at two different levels

  1. Column-Level Check Constraints: When we create the check constraints at the column level then they are applied only to that column of the table.
  2. Table-level Check Constraints: When we create the check constraints at the table level, then it can be referred from any column within that table.

A table can contain any number of check constraints and will apply to any column data type like integer, character, and decimal, date, etc.

Example: Lets insert some data to understand this concept

When we execute the above query it will give us the below error

SQL Server Constraints


It will give us the below error when we execute the above statement

SQL Server Constraints


When we execute the above query it will give us the below error

SQL Server Constraints


See All

Comments (504 Comments)

Submit Your Comment

See All Posts

Related Posts

Microsoft SQL Server / Blog

What is SQL Server?

The SQL Server is a relational database management system (RDBMS) which is developed by Microsoft. It is also called MS SQL Server. This product is built on the basic function of storing, retrieving data as required by other applications. It can be run either on the same computer or on another across a network.
15-Feb-2022 /26 /504

Microsoft SQL Server / Blog

How to Creating Altering and Deleting Database in SQL Server?

In this article, I am going to discuss Creating Altering and Deleting Database in SQL Server with examples. Please read our previous article where we discussed how to connect to SQL Server Database using a client tool called SQL Server Management Studio. As part of this article, we are going to discuss the following pointers.
15-Feb-2022 /26 /504

Microsoft SQL Server / Blog

How to Creating Altering and Deleting Tables in SQL server?

In this article, I am going to discuss Creating Altering and Deleting Tables in SQL Server with examples. Along the way, we will also discuss the Data Definition Language in detail. Please read our previous article before proceeding to this article where we discussed the Creating Altering and Deleting Database in SQL Server with examples. As part of this article, we are going to discuss the following important points.
15-Feb-2022 /26 /504