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 Check Constraint in SQL Server using T-SQL Query and SQL Server Management Studio with examples. For this SQL Check Constraint demonstration, we use the Customer Records table.
Let me update the Age for Custkey = 4. Please refer UPDATE Statement to understand the below SQL Server statement.
USE [SQL Tutorial] GO UPDATE [dbo].[CustomerRecords] SET [Age] = -150 WHERE [CustKey] = 4 GO
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:
In this example, we show you how to create a Check Constraint in SQL Server using the SQL Server Management Studio.
Within the object explorer, Expand the Database folder in which our table located. Please select the table to create a 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
Once you select New Constraint… option, the SQL management studio will open the corresponding table in design mode. And it will display a Check Constraint pop up window.
To enable Check constraint, we have to provide a Boolean expression inside the Expression property. So, let me click on the … button beside the Expression.
As you can see, we are writing a simple expression Age > 0 AND Age < 120. It means Age should be between 0 and 120
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 check for new records only. Let me keep it as Default Yes.
Let me save the table design
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)
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.
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
Insert Values into SQL Server Check Constraint Column
Let me insert a value into the table using the INSERT Statement.
-- Sql Server Check Constraint example USE [SQL Tutorial] GO INSERT INTO [dbo].[CustomerRecords] ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession]) VALUES (5, 'SQL', 'Tutorials', 175, '[email protected]', 92500, 'Author')
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.
USE [SQL Tutorial] GO INSERT INTO [dbo].[CustomerRecords] ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession]) VALUES (5, 'SQL', 'Tutorials', -17, '[email protected]', 92500, 'Author')
This time we will try with correct value, and you can see our insertion is successful.
USE [SQL Tutorial] GO INSERT INTO [dbo].[CustomerRecords] ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession]) VALUES (5, 'SQL', 'Tutorials', 17, '[email protected]', 92500, 'Author')
Let us see the total records in our table.
USE [SQL Tutorial] GO SELECT [CustKey] ,[FirstName] ,[LastName] ,[Age] ,[EmailAddress] ,[Yearly Income] ,[Profession] FROM [CustomerRecords]
SQL Check Constraint on Existing table using Query
Before working with the Check constraint, let me show you the final data inside our table:
In this example, we show how to add SQL Server check constraints on the existing table.
To add the check constraint, we are using the Alter Table Statement to alter the table content. Then we used the ADD CONSTRAINT statement to add the check constraint in SQL.
-- Creating SQL Server CHECK Constraint USE [SQL Tutorial] GO ALTER TABLE[CustomerRecords] ADD CONSTRAINT CK_CustomerRecords_Age CHECK([Age] > 0 AND [Age] < 120) GO
Let me insert a negative value
USE [SQL Tutorial] GO INSERT INTO [dbo].[CustomerRecords] ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession]) VALUES (6, 'SQL', 'Server', -25, '[email protected]', 92500, 'Author')
Insert NULLS in 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.
USE [SQL Tutorial] GO INSERT INTO [dbo].[CustomerRecords] ([CustKey], [FirstName], [LastName], [Age], [EmailAddress], [Yearly Income], [Profession]) VALUES (6, 'SQL', 'Server', NULL, '[email protected]', 2500, 'SQL Author')
It has inserted the NULL value into the check constraint. Because, expression result for NULL value returns undefined (Neither TRUE, Nor FALSE) so, Check constraint allows the record.
Create SQL Check Constraint on Multiple Columns
This example shows how to 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
-- Creating SQL Server CHECK Constraint USE [SQL Tutorial] GO ALTER TABLE[CustomerRecords] ADD CONSTRAINT CK_CustomerRecords_AgeAndIncome CHECK([Age] >= 18 AND [YearlyIncome] <= 100000) GO
Create 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.
USE [SQL Tutorial] GO 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
Delete SQL Check Constraint using Query
If you know the SQL Check constraint name that you want to delete, use the DROP Constraint statement along with the ALTER TABLE Statement
-- Delete SQL Server CHECK Constraint USE [SQL Tutorial] GO ALTER TABLE [dbo].[CustomerRecords] DROP CONSTRAINT CK_CustomerRecords_Age; GO
If you don’t know the check constraint name, use the following SELECT Statement to get the Constraint name.
-- Deleting SQL Server CHECK Constraint USE [SQL Tutorial] GO -- To find the CHECK Constraint Name SELECT name, create_date FROM sys.check_constraints WHERE OBJECT_NAME(parent_object_id) = N'CustomerRecords'; GO
Once you got the Check constraint 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 Constraints folder, and select the Delete option.
Once you select the Delete option, a new window called Delete Object will open. Click OK to delete the check constraint in SQL Server.