SQL Check Constraint with Examples - How to use SQL Check Constraints



SQL CHECK Constraint

  • The CHECK constraint is employed to restrict the range of values that can be inserted into a column.
  • When you define a CHECK constraint on a column, it permits only specific values for that column. Additionally, if you define a CHECK constraint on a table, it can restrict the values in certain columns based on values in other columns within the same row.

SQL CHECK on CREATE TABLE

  • The SQL below establishes a CHECK constraint on the "Age" column during the creation of the "Wikitechy" table. This CHECK constraint guarantees that a person's age must be 16 or younger.

Example

    CREATE TABLE tbl_Wikitechy (
        ID int NOT NULL,
        Student_Name varchar(50) NOT NULL,
        Mark int,
        Age int CHECK (Age<=16)
        );
    

Output

Step 1:

check-constraint-ouput

Step 2:

check-constraint-ouput-2
  • The image below illustrates an error occurring when entering a value exceeding the specified limit. After correcting the query, the operation was successful
sql-error-output

SQL CHECK on ALTER TABLE

  • To add a CHECK constraint on the "Age" column when the table is already created, use the following SQL

Example

    ALTER TABLE tbl_Wikitechy
    ADD CHECK (Age<=16);
    
    

Output

Step 1

sql-check-constraint-alter-ouput

Step 2:

sql-check-constraint-alter-ouput-2

DROP a CHECK Constraint

  • To remove or drop a CHECK constraint, use the following SQL:

Example

    ALTER TABLE tbl_Wikitechy
    DROP CONSTRAINT CHK_tbl_WikitechyAge;
    

Output

Step 1:

sql-check-constraint-dropr-ouput

Step 2:

sql-check-constraint-dropr-ouput-2

Related Searches to SQL Check Constraint with Examples - How to use SQL Check Constraints