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.

How To Use Check In Sql in SQL

How To Use Check In Sql in SQL

How to Use CHECK Constraint in SQL

The CHECK constraint is used to limit the values that can be placed in a column. It ensures that all values in a column satisfy a specific condition.


Syntax:

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

Or add a check constraint to an existing table:

ALTER TABLE table_nameADD CONSTRAINT constraint_name CHECK (condition);

Example 1: Create Table with CHECK

CREATE TABLE employees (    employee_id INT PRIMARY KEY,    age INT CHECK (age >= 18),         -- age must be 18 or older    salary DECIMAL(10, 2) CHECK (salary > 0)  -- salary must be positive);

Example 2: Add CHECK Constraint to Existing Table

ALTER TABLE employeesADD CONSTRAINT chk_salary_positive CHECK (salary > 0);

Notes:

  • The CHECK condition can use comparison operators (=, <, >, <=, >=, <>), logical operators (AND, OR, NOT), and more.

  • When you try to insert or update a value violating the check, the database throws an error.

  • Not all database engines enforce CHECK constraints strictly (e.g., older MySQL versions ignore them).


If you want, I can help you write a CHECK constraint for your specific table!

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