How to bypass check constraints in SQL
P粉642436282
P粉642436282 2024-04-01 15:19:51
0
1
469

Architecture

create table course
        (course_id  varchar(8), 
         title      varchar(50), 
         dept_name  varchar(20),
         credits    numeric(2,0) check (credits > 0),
         primary key (course_id),
         foreign key (dept_name) references department (dept_name)
            on delete set null
        );

I want to add this data to the table but cannot add 0 points.

"CS-001", titled "Weekly Seminar", 0 Credits

Insert query

INSERT INTO `course`(`course_id`, `title`, `credits`) VALUES ('CS-001','Weekly Seminar','0');

search result:

Is there any other way to insert the same data without changing the table structure?

P粉642436282
P粉642436282

reply all(1)
P粉554842091

foreign_key_checks option affects foreign key enforcement, not check constraint enforcement.

mysql> set foreign_key_checks=0;
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO `course`(`course_id`, `title`, `credits`) VALUES ('CS-001','Weekly Seminar','0');
ERROR 3819 (HY000): Check constraint 'course_chk_1' is violated.

You must use ALTER TABLE, but you do not have to drop the constraint.

mysql> alter table course alter check course_chk_1 not enforced;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> INSERT INTO `course`(`course_id`, `title`, `credits`) VALUES ('CS-001','Weekly Seminar','0');
Query OK, 1 row affected (0.00 sec)

But once the row is inserted, the check constraint cannot be re-enabled because the row will be re-checked when the constraint is enabled.

mysql> alter table course alter check course_chk_1 enforced;
ERROR 3819 (HY000): Check constraint 'course_chk_1' is violated.

You can subsequently delete or update the row that violates the check constraint and re-enable the constraint.

If you need to be able to insert a zero value into the credits column, then check (credits > 0) doesn't seem to be the right choice for that column. Maybe check(credits >= 0) required.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template