WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

SQL CHECK Constraint


SQL CHECK Constraint

CHECK constraint is used to limit the value range that can be placed in a column.


SQL CHECK Constraint on CREATE TABLE

The following SQL creates a CHECK constraint on the "User_Id" column when the "Persons" table is created. The CHECK constraint specifies that the column "User_Id" must only include integers greater than 0.

MySQL:

CREATE TABLE Persons
(
User_Id int NOT NULL,
Username varchar(255) NOT NULL,
Password varchar(255),
email varchar(255),
Phone varchar(255),
CHECK (User_Id>0)
)

SQL Server / Oracle / MS Access:

CREATE TABLE Persons
(
User_Id int NOT NULL CHECK (User_Id>0),
Username varchar(255) NOT NULL,
Password varchar(255),
email varchar(255),
Phone varchar(255)
)

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons
(
User_Id int NOT NULL,
Username varchar(255) NOT NULL,
Password varchar(255),
email varchar(255),
Phone varchar(255),
CONSTRAINT chk_Person CHECK (User_Id>0 AND Phone='Sandnes')
)

SQL CHECK Constraint on ALTER TABLE

To create a CHECK constraint on the "User_Id" column when the table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons
ADD CHECK (User_Id>0)

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons
ADD CONSTRAINT chk_Person CHECK (User_Id>0 AND Phone='Sandnes')

To DROP a CHECK Constraint

To drop a CHECK constraint, use the following SQL:

SQL Server / Oracle / MS Access:

ALTER TABLE Persons
DROP CONSTRAINT chk_Person

MySQL:

ALTER TABLE Persons
DROP CHECK chk_Person