SQL Check Constraint

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

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

Source Table 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

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

(1 row(s) affected)

Create SQL Server Check Constraint using Management Studio

Before we start working on this, let me show you the final data inside our table:

Source Table 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 is located. Please select the table to create a SQL Check Constraint (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.

Choose Add New SQL Check Constraint 4

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

Table in Design Mode 5

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

Edit Table Expression 6

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

Expression for the SQL Check Constraint 7

Next, we renamed the SQL Server 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, the check constraint will test the expression against the existing records. Otherwise, it will inspect for new records only. Therefore, let me keep it as Default Yes.
Name 8

Let me save the table design.

Close the Table Designer 9

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

Post Save Notification Error 10

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

Set Existing Data on Creating Option to No \ Yes 11

Now you can see our newly created Check constraint. 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, 'abmx@abd.com', 92500, 'Author')
Insert rows into table 13

It is returning an Error. It is because we are inserting the 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, 'abmx@abd.com', 92500, 'Author')
SQL Check Constraint conflict Error 14

This time we will try with the 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, 'abmx@abd.com', 92500, 'Author')
(1 row(s) affected)

Let us see the total records in our table.

SELECT [CustKey]
      ,[Yearly Income]
  FROM [CustomerRecords]
SQL Check Constraint 16

SQL Check Constraint on an Existing table using Query

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

Select Statement 19

In this SQL example, we show how to add check constraints to 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)
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, 'abmx@abd.com', 92500, 'Author')
Error Msg 547, Insert Statement Conflict Occurred 21

Insert NULLS in SQL Check Constraint

What happens when we insert the NULL values into the Check constraint column? First, let me insert the NULL value into the Age Address Column.

INSERT INTO [dbo].[CustomerRecords]
	  ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession])
     VALUES (6, 'SQL', 'Server',  NULL, 'abmx@abd.com', 2500, 'SQL Author')
(1 row(s) affected)

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

Insert Nulls in SQL Check Constraint 23

Create Check on Multiple Columns

This SQL example creates a check constraint on multiple columns. The 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)

Create SQL Check Constraint on table creation

Here, we show you how to create a check constraint in the SQL server at the time of table creation. Refer 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)
Command(s) completed successfully.

Delete SQL Check Constraint using transact query

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

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

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

SELECT name, create_date   
FROM sys.check_constraints
WHERE OBJECT_NAME(parent_object_id) = N'CustomerRecords';  
Alter Table 25

Once you get the name, you can use the ALTER TABLE Statement to Drop it.

Delete Check using SSMS

Within the object explorer, Expand the Database folder and the CustomerRecords table to find and delete the SQL Check Constraints folder. Right-click on the folder and select the Delete option.

Choose Delete option 17

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

Delete SQL Check Constraint 18
Categories SQL