MySQL
ORACLE
POSTGRESQL
SQL
SQL SERVER

SQL CHECK Constraint: Definitive Guide With Examples

intro

Let’s learn everything you need to know about the SQL CHECK constraint to become a master of database data integrity.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

In database management, ensuring data integrity is paramount. That is because accurate and consistent information maintains data quality and supports reliable decision-making. What is one of the most powerful tools to ensure data integrity in a database? SQL CHECK constraints! These enforce rules on column values, preventing the creation of records with invalid data.

In this guide, you will understand what CHECK SQL constraints are, how they work, and how to define them in both plain SQL and in a visual database client.

Let's dive in!

What Is a CHECK Constraint in SQL?

In SQL, a CHECK constraint is a rule applied to a column or a set of columns in a table to enforce data integrity. It ensures that all values in one or more columns meet some specific conditions. If a SQL CHECK constraint is in place in a table and an INSERT or UPDATE query violates query conditions, the whole operation is rejected.

Each database provides its own implementation of the CHECK SQL constraint. See the official documentation pages for more details:

CHECK SQL Syntax: First Examples

The CHECK SQL syntax is:

Copy
        
1 [CONSTRAINT [constraint_name]] CHECK (check_expression)

Where:

  • constraint_name is the name given to the CHECK constraint.
  • check_expression is an SQL expression involving the columns in the table with the rules to apply to their values.

In general, the constraint is applied on INSERT and UPDATE statements but not on DELETE statements. Keep in mind that a single table can have several CHECK constraints.

A CHECK constraint can be:

1. A column constraint It refers to only one column. In an ALTER TABLE query, it appears within a column definition.

Example:

Copy
        
1 CREATE TABLE t1( 2 c1 INT CHECK (c1 > 10), 3 -- other columns ... 4 );

2. A table constraint A table constraint refers to one or more columns. In an ALTER TABLE query, it is usually specified at the end, after the column definition.

Example:

Copy
        
1 CREATE TABLE t1 ( 2 c1 INT, 3 -- other columns ... 4 CHECK (c1 > 10) 5 );

The CONSTRAINT [constraint_name] part of the syntax is optional and required to define named constraints as below:

Copy
        
1 CREATE TABLE t1 ( 2 c1 INT, 3 -- other columns ... 4 CONSTRAINT c1_positive CHECK (c1 > 10) 5 );

Otherwise, the database engine will give the CHECK constraint an automatic name, such as t1_c1_check.

Typically, SQL CHECK constraints are enforced immediately after they are defined. This means that if one or more rows do not match the rules specified in check_expression, the constraint creation will fail. In MySQL, you can avoid this automatic enforcement behavior by adding the NOT ENFORCED string at the end of the CHECK constraint definition.

Note: Avoid data type conversion in constraint definitions, as implicit or explicit data type conversion may cause certain operations to fail.

How to Deal With SQL CHECK Constraints

Now that you know the CHECK SQL syntax, you are ready to learn how to define and drop such constraints.

You will see how to perform each operation with a plain SQL query and how to do everything in DbVisualizer. If you are unfamiliar with DbVisualizer, it is a top-rated visual SQL client supporting dozens of databases. This advanced tool allows you to manage CHECK constraints in just a few clicks.

Download it for free, install it, launch it, and set up a database connection to get started.

The CHECK constraint used in the examples below ensures that salary is greater than or equal to 0 and age is greater than or equal to 18. The sample queries will be written in MySQL, but you can easily adapt them to any other SQL dialect.

Add a CHECK Constraint on CREATE TABLE

Assume you want to create a MySQL employee table while checking for salary and age validity using the aforementioned SQL CHECK constraint. This is how you can do it:

Copy
        
1 CREATE TABLE employee ( 2 id INT AUTO_INCREMENT PRIMARY KEY, 3 fullname VARCHAR(100) NOT NULL, 4 address VARCHAR(255), 5 age INT, 6 salary DECIMAL(10, 2), 7 CONSTRAINT valid_employee CHECK (salary >= 0 AND age >= 18) 8 );

The example below will illustrate how you can do it in DbVisualizer. Connect to your MySQL server, reach your database (company, in this case) in the “Connections” section, right-click on it, and select the “Create Table…” option:

Selecting the Create Table option in DbVisualizer
Selecting the Create Table option in DbVisualizer

In the dialog that opens, give the table a name, define the columns, and reach the “Check Constraints” tab:

Reaching the Check Constraints tab
Reaching the Check Constraints tab

Here, click on the “+” button to specify the desired CHECK constraint:

Defining a CHECK constraint in DbVisualizer
Defining a CHECK constraint in DbVisualizer

Finally, press the “Execute” button to create the table. The result will be the same MySQL query seen before.

Find out more in the DbVisualizer documentation.

If you now try to add or update a record in the employee table with some values that do not respect the specified rule, the query will fail with this error:

Copy
        
1 [Code: 3819, SQL State: HY000] Check constraint 'valid_employee' is violated.

Add a CHECK Constraint with ALTER TABLE ADD CONSTRAINT

Now, suppose you want to add the CHECK constraint to an existing table. You can do this if you make use of the ALTER TABLE ... ADD CONSTRAINT statement:

Copy
        
1 ALTER TABLE employee 2 ADD CONSTRAINT valid_employee CHECK (salary >= 0 AND age >= 18);

In DbVisualizer, right-click on the table you want to add the constraint to, and select the “Alter Table…” option:

Selecting the Alter Table option in DbVisualizer
Selecting the Alter Table option in DbVisualizer

In the “Alter Table” modal, reach the “Check Constraint” tab, and follow the same procedure as before:

Adding a CHECK constraint in DbVisualizer
Adding a CHECK constraint in DbVisualizer

As you can see, the resulting SQL query is the same as the one presented above.

DROP a CHECK Constraint

You can remove a CHECK constraint by specifying its name in the following DROP CONSTRAINT query:

Copy
        
1 ALTER TABLE employee DROP CONSTRAINT valid_employee;

In DbVisualizer, reach the “Check Constraint” tab, and simply click the “-” button.

Rename a CHECK Constraint

In most databases, it is not possible to rename a constraint. Instead, you must delete it and recreate it with a different name.

PostgreSQL and Oracle allow that via the RENAME CONSTRAINT query:

Copy
        
1 ALTER TABLE company RENAME CONSTRAINT valid_employee TO chk_employee

In DbVisualizer, you can change the name of a constraint by double-clicking on it in the “Check Constraint” tab.

Popular Use Cases

These are some common use cases for CHECK:

  • The enforcement of business rules: CHECK can be used to implement business logic directly in the database, such as making sure that a discount percentage is within acceptable limits.
  • Consistency: CHECK can be used to maintain consistency across related columns, such as ensuring start dates are before end dates in a schedule.
  • Range restrictions: Limiting values to a specified range, like ensuring quantities are positive in an inventory system.
  • Conditional data entry: Enforcing conditions on data entry, such as ensuring a product is marked with the label "in stock" only if the quantity is greater than zero.
  • Data format validation: Validating the format of data entries, such as ensuring email addresses contain an "@" symbol.
  • Boolean logic enforcement: Ensuring that boolean columns adhere to true/false conditions, such as ensuring an is_active flag is only set when certain conditions are met.

Conclusion

In this article, you learned what the SQL CHECK constraint is, which databases support it, and how it helps define data integrity rules. Thanks to the use cases explored here, you now understand when to apply it in real-world applications.

As demonstrated here, defining constraints is much easier with DbVisualizer. Thanks to its intuitive UI, this database client allows you to create, update, and delete constraints with just a few clicks. These are only some of the features this powerful tool supports: DbVisualizer supports many other features such as query optimization and ERD-like schema generation. Try DbVisualizer for free today!

FAQ

How to update a CHECK constraint?

No, it is not possible to update an existing CHECK constraint in SQL. To do so, you need to drop the constraint and then add a new one with the desired condition as follows:

  • Drop the existing constraint:
Copy
        
1 ALTER TABLE table_name DROP CONSTRAINT constraint_name;
  • Add the new CHECK SQL constraint:
Copy
        
1 ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK (new_condition);

How to use SQL CHECK for duplicates?

Using the SQL CHECK for duplicates is uncommon. Instead, you should create a UNIQUE constraint on the columns where duplicates should not occur. Alternatively, you can make use of the sort statement on Unix architectures with the -u (unique) flag to quickly delete duplicates from any file.

How to use SQL CHECK for NULL values?

You use CHECK constraints to check for IS NOT NULL values in a column. At the same time, this is usually done by marking that column as not nullable at definition time.

What role does CHECK play in PostgreSQL data integrity?

In PostgreSQL, CHECK constraints play a crucial role in ensuring data integrity by enforcing specific conditions on column values. These constraints enable you to validate data entered into a table, ensuring it meets predefined criteria. For more guidance, follow our article on PostgreSQL data integrity.

What happens in case of a CHECK constraint violation?

In case of a CHECK constraint violation in SQL, the database management system rejects the operation with an error. For instance, if an INSERT or UPDATE statement attempts to add or modify a row with data that does not meet the condition of the CHECK constraint, the operation fails. This ensures data integrity by preventing invalid or inconsistent data from being inserted or updated in the database.

Dbvis download link img
About the author
Antonello Zanini

Antonello is a software engineer, and often refers to himself as a technology bishop. His mission is to spread knowledge through writing.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

Automating SQL Queries with SQL CLI and SQL Job Scheduling

author Bonnie tags AUTOMATION SQL 6 min 2025-01-14
title

A Guide to SQL Server Indexes on Partitioned Tables

author Antonello Zanini tags SQL SERVER 7 min 2025-01-13
title

How to Display All Duplicate Records in a MySQL Table

author Antonello Zanini tags MySQL 6 min 2025-01-08
title

Understanding the SQL UNIQUE Constraint

author Leslie S. Gyamfi tags DbVisualizer SQL 6 min 2025-01-07
title

How to Drop an Index By Partition Number in SQL Server

author Antonello Zanini tags SQL SERVER 7 min 2025-01-06
title

Exploring Cursors and Temporary Tables in SQL

author Ochuko Onojakpor tags Cursors SQL 10 min 2024-12-30
title

The Most Interesting Functions in MySQL – A Guide

author Lukas Vileikis tags MySQL 5 min 2024-12-27
title

MySQL Primary Key: What It Is, How It Works, and When to Use It

author Lukas Vileikis tags Data Visualization Tools DbVisualizer MySQL 8 min 2024-12-23
title

What Is a PostgreSQL Primary Key?

author Leslie S. Gyamfi tags POSTGRESQL 8 min 2024-12-18
title

A Guide To the SQL DECLARE Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SERVER 7 min 2024-12-12

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.