SQL Check Constraints on MySQL Databases

An SQL check constraint is used and designed in the schema of a database table to restrict the range of values that can be entered into a specific field. In many experienced, they are very rarely used. However, these simple checks, entered at the time of database table creation, can provide additional safe guards against ‘bad’ data getting into your database tables, either via errors in code or simply user area. SQL check constraints can act as a last line of defence against ‘bad’ data, as it is verification at the database level.

You can create a table with a check constraint in MySQL as follows. The check in this example disallows values of the ‘P_Id’ field from falling outside of the condition ‘P_Id>0′. In other words, the ‘P_Id’ field’s values must almost be greater than zero in order for the data to be accepted into the table by the database management system (DBMS).

CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
)

You are probably wondering how to add a constraint to an existing database table. This is quite easy, and uses an ‘ALTER TABLE’ SQL query. See the following example for how to add a check constraint to one of your existing database tables.

ALTER TABLE Persons
ADD CHECK (P_Id>0)

For more information, there are other highly useful example queries relating to SQL check constraints at the relevant SQL check constraint article on W3schools.

If you liked this post, you may be interested in these:

  1. SQL Check Constraints not supported in MySQL
  2. Storing PHP Session data in a database
  1. Matar says:

    MySQL accepts this, but ignores it.

    I tried your Persons example. It worked.
    I did: INSERT INTO Persons (P_Id, LastName, FirstName, Address, City) VALUES (‘-1′, ‘ln’, ‘fn’, ‘a’, ‘c’);
    It also worked.

    MySQL ignores CHECKs…

    “The CHECK value is not available until we support CHECK.”
    http://dev.mysql.com/doc/refman/5.1/en/table-constraints-table.html

  2. [...] previously wrote about using SQL check constraints in MySQL. It seems however that the MySQL relational database management system (RDBMS) does not actually [...]

Howdy! My name is Jordan Hall and you’ve reached my website for some reason. Hope you are enjoying it. If you want, I have a few more details about this website. If you are looking for a more professional overview and less general prose, take a look at my biography or my skill and experiences section.

Latest Project

A portfolio of sorts will appear here shortly listing some of the projects I've developed or those I'm currently working on.

For now, take a look at my projects page directly.

Latest Photographs

Some photograph previews will appear here at some point.

Please feel free to take a look at my photographs page.

Latest Comments