Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • What is CHECK Constraint in MySQL?

    • 0
    • 1
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 672
    Comment on it

    In MySQL, the CHECK constraint is used to put limit on value range on value inside a column.

    CHECK Constraint on CREATE TABLE

    The following statement creates a CHECK constraint on the "id" column when the "employee" table is created. The CHECK constraint specifies that the column "id" should only include integer values greater than 0:

    Example:

    CREATE TABLE employee
    (
    id int NOT NULL,
    first_name varchar(45) NOT NULL,
    last_name varchar(45),
    country varchar(45),
    CHECK (id>0)
    );
    

    We can also define CHECK constraint on multiple column, for this use the below statement:

    CREATE TABLE emplyee
    (
    id int NOT NULL,
    first_name varchar(45) NOT NULL,
    last_name varchar(45),
    country varchar(45),
    CONSTRAINT chk_Person CHECK (id>0 AND country='Canada')
    );
    

    CHECK Constraint on ALTER TABLE

    We can also create CHECK constraint on a column when the table is already created, for that we use ALTER command.

    ALTER TABLE employee
    ADD CHECK (id>0);
    

    Similarly we can define CHECK constraint on multiple columns when the table is already created as below:

    ALTER TABLE employee
    ADD CONSTRAINT chk_employee CHECK (id>0 AND country='Canada');
    

    To DROP a CHECK Constraint

    We can also drop a CHECK constraint. To drop a CHECK constraint, use the below statement:

    ALTER TABLE employee
    DROP CHECK chk_employee;
    
    Hope this will help you :)
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: