Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Python Programs
    • Java Programs

SQL Check Constraint

by suresh

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.

SQL Check Constraint 1

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
SQL Check Constraint 2

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

SQL Check Constraint 4

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.

SQL Check Constraint 5

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.

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 check 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.

-- 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')
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.

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')
SQL Check Constraint 14

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')
SQL Check Constraint 15

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 16

SQL Check Constraint on Existing table using Query

Before working with the Check constraint, 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 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
SQL Check Constraint 20

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')
SQL Check Constraint 21

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')
SQL Check Constraint 22

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.

SQL Check Constraint 23

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
SQL Check Constraint 26

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
SQL Check Constraint 24

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
SQL Check Constraint 25

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.

SQL Check Constraint 17

Once you select the Delete option, a new window called Delete Object will open. Click OK to delete the check constraint in SQL Server.

SQL Check Constraint 18

Placed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW
  • C Tutorial
  • C# Tutorial
  • Java Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQL Tutorial
  • SQL Server Tutorial
  • R Tutorial
  • Power BI Tutorial
  • Tableau Tutorial
  • SSIS Tutorial
  • SSRS Tutorial
  • Informatica Tutorial
  • Talend Tutorial
  • C Programs
  • C++ Programs
  • Java Programs
  • Python Programs
  • MDX Tutorial
  • SSAS Tutorial
  • QlikView Tutorial

Copyright © 2021 | Tutorial Gateway· All Rights Reserved by Suresh

Home | About Us | Contact Us | Privacy Policy