SQL Check Constraint

SQL Check Constraint will limit the data inserted into the SQL table columns. For example, if we want to restrict the number of digits in a phone number or limit the customer age between 18 to 60, then we can assign Sql Server Check Constraint to that column.

Let us see how to assign SQL Check Constraint using transact query and SQL Server Management Studio with examples. For this SQL Check Constraint demonstration, we use the Customer Records table.

SQL Check Constraint 1

Let me update the Age for Custkey = 4. Please refer UPDATE Statement to understand the below SQL Server statement.

UPDATE [dbo].[CustomerRecords]
SET [Age] = -150
WHERE [CustKey] = 4
GO
Messages
--------
(1 row(s) affected)

Although the age of any person is between 0 and 100 in most cases or 0 to 150 in rare cases. Our Age column is accepting negative values which are not correct in real-time. To deal with this situation, we have to use the SQL Server Check Constraint.

Create SQL Check Constraint using SSMS

Before we start working with the SQL Check constraint let me show you the final data inside our table:

SQL Check Constraint 3

In this example, we show you how to create the check using the Management Studio.

Within the object explorer, Expand the Database folder in which our table located. Please select the table to create a SQL Check (here it is CustomerRecords). Next, go to the Constraints folder, and right-click on it will open the context menu. Please select New Constraint… option

SQL Check Constraint 4

Once you select New option, the management studio will open the corresponding table in design mode. And it will display a Check pop up window.

SQL Check Constraint 5

To enable this, we have to provide a Boolean expression inside the Expression property. So, let me click on the … button beside the Expression.

SQL Check Constraint 6

As you can see, we are writing a simple expression Age > 0 AND Age < 120. It means Age should be between 0 and 120

SQL Check Constraint 7

Next, we renamed the Check constraint name as CK_CustomerRecords_Age. Please change the Name as per your requirements, and provide a valid description. Apart from these three, there is one more important property:

  • Check Existing Data On Creation or Re-Enabling: This property has Boolean Yes or No options. If you set it as Yes, check constraint will test the expression against the existing records. Otherwise, it will inspect for new records only. Let me keep it as Default Yes.
SQL Check Constraint 8

Let me save the table design

SQL Check Constraint 9

It is throwing an error. Because Customer Records table had one value that is not satisfying the expression (-150 is not between 0 and 120)

SQL Check Constraint 10

Let me change the Check Existing Data On Creation or Re-Enabling property to No. It means, it will not care about existing records, Check constraint will only test the expression for new records. OR you can Delete, or Update the record containing the -150 value.

SQL Check Constraint 11

Now you can see our newly created Check constraint in Sql Server. For this, Go to the object explorer -> Database – > Table Name -> Expand Constraints Folder

SQL Check Constraint 12

Insert Values into SQL Server Check Constraint Column

Let me insert a value into the table using the INSERT Statement.

INSERT INTO [dbo].[CustomerRecords]
          ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession])
   VALUES (5, 'SQL', 'Tutorials',  175, '[email protected]', 92500, 'Author')
SQL Check Constraint 13

It is returning an Error. This is because, we are inserting Age value as 175, and 175 is not between 0 and 120.

Let us try with a negative value. As you can see, it is also throwing the same error.

INSERT INTO [dbo].[CustomerRecords]
          ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession])
   VALUES (5, 'SQL', 'Tutorials',  -17, '[email protected]', 92500, 'Author')
SQL Check Constraint 14

This time we will try with correct value, and you can see our insertion is successful.

INSERT INTO [dbo].[CustomerRecords]
          ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession])
   VALUES (5, 'SQL', 'Tutorials',  17, '[email protected]', 92500, 'Author')
Messages
--------
(1 row(s) affected)

Let us see the total records in our table.

SELECT [CustKey]
      ,[FirstName]
      ,[LastName]
      ,[Age]
      ,[EmailAddress]
      ,[Yearly Income]
      ,[Profession]
  FROM [CustomerRecords]
SQL Check Constraint 16

SQL Check Constraint on Existing table using Query

Before working with this, let me show you the final data inside our table:

SQL Check Constraint 19

In this example, we show how to add SQL Server check constraints on the existing table.

To add this, we are using the Alter Table Statement to alter the table content. Then we used the ADD CONSTRAINT statement to add.

ALTER TABLE[CustomerRecords]
ADD CONSTRAINT CK_CustomerRecords_Age CHECK([Age] > 0 AND [Age] < 120)
 
GO
Messages
--------
Command(s) completed successfully.

Let me insert a negative value

INSERT INTO [dbo].[CustomerRecords]
	  ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession])
     VALUES (6, 'SQL', 'Server',  -25, '[email protected]', 92500, 'Author')
SQL Check Constraint 21

Insert NULLS in SQL Check Constraint

What happens when we insert the NULL values into the SQL Check constraint column?. Let me insert NULL value into the Age Address Column.

INSERT INTO [dbo].[CustomerRecords]
	  ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession])
     VALUES (6, 'SQL', 'Server',  NULL, '[email protected]', 2500, 'SQL Author')
Messages
--------
(1 row(s) affected)

It has inserted the NULL value into the check constraint. Because, expression result for NULL value returns undefined (Neither TRUE, Nor FALSE) so, it allows the record.

SQL Check Constraint 23

Create SQL Check Constraint on Multiple Columns

This example create a SQL check constraint on multiple columns. Below code will restrict the user not is enter Age less than 18, and Yearly income greater than 100000

ALTER TABLE[CustomerRecords]
ADD CONSTRAINT CK_CustomerRecords_AgeAndIncome CHECK([Age] >= 18 AND [YearlyIncome] <= 100000)
 
GO

Create SQL Check Constraint on table creation

Here, we show you how to create a check constraint in SQL server at the time of table creation. IRefer to Create Table article.

CREATE TABLE [dbo].[CustomerRecords2](
	[CustKey] [int] NOT NULL PRIMARY KEY,
	[FirstName] [varchar](50) NOT NULL,
	[LastName] [varchar](50) NULL,
	[Age] [int] NULL,
	[EmailAddress] [nvarchar](50) NULL,
	[Yearly Income] [money] NULL,
	[Profession] [nvarchar](100) NULL,
	CONSTRAINT CK_CustomerRecords_AgeColumn CHECK([Age] > 0 AND [Age] < 120)
)
GO
Messages
-------
Command(s) completed successfully.

Delete Check Constraint using transact Query

If you know the name that you want to delete, write the DROP Constraint statement along with the ALTER TABLE Statement transact sql query.

ALTER TABLE [dbo].[CustomerRecords]   
DROP CONSTRAINT CK_CustomerRecords_Age;  
GO
Messages
-------
Command(s) completed successfully.

If you don’t know the name, use the following SELECT Statement to get the Constraint name.

SELECT name, create_date   
FROM sys.check_constraints
WHERE OBJECT_NAME(parent_object_id) = N'CustomerRecords';  
GO
SQL Check Constraint 25

Once you got the name, you can use the ALTER TABLE Statement to Drop the Check constraint.

Delete Check Constraint using SSMS

Within the object explorer, Expand the Database folder, and expand the CustomerRecords table to find the constraints folder. Right-click on the folder, and select the Delete option.

SQL Check Constraint 17

Once you select the Delete option, a new window called Delete Object will open. Click OK to delete it.

SQL Check Constraint 18