SQL Constraints

From NovaOrdis Knowledge Base
Revision as of 22:34, 23 May 2024 by Ovidiu (talk | contribs) (→‎Foreign Key Constraint)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Internal

Overview

NOT NULL Constraint

CREATE TABLE ...
( ...
  somecolumn varchar(30) NOT NULL, 
  ...
);

Also see:

NULL

Primary Key Constraint

Primary Key
CREATE TABLE ...
( ...
  CONSTRAINT pk_someconstraint PRIMARY KEY (somecolumn)
);

The primary key constraint can also be added after table creation with ALTER TABLE.

Foreign Key Constraint

A foreign key constraint can be created to verify that the values in one table exist in another table.

Foreign Key
CREATE TABLE ...
( ...
  CONSTRAINT fk_someconstraint FOREIGN KEY (somecolumn)
);

The foreign key constraint can also be added after table creation with ALTER TABLE.

Check Constraint

CREATE TABLE ...
( ...
  eye_color CHAR(2) CHECK (eye_color IN ('BR', 'BL', 'GR')),
  ...
);