Code has been added to clipboard!

Using SQL CHECK on Different Database Systems

Reading time 2 min
Published Aug 9, 2017
Updated Oct 11, 2019

SQL CHECK Constraint: Main Tips

  • This constraint is needed in order to cap the range of values that could be in the column.
  • When defining the constraint to a sole column it permits just specific values to that column.
  • When defining the constraint to a table it will cap the values of specific columns by basing off the values of different columns in the same row.

CHECK CREATE TABLE

The code examples below produce a constraint CHECK in the "Person" table on the column "P_Ids". The constraint defines that the column can only have integers bigger than 0.

MySQL:

Example
CREATE TABLE Person
(
P_Ids int NOT NULL,
LName varchar(255) NOT NULL,
FName varchar(255),
AddressID varchar(255),
CityID varchar(255),
CHECK (P_Ids>0)
)

MS Access / SQL Server / Oracle:

Example
CREATE TABLE Person
(
P_Ids int NOT NULL CHECK (P_Ids>),
LName varchar(255) NOT NULL,
FName varchar(255),
AddressID varchar(255),
CityID varchar(255)
)

In order to be able to name the constraint CHECK, and defining it on various columns, the example below shows the syntax:

MS Access / SQL Server / Oracle / MySQL:

Example
CREATE TABLE Person
(
P_Ids int NOT NULL,
LName varchar(255) NOT NULL,
FName varchar(255),
AddressID varchar(255),
CityID varchar(255),
CONSTRAINT ck_Person CHECK (P_Ids>0 AND CityID='paris')
)

CHECK ALTER TABLE

When creating a constraint CHECK after a table is produced:

MS Access / SQL Server / Oracle / MySQL:

Example
ALTER TABLE Person
ADD CHECK (P_Ids>0)

In order to be able to name the constraint CHECK, and defining it on various columns, the example below shows the syntax:

MS Access / SQL Server / MySQL / Oracle:

Example
ALTER TABLE Person
ADD CONSTRAINT ck_Person CHECK (P_Ids>0 AND CityID='Paris')

DROP CHECK: Example

The code examples below show how to drop the constraint CHECK:

SQL Server / MS Access / Oracle:

Example
ALTER TABLE Person
DROP CONSTRAINT ck_Person

MySQL:

Example
ALTER TABLE Person
DROP CHECK CK_PersonsAge;
Learn SQL
Introduction
Syntax
Data Types
Server Data Types
Commands
Commands List
Wildcards
Constraints
Aggregate Functions
Date Functions
Date Format
Injection
SQL Server Hosting
Views
Auto-incrementation
SQL Operators
AS
AND & OR
IN
BETWEEN
WHERE
GROUP BY
HAVING
ORDER BY
LIKE
NOT
NOT EQUAL
UNION
NULL
NOT NULL
DEFAULT
UNIQUE
FOREIGN KEY
PRIMARY KEY
CHECK
Indexes
ALTER TABLE
CREATE DATABASE
CREATE TABLE
DELETE
DROP
INSERT INTO SELECT
INSERT INTO
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
UPDATE
FULL OUTER JOIN
INNER JOIN
JOIN
LEFT JOIN
RIGHT JOIN
AVG()
COUNT
FIRST
LAST
MAX
MIN()
SUM()
LEN
UCASE
MID
NOW
ROUND
FORMAT
LOWER
CONVERT
ISNULL