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.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Identi.ca
  • MySpace
  • Slashdot
  • StumbleUpon
  • Twitter
  • Reddit
    • Matar
    • March 2nd, 2010

    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

  1. No trackbacks yet.