I have a .csv file which look like this:
and that can be downloaded from here.
I create my DB and my table with the following code:
CREATE DATABASE test_schema;
CREATE TABLE test_schema.teams (
teamkey SMALLINT NOT NULL AUTO_INCREMENT,
teamid CHAR(3) NOT NULL,
yearid YEAR(4) NOT NULL,
leagueid CHAR(2) NOT NULL,
teamrank TINYINT(2) NOT NULL,
PRIMARY KEY (teamkey),
UNIQUE KEY teamkey_UNIQUE (teamkey),
KEY teamid_yearid_leagueid_UNIQUE (teamid, yearid, leagueid),
CONSTRAINT check_teamrank CHECK (((teamrank >= 0) and (teamrank <= 12))),
CONSTRAINT check_year CHECK (((yearid >= 1871) and (yearid <=2155))))
ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Now, when I try to import using:
LOAD DATA LOCAL INFILE "path_to_file_in_my_computer/Teams.csv"
INTO TABLE test_schema.teams
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(@teamID, @yearID, @lgID, @Rank);
I get 2895 warnings which are all the same:
Warning (Code 3819): Check constraint 'check_year' is violated.
This warning makes no sense since yearid
goes from 1871 to 2018 as can be corroborated if you look at the structure of the Teams.csv file. So any advice or suggestion on how to handle this error will be much appreciated. I’m working on MySQL Workbench 8.0.
PS: I posted a similar question (deleted) today morning but it needed more details that are provided here.
Hello everyone, in this little post we will review a new feature in MySQL 8.
What is “CHECK Constraint”?
This is a new feature to specify a condition to check the value before INSERT or UPDATE into a row. The constraint could return an error if the result of a search condition is FALSE for any row of the table (but not if the result is UNKNOWN or TRUE).
This feature starts working on MySQL 8.0.16, and in previous versions, we could create it, but it doesn’t work, meaning the syntax is supported but it is not working,
There are some rules to keep in mind…
– AUTO_INCREMENT columns are not permitted
– Refer to another column in another table is not permitted
– Stored functions and user-defined functions are not permitted (you can not call a function or any user-defined functions)
– Stored procedure and function parameters are not permitted (you cannot call a procedure and function parameters)
– Subqueries are not permitted
– Columns used in foreign key for the next actions (ON UPDATE, ON DELETE) are not permitted
– This CHECK is evaluated for the next statements INSERT, UPDATE, REPLACE, LOAD DATA, and LOAD XML. Also, CHECK constraint is evaluated for INSERT IGNORE, UPDATE IGNORE, LOAD DATA … IGNORE, and LOAD XML … IGNORE. For those statements, a warning occurs if a constraint evaluates to FALSE. The insert or update is skipped.
Let’s See Some Examples
I created the next table to test this functionality. This is super easy as you can see in examples:
CREATE TABLE users ( id int not null auto_increment, firstname varchar(50) not null, lastname varchar(50) not null, age TINYINT unsigned not null CONSTRAINT `check_1` CHECK (age > 15), gender ENUM(‘M’, ‘F’) not null, primary key (id) ) engine = innodb; |
In this simple test, we can write or update rows only if the “age” column value is more than 15.
Let’s see an example trying to INSERT rows with the “age” column less than 15:
mysql> INSERT INTO users SET firstname = ‘Name1’, lastname = ‘LastName1’, age = 10, gender = ‘M’; ERROR 3819 (HY000): Check constraint ‘check_1’ is violated. |
To DROP, use the next example:
ALTER TABLE users DROP CHECK check_1; |
Let’s see another example adding more logic into it. I altered the table with the next CHECKs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
ALTER TABLE users ADD CONSTRAINT gender_male CHECK ( CASE WHEN gender = ‘M’ THEN CASE WHEN age >= 21 THEN 1 ELSE 0 END ELSE 1 END = 1 ); ALTER TABLE users ADD CONSTRAINT gender_female CHECK ( CASE WHEN gender = ‘F’ THEN CASE WHEN age >= 18 THEN 1 ELSE 0 END ELSE 1 END = 1 ); |
We added more logic, and now it depends on the “gender” and “age” columns. A CHECK constraint is satisfied if, and only if, the specified condition evaluates to TRUE or UNKNOWN(for NULL column value) for the row of the table. The constraint is violated otherwise.
Let see an example from the previous logic.
mysql> INSERT INTO users SET firstname = ‘Name2’, lastname = ‘LastName2’, age = 10, gender = ‘F’; ERROR 3819 (HY000): Check constraint ‘gender_female’ is violated. mysql> INSERT INTO users SET firstname = ‘Name3’, lastname = ‘LastName3’, age = 10, gender = ‘M’; ERROR 3819 (HY000): Check constraint ‘gender_male’ is violated. |
As you can see in the ERROR message, MySQL is showing the CHECK constraint name. This is good to use from the application source code to debug the error and to know from which CHECK is failing.
Finally, this is the table structure:
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(50) NOT NULL, `lastname` varchar(50) NOT NULL, `age` tinyint(3) unsigned NOT NULL, `gender` enum(‘M’,‘F’) NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `gender_female` CHECK (((case when (`gender` = ‘F’) then (case when (`age` > 18) then 1 else 0 end) else 1 end) = 1)), CONSTRAINT `gender_male` CHECK (((case when (`gender` = ‘M’) then (case when (`age` > 21) then 1 else 0 end) else 1 end) = 1)) ) ENGINE=InnoDB AUTO_INCREMENT=4; |
We can add more logic in the table using this feature, but from my previous experience as a programmer, I don’t recommend adding logic in the tables because it is difficult to find or debug errors unless you do not have access to the application code.
MySQL CHECK is an integrity constraint. The CHECK constraint is specifically used for restricting the input values that can be allowed to one or more columns in a table.
The CHECK constraint functionality can be utilized after version 8.0.16 and above. Before MySQL 8.0.16 version, the syntax of the CHECK constraint was acceptable although the functionality was ignored. This means, when using CHECK, syntactically it would be accepted by MySQL but the constraint is overlooked while the statement was executed or is simply ignored.
The latest versions of MySQL allow us to use the CHECK constraint syntactically as well as while executing the statement, which means if in case, the value doesn’t meet the CHECK constraint’s requirement then an error is thrown.
CHECK constraint using CREATE TABLE statement
We can put a CHECK constraint on a single column or multiple columns when we are creating a table.
Below is the syntax for the CHECK constraint while creating a table:
CREATE TABLE tablename (
Value1 datatype,
Value2 datatype,
Value3 datatype CHECK check_constraint,
CONSTRAINT check_name CHECK (constraint)
);
Code language: SQL (Structured Query Language) (sql)
For better understanding let’s take an example. We’ll create a table as Employee and will have four attributes, such as name, gender, age, and email. Out of these four values, we are going to put CHECK constraint on gender, specifically male(M) or female(F), or transgender(T).
CREATE TABLE employee(
Name varchar(50),
Age int,
Email varchar(50),
Gender char(1) CHECK (Gender in(‘M’,’F’,’T’))
);
Code language: SQL (Structured Query Language) (sql)
CHECK constraint using ALTER table statement
In cases where the table already exists, and we want to put a constraint over a column then it can be possible by putting a constraint on a column with ALTER Table. In our case, we’ll use the CHECK constraint.
Below is the syntax for creating a CHECK constraint using ALTER table:
ALTER TABLE tablename
ADD constraint_name CHECK (check_constraint);
Code language: SQL (Structured Query Language) (sql)
Let’s understand it with an example, we’ll take the employee table which we just created, having the name, age, email, and gender of the employees in which gender already has a check constraint. We need to restrict the age of our employees from 18 to 65. Let’s see how to write a statement for the same.
ALERT TABLE employee
ADD chk_age CHECK (Age >= 18 AND Age <=65);
Code language: SQL (Structured Query Language) (sql)
Insert data into the table and Check the constraint error
As we have created all the necessary CHECK constraints on the Employee table, now whenever we’ll insert data into the table then the constraints will also be checked before the data is inserted into the table by SQL.
For example, if we write the below statement for the employee table then MySQL will throw an error. As we have only allowed three input values to the Gender column which are F, M, and T for Female, Male, and Transgender respectively. But in the below example, even though the gender is technically correct still SQL will throw an error because we have allowed ‘F’ for female and no other value.
INSERT INTO employee
VALUES ('Anamika' , 34, 'ana@mail.co' , 'Female');
Code language: SQL (Structured Query Language) (sql)
The error below is the error that you’ll see whenever you’ll violate the constraint which is set for a particular column in a table. The best thing to do to resolve this error is to insert only those values which are within the range of the constraint which is set for the said column in that table.
ERROR 3819 (HY000): Check constraint ‘e_chk_1’ is violated.
View existing constraints on a particular table
If you want to check if a constraint or any constraint exists within the table then you can use the following command. This command will show a tabular output of all the constraint-related data for the table name you’ve passed in the statement, in our case we’ll use the employee table.
SELECT *
FROM information_schema.table_constraints
WHERE table_schema = schema()
AND table_name = 'employee';
Code language: SQL (Structured Query Language) (sql)
Remove/Drop CHECK constraint
To drop a check constraint from a particular column in a table we use ALTER table statement.
Let’s see an example to understand how it works. We’ll take the employee table which we are using in this tutorial, we currently have two CHECK constraints on the table. The first is the constraint is for the gender column and the second is for the age column. In the below example, we’ll drop the CHECK constraint on the age column.
ALTER TABLE employee
DROP constraint chk_age;
Code language: SQL (Structured Query Language) (sql)
Useful Resources:
https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
Introduction
Starting from MySQL 8.0.16 database server and later versions, a CHECK
constraint is a feature that allows you to specify a condition that validates data during an INSERT
or UPDATE
command. If the constraint is violated when an SQL statement is issued against a table, MySQL raises a general error and aborts the operation altogether. You can use the MySQL CHECK
constraints to enforce business logic at the backend of your application to achieve data integrity. Also, by defining specific data restrictions in the database server, you can be sure that all data administrators in a multi-user environment adhere to the set business rules when making modifications directly in the database without going through a user interface.
For instance, in your organization, you can place a policy that requires all employees to come from the state of CALIFORNIA
. To avoid this rule from being violated in the system, you can code a validation logic in your database. Any database administrator registering employees from the non-allowlisted states should get an error. To put this in a better perspective, you’ll create a sample_company
database and an employees
table in this guide. You’ll then put a CHECK
constraint to limit the value range that can be placed in the state
column for new staff members joining your hypothetical company.
Prerequisites
To follow along with this tutorial, make sure you have the following:
-
An Vultr Ubuntu 20.04 server.
-
A sudo user.
-
A LAMP Stack. You can also follow this tutorial on a Vultr One-Click LAMP server.
Create a sample_company
Database
Connect to your server and log in to MySQL as root.
$ sudo mysql -u root -p
Enter the root password of your MySQL server and press ENTER to proceed. Then, issue the command below to create a sample_company
database`.
mysql> CREATE DATABASE sample_company;
Switch to the sample_company
database.
mysql> USE sample_company;
Create an employees
Table
You’ll create an employees
table. This table acts as an employee register, and new staff members’ details must be inserted here. The employee_id
will be a unique key to identify each employee. Then, the first_name
and last_name
fields will record the full names of the employees. Finally, you’ll use the state
column to record the employees’ localities.
Run the command below to create the employees
table.
mysql> CREATE TABLE employees (
employee_id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
state VARCHAR(50)
) ENGINE = InnoDB;
Before entering any records into the table, you’ll set a validation rule in the next step.
Set a Check Constraint in the employees
Table
With the employees
table in place, you’re going to set a CHECK
constraint that only allows staff members from the CALIFORNIA
state.
Run the command below to add the constraint.
mysql> ALTER TABLE employees
ADD CHECK (state = 'CALIFORNIA');
Make sure you get the output below to confirm the table has been updated with a new constraint.
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
Test the CHECK
Constraint
Create a valid record in the employees
table. For this entry, don’t violate the state
column’s CHECK
constraint.
mysql> INSERT INTO employees
(
first_name,
last_name,
state
)
VALUES
(
'JOHN',
'DOE',
'CALIFORNIA'
);
Your record should be inserted into the employees
table without any problems.
Query OK, 1 row affected (0.00 sec)
Query the employees
table to confirm if the record was inserted into the table.
mysql> SELECT
employee_id,
first_name,
last_name,
state
FROM employees;
The output below confirms that the record is in place.
+-------------+------------+-----------+------------+
| employee_id | first_name | last_name | state |
+-------------+------------+-----------+------------+
| 1 | JOHN | DOE | CALIFORNIA |
+-------------+------------+-----------+------------+
1 row in set (0.00 sec)
Next, attempt to insert a new employee from the FLORIDA
state and see if the CHECK
constraint for the state
column will be violated.
Run the INSERT
command below.
mysql> INSERT INTO employees
(
first_name,
last_name,
state
)
VALUES
(
'MARY',
'SMITH',
'FLORIDA'
);
The command above should fail, and you should receive a standard error message displaying that the constraint has been violated.
ERROR 3819 (HY000): Check constraint 'employees_chk_1' is violated.
Map Multiple Constraints
For this demonstration, you may use the MySQL IN
clause to create an allowlist of multiple states that you want to be accepted in the employees
table.
To do this, you’ll need to delete the first CHECK
constraint and create a new one. Confirm the name of the constraint by running the SELECT
command below against the INFORMATION_SCHEMA
table.
mysql> SELECT
CONSTRAINT_NAME,
TABLE_SCHEMA,
TABLE_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'employees'
AND CONSTRAINT_SCHEMA = 'sample_company'
AND CONSTRAINT_TYPE = 'CHECK';
Check the name of the constraint as displayed in the CONSTRAINT_NAME
column as shown below.
+-----------------+----------------+------------+
| CONSTRAINT_NAME | TABLE_SCHEMA | TABLE_NAME |
+-----------------+----------------+------------+
| employees_chk_1 | sample_company | employees |
+-----------------+----------------+------------+
1 row in set (0.01 sec)
Then, DROP
the constraint. In this case, delete the employees_chk_1
.
mysql> ALTER TABLE employees
DROP CHECK employees_chk_1;
The output below confirms the deletion of the employees_chk_1
constraint.
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
Create a new constraint with the new rules.
mysql> ALTER TABLE employees
ADD CHECK (state IN ('CALIFORNIA', 'COLORADO', 'ARIZONA'));
Ensure you get the output as shown below.
Query OK, 1 row affected (0.23 sec)
Records: 1 Duplicates: 0 Warnings: 0
Next, try to insert new records from both the COLORADO
and ARIZONA
state.
mysql> INSERT INTO employees
(
first_name,
last_name,
state
)
VALUES
(
'JANE',
'MARK',
'COLORADO'
);
mysql> INSERT INTO employees
(
first_name,
last_name,
state
)
VALUES
(
'PETER',
'SMITH',
'ARIZONA'
);
You should get a success message from both INSERT
statements above.
Query OK, 1 row affected (0.00 sec)
Confirm the data by running a SELECT
statement against the employees
table.
mysql> SELECT
employee_id,
first_name,
last_name,
state
FROM employees;
You should now see a list of 3
employees as shown below.
+-------------+------------+-----------+------------+
| employee_id | first_name | last_name | state |
+-------------+------------+-----------+------------+
| 1 | JOHN | DOE | CALIFORNIA |
| 2 | JANE | MARK | COLORADO |
| 3 | PETER | SMITH | ARIZONA |
+-------------+------------+-----------+------------+
3 rows in set (0.00 sec)
Again, try to violate the CHECK
constraint with an employee from a non-allowlisted state such as HAWAII
) and see if an error will be thrown.
mysql> INSERT INTO employees
(
first_name,
last_name,
state
)
VALUES
(
'FRANK',
'JACOB',
'HAWAII'
);
You should get an error as shown below because FRANK JACOB
does not come from CALIFORNIA
, COLORADO
or ARIZONA
.
ERROR 3819 (HY000): Check constraint 'employees_chk_1' is violated.
This confirms that your CHECK
constraint has indeed mapped multiple allowlist values and is working as expected.
Conclusion
In this tutorial, you’ve used MySQL CHECK
constraint to improve your MySQL database’s data integrity. You should always take advantage of this feature to enforce data quality and improve your business processes’ logic.
As with any application, the correctness of the data is required. For example, the user’s age must be greater than zero, the user’s login name must not contain spaces, the user’s password must meet a certain complexity, and so on.
For these requirements, although we can validate the data entered by the user in the application interface, this cannot replace the data validation at the database level. This can increase the security of the application.
MySQL provides CHECK
constraints to ensure that the data stored in the table meets your requirements. Data that does not meet the CHECK
constraints will be rejected.
Note that MySQL didn’t really support CHECK
constraints until MySQL 8.0.16. In earlier versions, you could only simulate CHECK
constraints through triggers or views with WITH CHECK OPTION
.
MySQL CHECK
syntax
The following is the syntax of MySQL CHECK
:
Here, expr
is a boolean expression that evaluates to a row of data. If it returns true, then MySQL allows this row to be inserted into the table, otherwise MySQL rejects this row into the table with an error.
You can create CHECK
constraints in a CREATE TABLE
statement or add CHECK
constraints in a ALTER TABLE
statement statement.
If you use a CHECK
constraint in a column definition, the CHECK
expression can only refer to this column.
If you are using stand-alone CHECK
constraints, the CHECK
expression can be applied to all columns on the table.
The following takes the age
column needs to be greater than 0 as an example, and uses a different method to add this constraint:
-
Use
CHECK
constraints in column definition in aCREATE TABLE
statementCREATE TABLE user ( id INT AUTO_INCREMENT PRIMARY KEY, age INT NOT NULL );
-
Use
CHECK
constraints in the table level in aCREATE TABLE
statementCREATE TABLE user ( id INT AUTO_INCREMENT PRIMARY KEY, age INT NOT NULL, CONSTRAINT CHECK(age > 0) );
-
Add
CHECK
Constraint in aALTER TABLE
statement
ALTER TABLE user
ADD CONSTRAINT CHECK(age > 0);
MySQL CHECK
Constraint Examples
Through the following examples, you will easily understand the usage and role of MySQL CHECK
constraints.
Suppose, you need a table to store the user’s name, login name, password, and need to meet the following requirements:
- The user’s name cannot be null.
- The login name must be at least 4 characters.
- The password must be at least 8 characters.
- The password cannot be the same as the login name.
You can create a table using the following CREATE TABLE
statement:
CREATE TABLE user (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(45) NOT NULL,
login_name VARCHAR(45) NOT NULL CHECK(length(login_name) >= 4),
password VARCHAR(45) NOT NULL CHECK(length(password) >= 8),
CONSTRAINT CHECK(login_name <> password)
);
Here, there are 3 CHECK
constraints in the CREATE TABLE
statement:
- In the
login_name
column definition,CHECK(length(login_name) >= 4)
ensures that the length of the login name is not less than 4. - In the
password
column definition,CHECK(length(password) >= 8)
ensures that the length of the login name is not less than 8. - The constraint
CONSTRAINT CHECK(login_name <> password)
on the table ensures that password cannot be the same as the login name.
You can view constraints on the user
table with the following SHOW CREATE TABLE
statement:
*************************** 1. row ***************************
Table: user
Create Table: CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`login_name` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `user_chk_1` CHECK ((length(`login_name`) >= 4)),
CONSTRAINT `user_chk_2` CHECK ((length(`password`) >= 8)),
CONSTRAINT `user_chk_3` CHECK ((`login_name` <> `password`))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
As you can see in the output above, there are 3 CHECK
constraints. Constraint names are generated by MySQL by default.
Note that the name
column’s NOT NULL
is also a special constraint.
To verify that whether the CHECK(length(login_name) >= 4)
constraint is in effect, try to insert a row using the following INSERT
statement:
INSERT INTO user (name, login_name, password)
VALUES ('Tim', 'tim', 'timisok');
Since tim
is less than 4, MySQL gives the following error:
ERROR 3819 (HY000): Check constraint 'user_chk_1' is violated.
To verify that whether the CHECK(length(password) >= 8)
constraint is in effect, try inserting a row using the following INSERT
statement:
INSERT INTO user (name, login_name, password)
VALUES ('Tim', 'tim1', 'timisok');
Since timisok
is less than 8, MySQL gives the following error:
ERROR 3819 (HY000): Check constraint 'user_chk_2' is violated.
To verify that whether the CONSTRAINT CHECK(login_name <> password)
constraint is in effect, try inserting a row using the following INSERT
statement:
INSERT INTO user (name, login_name, password)
VALUES ('Tim', 'timisgood', 'timisgood');
Since the login and password given in the above statement are both timisgood
, MySQL gives the following error:
ERROR 3819 (HY000): Check constraint 'user_chk_3' is violated.
You can use the following statement to insert a row that meets all the CHECK
constraints.
INSERT INTO user (name, login_name, password)
VALUES ('Tim', 'hitim', 'timisgood');
The row was successfully inserted into the user
table.
Conclusion
MySQL provides CHECK
constraints to ensure that the data stored in the table meets your requirements. Rows that do not meet the CHECK
constraints are rejected for insertion into the table.
You can add CHECK
constraints for a column or a table.
Earlier I wrote about check constraints when MySQL 8.0.16 was released. But this week I noticed two different folks having similar problems with them. And sadly it is ‘pilot error’.
The first was labeled MYSQL 8.0.17 CHECK not working even though it has been implemented and a cursory glance may make one wonder what is going on with the database.
The table is set up with two constraints. And old timers will probably mutter something under their breath about using ENUMs but here they are:
JOB_TITLE varchar(20) CHECK(JOB_TITLE IN (‘Lecturer’, ‘Professor’, ‘Asst. Professor’, ‘Sr. Lecturer’)),
DEPARTMENT varchar(20) CHECK(DEPARTMENT IN (‘Biotechnology’, ‘Computer Science’, ‘Nano Technology’, ‘Information Technology’)),
And if you cut-n-paste the table definition into MySQL Workbench or MySQL Shell, it is perfectly valid DDL.
So the table is good.
What about the query?
INSERT INTO Employee (FNAME, MNAME, LNAME, BIRTHDATE, GENDER, SSN, JOB_TITLE, SALARY, HIREDATE, TAX, DEPARTMENT ) VALUES
(‘Sangeet’, ‘R’, ‘Sharma’, date ‘1965-11-08’, ‘M’, ’11MH456633′, ‘Prof’, 1200900, date ‘1990-12-16’, 120090, ‘Computer’);
At first glance the query looks good. But notice the use of ‘Prof’ instead of ‘Professor’ and ‘Computer’ instead of ‘Computer Science’. The two respective constraints are are working as they are supposed to. That is why you see the error message ERROR: 3819: Check constraint ’employee_chk_2′ is violated.
So how to fix? Well you can re-write the DDL so that ‘Prof’ and ‘Computer’. Or you can make the data match the specifications. If you are going to the trouble to add a constraint you are sabotaging your own work by doing things like this.
The Second Issue
In another Stackoverflow post someone with this table CREATE TABLE Test( ID CHAR(4), CHECK (CHAR_LENGTH(ID) = 4) ); was wondering why constraint checks were be a problem with insert into Test(ID) VALUES (‘12345’);
And the error you get if you try the above? ERROR: 1406: Data too long for column ‘ID’ at row 1!
Well, this is not a case where a constraint check is behaving badly. Look at the table definition. ID is a four (4) CHAR column. And the length of ‘12345’ is not four!
Now in the past MySQL was lax and would truncate that extra character and provide a warning. And those warnings were often ignored. MySQL had a bad reputation for doing that truncation and the SQL mode of the server was changed to a default setting that does not allow that truncation. Now the server tells you the data is too long for that column. The constraint checks have not come into play at that stage as the server sees you trying to shove five characters into a four character space.
So how to fix? 1) make ID a CHAR(5) and rewrite the constraint, 2) change the SQL mode to allow the server to truncate data, or 3) do not try to put five characters into a space you designed for four.
My Gripe
It is frustrating to see something like constraint checks that are a really useful tool being abused. And it is frustrating as so many people search the web for answers with keywords and will not look at the manual. In both of the examples above five minutes with the manual pages would have save a lot of effort.
Summary: in this tutorial, you will learn how to use MySQL CHECK
constraint to ensure that values stored in a column or group of columns satisfy a Boolean expression.
MySQL 8.0.16 implemented the SQL check constraint. If you use MySQL with the earlier versions, you can emulate a CHECK
constraint using a view WITH CHECK OPTION
or a trigger.
Introduction to the MySQL CHECK
constraint
Prior to MySQL 8.0.16, the CREATE TABLE
allows you to include a table CHECK
constraint. However, the CHECK
constraint is just parsed and ignored:
CHECK(expression)
Code language: SQL (Structured Query Language) (sql)
As of MySQL 8.0.16, the CREATE TABLE
supported essential features of table and column CHECK
constraints for all storage engines.
Here is the syntax:
[CONSTRAINT [constraint_name]] CHECK (expression) [[NOT] ENFORCED]
Code language: SQL (Structured Query Language) (sql)
In this syntax:
First, specify the name for the check constraint that you want to create. If you omit the constraint name, MySQL automatically generates a name with the following convention:
table_name_chk_n
Code language: SQL (Structured Query Language) (sql)
where n
is an ordinal number 1,2,3… For example, the names of CHECK
constraints for the parts
table will be parts_chk_1
, parts_chk_2
, …
Second, specify a Boolean expression
which must evaluate to TRUE
or UNKNOWN
for each row of the table. If the expression evaluates to FALSE
, the values violate the constraint or a constraint violation occurs.
Third, optionally specify enforcement clause to indicate whether the check constraint is enforced:
- Use
ENFORCED
or just omit theENFORCED
clause to create and enforce the constraint. - Use
NOT ENFORCED
to create the constraint but do not enforce it.
As mentioned earlier, you can specify a CHECK
constraint as a table constraint or column constraint.
A table CHECK
constraint can reference multiple columns while the column CHECK
constraint can refer to the only column where it is defined.
MySQL CHECK
constraint examples
Let’s take some examples of using the CHECK
constraints.
1) MySQL CHECK
constraint – column constraint example
This statement creates a new parts
table:
CREATE TABLE parts (
part_no VARCHAR(18) PRIMARY KEY,
description VARCHAR(40),
cost DECIMAL(10,2 ) NOT NULL CHECK (cost >= 0),
price DECIMAL(10,2) NOT NULL CHECK (price >= 0)
);
Code language: SQL (Structured Query Language) (sql)
In this statement, we have two column CHECK
constraints: one for the cost column and the other for the price column.
Because we did not explicitly specify the names for the CHECK
constraints, MySQL automatically generated names for them.
To view the table definition with the CHECK
constraint name, you use the SHOW CREATE TABLE
statement:
SHOW CREATE TABLE parts;
Code language: SQL (Structured Query Language) (sql)
Here is the output:
As you can see clearly from the output, MySQL generated the check constraint parts_chk_1
and parts_chk_2
.
Once the CHECK
constraints are in place, whenever you insert or update a value that causes the Boolean expression evaluates to false, MySQL rejects the change and issues an error.
This statement inserts a new row into the parts table:
INSERT INTO parts(part_no, description,cost,price)
VALUES('A-001','Cooler',0,-100);
Code language: SQL (Structured Query Language) (sql)
MySQL issued an error:
Error Code: 3819. Check constraint 'parts_chk_2' is violated.
Code language: SQL (Structured Query Language) (sql)
Because the value of the price
column is negative which causes the expression price > 0
evaluates to FALSE
that results in a constraint violation.
2) MySQL CHECK
constraint – table constraint example
First, drop the parts
table:
DROP TABLE IF EXISTS parts;
Code language: SQL (Structured Query Language) (sql)
Then, create a new parts
table with one more table CHECK
constraint:
CREATE TABLE parts (
part_no VARCHAR(18) PRIMARY KEY,
description VARCHAR(40),
cost DECIMAL(10,2 ) NOT NULL CHECK (cost >= 0),
price DECIMAL(10,2) NOT NULL CHECK (price >= 0),
CONSTRAINT parts_chk_price_gt_cost
CHECK(price >= cost)
);
Code language: SQL (Structured Query Language) (sql)
The following new clause defines a table CHECK
constraint that ensures the price is always greater than or equal to cost:
CONSTRAINT parts_chk_price_gt_cost CHECK(price >= cost)
Code language: SQL (Structured Query Language) (sql)
Because we explicitly specify the name for the CHECK
constraint, MySQL just creates the new constraint with the specified name.
Here is the definition of the parts
table:
SHOW CREATE TABLE parts;
Code language: SQL (Structured Query Language) (sql)
The table CHECK
constraint appears at the end of the table definition after the column list.
This statement attempts to insert a new part whose price is less than cost:
INSERT INTO parts(part_no, description,cost,price)
VALUES('A-001','Cooler',200,100);
Code language: SQL (Structured Query Language) (sql)
Here is the error due to the constraint violation:
Error Code: 3819. Check constraint 'parts_chk_price_gt_cost' is violated.
Code language: SQL (Structured Query Language) (sql)
In this tutorial, you have learned about the MySQL CHECK
constraints to ensure values stored in a column satisfy a Boolean condition.
Was this tutorial helpful?
check constraint means to filter one or more columns according to certain preset rules. If the condition is true, the filtering succeeds; if the condition is false, the filtering fails and the failure code is returned to the client.
Why do you want to list and write this separately? You often encounter irregular SQL. In many cases, you can only filter by the database layer. If you don’t filter on the code side, you can only filter on the database side.
1, Common filtering methods
Assume table f1, field r1 is a multiple of 3, otherwise write is rejected. And suppose that the input of r1 is not standardized and can only be filtered by the database, what should we do? There are only a few:
1) Write pre trigger
Example 1
mysql> create table f1 (r1 int); Query OK, 0 rows affected (0.03 sec) DELIMITER $ USE `ytt`$ DROP TRIGGER /*!50032 IF EXISTS */ `tr_check_f1_r1`$ CREATE /*!50017 DEFINER = 'root'@'%' */ TRIGGER `tr_check_f1_r1` BEFORE INSERT ON `f1 FOR EACH ROW BEGIN IF MOD(new.r1,3) <> 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Column r1 should be mod by 3,failed to insert.'; END IF; END; $ DELIMITER ;
Under execution, exceptions are exposed
mysql> insert into f1 values (5); ERROR 1644 (45000): Column r1 should be mod by 3,failed to insert.
Normal insertion
mysql> insert into f1 values (3); Query OK, 1 row affected (0.01 sec) mysql> select * from f1; +------+ | r1 | +------+ | 3 | +------+ 1 row in set (0.00 sec)
The above example is simple for the scenario of single column filtering, and the complex filtering of multiple columns will be discussed later.
2) Write stored procedure encapsulate SQL
Processing input constraint in stored procedure is the same as processing input constraint logic in program side, but the same processing logic is placed in database side, and all data input in the future can only rely on a single entry of stored procedure.
3) Do not reject any input, and regularly process irregular data
This will lead to a large amount of data input, and there are many useless irregular data. Generally, irregular data is processed regularly during non business peak hours.
There are no examples of these two methods, which are similar to the first one.
2, CHECK constraint
Now we want to talk about the CHECK constraint that has been standardized before the table based definition filtered at the column level. (MySQL version > = 8.0.16)
mysql> create table f1 (r1 int constraint tb_f1_r1_chk1 check (mod(r1,3)=0)); Query OK, 0 rows affected (0.03 sec) mysql> create table f2 (r1 int constraint tb_f2_r1_chk1 check (mod(r1,3)=0) not enforced); Query OK, 0 rows affected (0.02 sec)
Here, the related restrictions of CHECK constraint are as follows:
- constraint names are unique in each database.
In other words, there are not two identical constraints in a single database. If they are not defined, the system will automatically generate a unique constraint name.
-
The check constraint is valid for the statement insert/update/replace/load data/load xml; it is invalid for the corresponding ignore statement.
-
Not every function can be used. For example, if the result of the function is uncertain: NOW(), connection ﹣ ID (), current ﹣ user().
-
Not for stored procedures and stored functions.
-
System variable is not applicable.
-
Subqueries are not applicable.
-
Foreign key actions (such as ON UPDATE, ON DELETE) are not applicable.
-
Enforced is enabled by default. If not enforced is added separately, the check constraint fails.
Example 2
In combination with the actual examples of the two tables above, the check constraint is only valid for table f1.
mysql> insert into f1 values (10); ERROR 3819 (HY000): Check constraint 'tb_f1_r1_chk1' is violated. mysql> insert into f2 values (10); Query OK, 1 row affected (0.01 sec) mysql> select * from f1 Empty set (0.00 sec) mysql> select * from f2; +------+ | r1 | +------+ | 10 | +------+ 1 row in set (0.00 sec)
Let’s look at a more detailed example of the CHECK constraint.
Example 3
mysql> drop table f1; Query OK, 0 rows affected (0.02 sec) mysql> create table f1 -> ( -> r1 int constraint tb_f1_r1_chk1 check (r1 > 10), -> r2 int constraint tb_f1_r2_positive check (r2 > 0), -> r3 int constraint tb_f1_r3_chk1 check (r3 < 100), -> constraint tb_f1_r1_nonzero check (r1 <> 0), -> constraint tb_f1_r1r2_chk1 check (r1 <> r2), -> constraint tb_f1_r1r3_chk1 check (r1 > r3) -> ); Query OK, 0 rows affected (0.02 sec)
There is a point in the above example,
-
The constraints TB ﹣ F1 ﹣ R1 ﹣ nonzero, TB ﹣ F1 ﹣ R1 ﹣ R2 ﹣ CHK1, TB ﹣ F1 ﹣ R3 ﹣ chk do not follow the fixed column, which is effective for the whole, or the table based check constraint.
-
Constraint TB ﹣ F1 ﹣ R1 ﹣ contains constraint TB ﹣ F1 ﹣ R1 ﹣ nonezero, so that TB ﹣ F1 ﹣ R1 ﹣ nonezero will never detect an exception. So after checking, remove this constraint.
The definition after removing redundant constraints,
mysql> create table f1 -> ( -> r1 int constraint tb_f1_r1_chk1 check (r1 > 10), -> r2 int constraint tb_f1_r2_positive check (r2 > 0), -> r3 int constraint tb_f1_r3_chk1 check (r3 < 100), -> constraint tb_f1_r1r2_chk1 check (r1 <> r2), -> constraint tb_f1_r1r3_chk1 check (r1 > r3) -> ); Query OK, 0 rows affected (0.02 sec)
If you want to do a test on this table, you can see that the constraint of each column here is actually the relationship between and. If any column constraint is not established, the write fails.
mysql> insert into f1 values (20,10,10); Query OK, 1 row affected (0.01 sec) mysql> insert into f1 values (10,10,10); ERROR 3819 (HY000): Check constraint 'tb_f1_r1_chk1' is violated. mysql> insert into f1 values (20,-10,10); ERROR 3819 (HY000): Check constraint 'tb_f1_r2_positive' is violated. mysql> insert into f1 values (20,10,30); ERROR 3819 (HY000): Check constraint 'tb_f1_r1r3_chk1' is violated.
Next, we modify the trigger at the beginning. As long as we add the relevant conditions, we can implement the same check column constraint.
DELIMITER $ USE `ytt`$ DROP TRIGGER /*!50032 IF EXISTS */ `tr_check_f1_r1`$ CREATE /*!50017 DEFINER = 'root'@'%' */ TRIGGER `tr_check_f1_r1` BEFORE INSERT ON `f1` FOR EACH ROW BEGIN DECLARE v1 TINYINT DEFAULT 0; IF (new.r1 > 10 AND new.r1 > new.r3 AND new.r1 <> new.r2 AND new.r2 > 0 AND new.r3 < 100) = 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "Failed to write: constraint check: n (n r1 >10 n&& r1 > r3 n&& r1 <> r2 n&& r2> 0 n&& r3 < 100n)."; END IF; END; $ DELIMITER ;
Test results,
mysql> insert into f1 values (20,30,100); ERROR 1644 (45000): Failed to write: constraint check: ( r1 >10 && r1 > r3 && r1 <> r2 && r2> 0 && r3 < 100 ). mysql> insert into f1 values (100,30,90); Query OK, 1 row affected (0.01 sec) mysql> select * from f1; +------+------+------+ | r1 | r2 | r3 | +------+------+------+ | 100 | 30 | 90 | +------+------+------+ 1 row in set (0.00 sec)
conclusion
This paper introduces the usage of database CHECK constraint and some examples.
I personally suggest that the best way to implement this CHECK constraint is to split it from the database side to the application side. The simpler the data side, the better the performance. But there are exceptions. If the application side is difficult to implement due to historical reasons or other factors, it can only be sent to the database side.
What else do you want to know about MySQL technology? Leave a message and tell Xiaobian!
Мой вопрос говорит о том, что он хочет, чтобы я добавил ограничение, чтобы компания не могла больше покупать автомобили, выпущенные до 2018 года. Проблема в том, что в моей базе данных уже есть информация об автомобилях, выпущенных до 2018 года. Я не могу удалить таблицу, потому что она будет возиться с некоторыми из моих других запросов. Могу я получить совет по этому поводу?
Мой код ниже для таблицы транспортных средств
create table Vehicle(
LicensePlate varchar(48) primary key, /*Primary key for table Vehicle for License plate, variable can hold up to 48 characters*/
Make varchar (48),
CarYear int
);
insert into Vehicle (LicensePlate,Make,CarYear) values ('1234 AA','Toyota',1970);
insert into Vehicle (LicensePlate,Make,CarYear) values ('1237 AB','Mazda',1995);
insert into Vehicle (LicensePlate,Make,CarYear) values ('1892 BG','Toyota',2000);
insert into Vehicle (LicensePlate,Make,CarYear) values ('1876 FA','Nissan',1999);
insert into Vehicle (LicensePlate,Make,CarYear) values ('3021 AA','Mazda',1950);
insert into Vehicle (LicensePlate,Make,CarYear) values ('2134 FF','Toyota',1992);
-- Company has decided not to purchase any more car that were made before 2018. Add appropriate constraints to the Vehicle table to enforce this requirement.
alter table Vehicle add constraint checker_1 check (CarYear > 2018);
mathina, 1 ноября 2022 г., 23:43
135
1
Introduction
Starting from MySQL 8.0.16 database server and later versions, a CHECK
constraint is a feature that allows you to specify a condition that validates data during an INSERT
or UPDATE
command. If the constraint is violated when an SQL statement is issued against a table, MySQL raises a general error and aborts the operation altogether. You can use the MySQL CHECK
constraints to enforce business logic at the backend of your application to achieve data integrity. Also, by defining specific data restrictions in the database server, you can be sure that all data administrators in a multi-user environment adhere to the set business rules when making modifications directly in the database without going through a user interface.
For instance, in your organization, you can place a policy that requires all employees to come from the state of CALIFORNIA
. To avoid this rule from being violated in the system, you can code a validation logic in your database. Any database administrator registering employees from the non-allowlisted states should get an error. To put this in a better perspective, you’ll create a sample_company
database and an employees
table in this guide. You’ll then put a CHECK
constraint to limit the value range that can be placed in the state
column for new staff members joining your hypothetical company.
Prerequisites
To follow along with this tutorial, make sure you have the following:
-
An Vultr Ubuntu 20.04 server.
-
A sudo user.
-
A LAMP Stack. You can also follow this tutorial on a Vultr One-Click LAMP server.
Create a sample_company
Database
Connect to your server and log in to MySQL as root.
$ sudo mysql -u root -p
Enter the root password of your MySQL server and press ENTER to proceed. Then, issue the command below to create a sample_company
database`.
mysql> CREATE DATABASE sample_company;
Switch to the sample_company
database.
mysql> USE sample_company;
Create an employees
Table
You’ll create an employees
table. This table acts as an employee register, and new staff members’ details must be inserted here. The employee_id
will be a unique key to identify each employee. Then, the first_name
and last_name
fields will record the full names of the employees. Finally, you’ll use the state
column to record the employees’ localities.
Run the command below to create the employees
table.
mysql> CREATE TABLE employees (
employee_id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
state VARCHAR(50)
) ENGINE = InnoDB;
Before entering any records into the table, you’ll set a validation rule in the next step.
Set a Check Constraint in the employees
Table
With the employees
table in place, you’re going to set a CHECK
constraint that only allows staff members from the CALIFORNIA
state.
Run the command below to add the constraint.
mysql> ALTER TABLE employees
ADD CHECK (state = 'CALIFORNIA');
Make sure you get the output below to confirm the table has been updated with a new constraint.
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
Test the CHECK
Constraint
Create a valid record in the employees
table. For this entry, don’t violate the state
column’s CHECK
constraint.
mysql> INSERT INTO employees
(
first_name,
last_name,
state
)
VALUES
(
'JOHN',
'DOE',
'CALIFORNIA'
);
Your record should be inserted into the employees
table without any problems.
Query OK, 1 row affected (0.00 sec)
Query the employees
table to confirm if the record was inserted into the table.
mysql> SELECT
employee_id,
first_name,
last_name,
state
FROM employees;
The output below confirms that the record is in place.
+-------------+------------+-----------+------------+
| employee_id | first_name | last_name | state |
+-------------+------------+-----------+------------+
| 1 | JOHN | DOE | CALIFORNIA |
+-------------+------------+-----------+------------+
1 row in set (0.00 sec)
Next, attempt to insert a new employee from the FLORIDA
state and see if the CHECK
constraint for the state
column will be violated.
Run the INSERT
command below.
mysql> INSERT INTO employees
(
first_name,
last_name,
state
)
VALUES
(
'MARY',
'SMITH',
'FLORIDA'
);
The command above should fail, and you should receive a standard error message displaying that the constraint has been violated.
ERROR 3819 (HY000): Check constraint 'employees_chk_1' is violated.
Map Multiple Constraints
For this demonstration, you may use the MySQL IN
clause to create an allowlist of multiple states that you want to be accepted in the employees
table.
To do this, you’ll need to delete the first CHECK
constraint and create a new one. Confirm the name of the constraint by running the SELECT
command below against the INFORMATION_SCHEMA
table.
mysql> SELECT
CONSTRAINT_NAME,
TABLE_SCHEMA,
TABLE_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'employees'
AND CONSTRAINT_SCHEMA = 'sample_company'
AND CONSTRAINT_TYPE = 'CHECK';
Check the name of the constraint as displayed in the CONSTRAINT_NAME
column as shown below.
+-----------------+----------------+------------+
| CONSTRAINT_NAME | TABLE_SCHEMA | TABLE_NAME |
+-----------------+----------------+------------+
| employees_chk_1 | sample_company | employees |
+-----------------+----------------+------------+
1 row in set (0.01 sec)
Then, DROP
the constraint. In this case, delete the employees_chk_1
.
mysql> ALTER TABLE employees
DROP CHECK employees_chk_1;
The output below confirms the deletion of the employees_chk_1
constraint.
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
Create a new constraint with the new rules.
mysql> ALTER TABLE employees
ADD CHECK (state IN ('CALIFORNIA', 'COLORADO', 'ARIZONA'));
Ensure you get the output as shown below.
Query OK, 1 row affected (0.23 sec)
Records: 1 Duplicates: 0 Warnings: 0
Next, try to insert new records from both the COLORADO
and ARIZONA
state.
mysql> INSERT INTO employees
(
first_name,
last_name,
state
)
VALUES
(
'JANE',
'MARK',
'COLORADO'
);
mysql> INSERT INTO employees
(
first_name,
last_name,
state
)
VALUES
(
'PETER',
'SMITH',
'ARIZONA'
);
You should get a success message from both INSERT
statements above.
Query OK, 1 row affected (0.00 sec)
Confirm the data by running a SELECT
statement against the employees
table.
mysql> SELECT
employee_id,
first_name,
last_name,
state
FROM employees;
You should now see a list of 3
employees as shown below.
+-------------+------------+-----------+------------+
| employee_id | first_name | last_name | state |
+-------------+------------+-----------+------------+
| 1 | JOHN | DOE | CALIFORNIA |
| 2 | JANE | MARK | COLORADO |
| 3 | PETER | SMITH | ARIZONA |
+-------------+------------+-----------+------------+
3 rows in set (0.00 sec)
Again, try to violate the CHECK
constraint with an employee from a non-allowlisted state such as HAWAII
) and see if an error will be thrown.
mysql> INSERT INTO employees
(
first_name,
last_name,
state
)
VALUES
(
'FRANK',
'JACOB',
'HAWAII'
);
You should get an error as shown below because FRANK JACOB
does not come from CALIFORNIA
, COLORADO
or ARIZONA
.
ERROR 3819 (HY000): Check constraint 'employees_chk_1' is violated.
This confirms that your CHECK
constraint has indeed mapped multiple allowlist values and is working as expected.
Conclusion
In this tutorial, you’ve used MySQL CHECK
constraint to improve your MySQL database’s data integrity. You should always take advantage of this feature to enforce data quality and improve your business processes’ logic.
MySQL CHECK is an integrity constraint. The CHECK constraint is specifically used for restricting the input values that can be allowed to one or more columns in a table.
The CHECK constraint functionality can be utilized after version 8.0.16 and above. Before MySQL 8.0.16 version, the syntax of the CHECK constraint was acceptable although the functionality was ignored. This means, when using CHECK, syntactically it would be accepted by MySQL but the constraint is overlooked while the statement was executed or is simply ignored.
The latest versions of MySQL allow us to use the CHECK constraint syntactically as well as while executing the statement, which means if in case, the value doesn’t meet the CHECK constraint’s requirement then an error is thrown.
CHECK constraint using CREATE TABLE statement
We can put a CHECK constraint on a single column or multiple columns when we are creating a table.
Below is the syntax for the CHECK constraint while creating a table:
CREATE TABLE tablename (
Value1 datatype,
Value2 datatype,
Value3 datatype CHECK check_constraint,
CONSTRAINT check_name CHECK (constraint)
);
Code language: SQL (Structured Query Language) (sql)
For better understanding let’s take an example. We’ll create a table as Employee and will have four attributes, such as name, gender, age, and email. Out of these four values, we are going to put CHECK constraint on gender, specifically male(M) or female(F), or transgender(T).
CREATE TABLE employee(
Name varchar(50),
Age int,
Email varchar(50),
Gender char(1) CHECK (Gender in(‘M’,’F’,’T’))
);
Code language: SQL (Structured Query Language) (sql)
CHECK constraint using ALTER table statement
In cases where the table already exists, and we want to put a constraint over a column then it can be possible by putting a constraint on a column with ALTER Table. In our case, we’ll use the CHECK constraint.
Below is the syntax for creating a CHECK constraint using ALTER table:
ALTER TABLE tablename
ADD constraint_name CHECK (check_constraint);
Code language: SQL (Structured Query Language) (sql)
Let’s understand it with an example, we’ll take the employee table which we just created, having the name, age, email, and gender of the employees in which gender already has a check constraint. We need to restrict the age of our employees from 18 to 65. Let’s see how to write a statement for the same.
ALERT TABLE employee
ADD chk_age CHECK (Age >= 18 AND Age <=65);
Code language: SQL (Structured Query Language) (sql)
Insert data into the table and Check the constraint error
As we have created all the necessary CHECK constraints on the Employee table, now whenever we’ll insert data into the table then the constraints will also be checked before the data is inserted into the table by SQL.
For example, if we write the below statement for the employee table then MySQL will throw an error. As we have only allowed three input values to the Gender column which are F, M, and T for Female, Male, and Transgender respectively. But in the below example, even though the gender is technically correct still SQL will throw an error because we have allowed ‘F’ for female and no other value.
INSERT INTO employee
VALUES ('Anamika' , 34, 'ana@mail.co' , 'Female');
Code language: SQL (Structured Query Language) (sql)
The error below is the error that you’ll see whenever you’ll violate the constraint which is set for a particular column in a table. The best thing to do to resolve this error is to insert only those values which are within the range of the constraint which is set for the said column in that table.
ERROR 3819 (HY000): Check constraint ‘e_chk_1’ is violated.
View existing constraints on a particular table
If you want to check if a constraint or any constraint exists within the table then you can use the following command. This command will show a tabular output of all the constraint-related data for the table name you’ve passed in the statement, in our case we’ll use the employee table.
SELECT *
FROM information_schema.table_constraints
WHERE table_schema = schema()
AND table_name = 'employee';
Code language: SQL (Structured Query Language) (sql)
Remove/Drop CHECK constraint
To drop a check constraint from a particular column in a table we use ALTER table statement.
Let’s see an example to understand how it works. We’ll take the employee table which we are using in this tutorial, we currently have two CHECK constraints on the table. The first is the constraint is for the gender column and the second is for the age column. In the below example, we’ll drop the CHECK constraint on the age column.
ALTER TABLE employee
DROP constraint chk_age;
Code language: SQL (Structured Query Language) (sql)
Useful Resources:
https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
My question says that it wants me to add a constraint so that the company cannot purchase any more car that were made before 2018.The problem is that my database already has info about cars that were made before 2018. I cant delete the table because it will mess with some of my other queries . Can i get some advice on it?
My code below for vehicle table
create table Vehicle(
LicensePlate varchar(48) primary key, /*Primary key for table Vehicle for License plate, variable can hold up to 48 characters*/
Make varchar (48),
CarYear int
);
insert into Vehicle (LicensePlate,Make,CarYear) values ('1234 AA','Toyota',1970);
insert into Vehicle (LicensePlate,Make,CarYear) values ('1237 AB','Mazda',1995);
insert into Vehicle (LicensePlate,Make,CarYear) values ('1892 BG','Toyota',2000);
insert into Vehicle (LicensePlate,Make,CarYear) values ('1876 FA','Nissan',1999);
insert into Vehicle (LicensePlate,Make,CarYear) values ('3021 AA','Mazda',1950);
insert into Vehicle (LicensePlate,Make,CarYear) values ('2134 FF','Toyota',1992);
-- Company has decided not to purchase any more car that were made before 2018. Add appropriate constraints to the Vehicle table to enforce this requirement.
alter table Vehicle add constraint checker_1 check (CarYear > 2018);