×
>
<

DBMS

DBMS Constraint Check | CrackEase

Check in DBMS

Check

  • Use a CHECK constraint when you want to ensure a column (or combination of columns) contains only values that satisfy a condition. For example, to allow access only if the age entered is at least 18 you would use a check constraint.
  • Check constraints validate data at the time of INSERT or UPDATE, and will prevent changes that violate the condition.

Syntax for CHECK constraint

Syntax

  
CREATE TABLE STUDENT (
     column1 datatype(size),
     column2 datatype(size),
     column3 datatype(size),
     CHECK (condition)
);
  
Example
  
CREATE TABLE STUDENT (
    ID int,
    Name varchar(255),
    Age int,
    CHECK (Age >= 18)
);
  

  • In the example above the check (Age >= 18) enforces that only values 18 or greater are accepted for the Age column.
  • If a user tries to insert Age = 16, the DBMS will return an error and the insert will fail.

Check constraint at table level (multiple columns)
Example
  
CREATE TABLE student (
   ID int,
   Name varchar(255),
   Age int,
   City varchar(255),
   CONSTRAINT CHK_Person CHECK (Age >= 18 AND City = 'Hyderabad')
);
  

  • You can apply a check constraint that references more than one column (table-level constraint). In the example above, both conditions must be true: Age >= 18 and City = 'Hyderabad'.
  • Rows failing either condition will be rejected.

Primary Key VS Unique Key
Primary Key

  • Uniquely identifies a record in a table.
  • Does not allow NULL values.
  • Often implemented by a clustered index (DBMS-dependent).
  • Only one primary key is allowed per table (but it can be a composite key made of multiple columns).

Unique Key

  • Ensures values in the specified column(s) are unique across the table.
  • Can allow NULL values (rules vary slightly by RDBMS).
  • Implemented by a non-clustered index typically.
  • Multiple unique keys can be defined on a table.

Footer Content | CrackEase