MySQL CHECK Constraint

MySQL CHECK Constraint

The CHECK constraint in MySQL is used to ensure that the values in a column meet a specific condition.
It is a way to enforce data integrity rules at the column or table level.

⚠️ MySQL supports CHECK constraints fully from version 8.0.16.


🔹 Syntax (Column-Level)


  • condition → Logical expression that values must satisfy


🔹 Syntax (Table-Level)


  • Can reference one or more columns


🔹 Syntax (Using ALTER TABLE)


  • Adds a CHECK constraint to an existing table


🔹 Example 1: Column-Level CHECK


  • Ensures marks are between 0 and 100


🔹 Example 2: Table-Level CHECK


  • Ensures bonus is no more than 20% of salary


🔹 Example 3: Adding CHECK Using ALTER TABLE


  • Adds a named CHECK constraint to the marks column after table creation


🔹 Key Points

  1. CHECK enforces specific rules on column or table values.

  2. Helps maintain valid and consistent data.

  3. Can be applied during creation or added later using ALTER TABLE.

  4. Multiple CHECK constraints can exist in a table.

  5. Useful for ranges, conditions, or logical rules on data.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *