β SQL CHECK β Enforce Column Rules and Data Validations
π§² Introduction β What is SQL CHECK?
The CHECK constraint in SQL is used to enforce custom conditions on column values. It helps maintain data quality by restricting the range, pattern, or logic of what can be inserted or updated in a column.
π― In this guide, you’ll learn:
- Syntax of the
CHECKconstraint - Common use cases and expressions
- Best practices and DBMS behavior notes
β 1. Basic CHECK Syntax
CREATE TABLE employees (
id INT PRIMARY KEY,
age INT CHECK (age >= 18),
salary DECIMAL(10,2) CHECK (salary > 0)
);
β Ensures age is at least 18 and salary is positive.
π§± 2. Named CHECK Constraints
CREATE TABLE products (
price DECIMAL(10,2),
CONSTRAINT chk_price_positive CHECK (price > 0)
);
β Naming helps in debugging and maintaining constraints.
π 3. Add CHECK to Existing Table
ALTER TABLE orders
ADD CONSTRAINT chk_total_positive
CHECK (total_amount >= 0);
β Adds validation rule after table creation.
π§ 4. Complex CHECK Conditions
CREATE TABLE students (
grade CHAR(1) CHECK (grade IN ('A', 'B', 'C', 'D', 'F'))
);
β Restricts values to a predefined set.
CHECK (discount <= price)
β Enforces a rule across multiple columns.
β οΈ 5. CHECK Limitations & Notes
- CHECK constraints evaluate row-by-row, not across rows
- Not supported in some older MySQL versions (prior to 8.0)
- Cannot reference values from other tables (use triggers instead)
- Violations raise an error and reject the statement
π Best Practices
| β Recommended | β Avoid This |
|---|---|
| Use for domain rules and logical bounds | Putting business logic into applications only |
| Name constraints clearly | Allowing silent errors without constraint |
Combine with NOT NULL, DEFAULT | Writing overly complex expressions |
π Summary β Recap & Next Steps
CHECK constraints help enforce domain-specific business rules at the database level. Theyβre simple to define and provide strong data quality assurance.
π Key Takeaways:
- Use
CHECKto restrict allowed column values - Works best with numeric ranges, sets, and logical expressions
- Combine with other constraints like
NOT NULLandUNIQUE
βοΈ Real-World Relevance:
Used in billing, validation of form data, gradebooks, pricing systems, and regulated data systems.
β FAQ β SQL CHECK
β What does the CHECK constraint do?
β It restricts column values based on a logical condition.
β Can I use CHECK on multiple columns?
β Yes. You can create expressions involving multiple columns.
β What happens if a CHECK fails?
β The statement is aborted, and the error is returned.
β Is CHECK supported in all databases?
β Most modern SQL engines support it. MySQL did not fully support it before version 8.0.
Share Now :
