ADVERTISEMENT

SQL CHECK

The CHECK constraint ensures that the values in a column meet a specific condition before being inserted or updated. It’s used to enforce domain-level integrity.

🔹 Basic Syntax

-- Add CHECK during table creation
CREATE TABLE employees (
  employee_id INT PRIMARY KEY,
  age INT,
  salary DECIMAL(10,2),
  CHECK (age >= 18 AND salary >= 10000)
);

-- Add CHECK to an existing table
ALTER TABLE employees
ADD CONSTRAINT chk_salary CHECK (salary >= 10000);

🔹 Example

CREATE TABLE students (
  student_id INT PRIMARY KEY,
  grade INT CHECK (grade BETWEEN 1 AND 12)
);

✅ Only allows grade values from 1 to 12.

🔹 Important Notes

  • Can apply to a single column or multiple columns.
  • Violations will throw an error during INSERT or UPDATE.
  • Named constraints improve clarity and maintenance.
  • Some DBMS (like older MySQL versions) may ignore CHECK by default unless in strict mode.

🧠 Quick Recap

Key PointExplanation
PurposeEnforce rules/conditions on column values
ScopeSingle or multiple columns
When EnforcedOn INSERT and UPDATE operations
Syntax TipUse CHECK (condition) inside or after table
DBMS CaveatMySQL may ignore unless in strict mode

💡 Use CHECK constraints to make sure your data stays within expected boundaries and is logically valid.

ADVERTISEMENT