Lesson 4 of the SQL Optimization Course: Column - level CHECK Constraint

Table of Contents
Lesson 4 of the SQL Optimization Course: Column - level CHECK Constraint
Introduction
For relational databases, the design of tables and SQL is written are particularly crucial. It wouldn’t be an exaggeration to say that they account for 90% of performance. So this time, specifically targeting these two major knowledge areas, we’ll conduct a detailed analysis for you, peeling back the layers.
This Series uses plain and understandable language and selects a large number of examples to elaborate on the subtleties for you.
🧑💻 Target audience:
- DBA
- Database developers
- Students
We will use MySQL as the demonstration database.
Lesson 4 Column - level CHECK Constraint
The CHECK constraint is used to filter one or more columns according to pre - set rules. If the condition is true, the filtering is successful; if false, the filtering fails, and a failure code is returned to the client.
Why is this discussed separately? It’s common to encounter non - standard SQL. In many cases, since the code - side doesn’t perform filtering, the filtering has to be done at the database level.
1. Common Filtering Methods
Suppose we have a table f1
with a column r1
whose value should be a multiple of 3; otherwise, the write operation is rejected. Also, assume that the input for r1
is not standardized and can only be filtered by the database. What can we do? There are mainly the following methods:
1.1 Write a Pre - insert Trigger
Example 1
|
|
- **Execution and Results**
- **Abnormal Insertion**:
|
|
Normal Insertion
|
|
The above example simply addresses the scenario of single - column filtering. Complex multi - column filtering will be discussed later.
1.2 Write a Stored Procedure to Encapsulate SQL
Handle input constraints within the stored procedure. This is similar to handling input constraint logic on the application side, but the same processing logic is placed at the database side. And in the future, all data entry can only rely on the single - entry point of the stored procedure.
1.3 Accept All Inputs and Process Non - standard Data Regularly
This will lead to a large amount of entered data, including many useless non - standard data. Usually, non - standard data is processed regularly during non - peak business hours. Examples for these two methods are not provided as they are similar to the first one.
2. CHECK Constraints
Now, let’s talk about the CHECK constraint that filters at the column level and is defined before the table definition (MySQL version >= 8.0.16).
|
|
The relevant restrictions of the CHECK constraint are as follows:
- The
constraint
name must be unique in each database. That is, there are no two identicalconstraints
in a single database. If not defined, the system will automatically generate a unique constraint name. - The CHECK constraint takes effect for statements like
insert
,update
,replace
,load data
,load xml
; it fails for the correspondingignore
statements. - Not every function can be used. For example, functions with uncertain results such as
NOW()
,CONNECTION_ID()
,CURRENT_USER()
. - It is not applicable to stored procedures and stored functions.
- System variables are not applicable.
- Sub - queries are not applicable.
- Foreign key actions (such as
ON UPDATE
,ON DELETE
) are not applicable. - By default,
enforced
is enabled. Ifnot enforced
is added separately, the CHECK constraint fails.
Example 2
Based on the above, let’s look at the actual examples of the two tables. The CHECK constraint only takes effect for table f1
.
|
|
Next, let’s look at a more detailed example of the CHECK constraint.
Example 3
|
|
Regarding the above example:
- Constraints
tb_f1_r1_nonzero
,tb_f1_r1r2_chk1
,tb_f1_r1r3_chk
are not tied to a specific column and are globally valid. In other words, they are table - based CHECK constraints. - Constraint
tb_f1_r1_chk1
includes constrainttb_f1_r1_nonezero
, sotb_f1_r1_nonezero
can never detect an exception. After checking, this constraint can be removed.
The definition after removing the redundant constraint:
|
|
Let’s test this table. We can see that the constraints for each column are in an “AND” relationship. If any column’s constraint is not met, the write operation fails.
|
|
Next, we can transform the trigger we started with. By adding the relevant conditions, we can achieve the same column - level CHECK constraint.
|
|
Test the Effect
|
|
Summary
This article introduced the usage and some examples related to the database CHECK constraint. Personally, I suggest that if the CHECK constraint can be separated from the database side and implemented on the application side, it would be better. The simpler the database side, the better the performance. However, there are exceptions. If it is difficult to implement on the application side due to historical reasons or other factors, it has to be implemented on the database side.
Recommended reading
The SQL Optimization Course
- Lesson 1 of the SQL Optimization Course: The Art of MySQL Data Types:Part 1
- Lesson 2 of the SQL Optimization Course: The Art of MySQL Data Types:Part 2
- Lesson 3 of the SQL Optimization Course: Column Not Null & Auto Increment
- Lesson 4 of the SQL Optimization Course: Column - level CHECK Constraint
- Lesson 5 of the SQL Optimization Course: Can foreign keys be used?
The SQL optimization knowledge
👋 See you in the next lesson.
What is SQLFlash?
SQLFlash is your AI-powered SQL Optimization Partner.
Based on AI models, we accurately identify SQL performance bottlenecks and optimize query performance, freeing you from the cumbersome SQL tuning process so you can fully focus on developing and implementing business logic.