Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Check Constraint In Sql in SQL

Check Constraint In Sql in SQL

? CHECK Constraint in SQL

The CHECK constraint is used to limit the values that can be placed in a column by specifying a Boolean expression. If the expression evaluates to FALSE or UNKNOWN, the data modification (INSERT or UPDATE) is rejected.


? Syntax

1. Adding CHECK constraint when creating a table

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

2. Adding CHECK constraint to an existing table

ALTER TABLE table_nameADD CONSTRAINT constraint_name CHECK (condition);

? Examples

1. Creating a table with CHECK constraint

CREATE TABLE employees (    emp_id INT PRIMARY KEY,    emp_name VARCHAR(100),    age INT,    CONSTRAINT chk_age CHECK (age >= 18 AND age <= 65));
  • Ensures age is between 18 and 65.


2. Adding CHECK constraint to existing table

ALTER TABLE employeesADD CONSTRAINT chk_salary CHECK (salary > 0);
  • Ensures salary is always positive.


? Key Points

  • CHECK constraints enforce data integrity at the column or table level.

  • Supported in most SQL databases like MySQL (since 8.0.16), PostgreSQL, SQL Server, Oracle.

  • The condition must be a Boolean expression.

  • If violated, the operation fails with an error.


Want examples with multiple columns or removing CHECK constraints?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql