Wednesday, December 18, 2024

SQL CHECK Keyword

 The CHECK keyword in SQL is used to define a constraint that limits the values that can be inserted into a column. It ensures that the values in a column meet a specified condition. If the condition is not met, an error is raised, and the operation is rejected.

Syntax:

CREATE TABLE table_name (
    column_name data_type,
    CONSTRAINT constraint_name CHECK (condition)
);

Example:

  1. Creating a table with a CHECK constraint:

    CREATE TABLE employees (
        id INT,
        name VARCHAR(100),
        age INT,
        CONSTRAINT chk_age CHECK (age >= 18)
    );
    

    In this example, the CHECK constraint ensures that only values where age is greater than or equal to 18 can be inserted into the age column.

  2. Using CHECK with a column definition:

    CREATE TABLE students (
        id INT,
        name VARCHAR(100),
        grade CHAR(1),
        CHECK (grade IN ('A', 'B', 'C', 'D', 'F'))
    );
    

    In this example, the CHECK constraint ensures that the grade column only contains values from the set ('A', 'B', 'C', 'D', 'F').

  3. Adding a CHECK constraint to an existing table:

    ALTER TABLE employees
    ADD CONSTRAINT chk_age CHECK (age >= 18);
    

Key Points:

  • The condition inside the CHECK constraint can reference multiple columns and use operators like =, >, <, BETWEEN, IN, etc.
  • It can also be used to ensure that values fall within a certain range or match specific patterns (e.g., an email address).
  • If a value violating the CHECK constraint is inserted, an error is thrown, and the insertion is blocked.

Note: Not all database systems support CHECK constraints, or they might implement them with slight variations.

No comments:

Post a Comment