Constraints are like Gate Keepers. Control the type of data that goes into the table. These are used to prevent invalid data.
Constraints can be added on
Table
Column
Types of Constraints
Type
Note
NOT NULL
Field must have values
UNIQUE
Only unique value are allowed
DEFAULT
Ability to SET default
PRIMARY KEY
Uniquely identifies each row/record
FOREIGN KEY
Constraint based on Column in other table
CHECK
Check all values must meet specific criteria
NOT NULL
CREATETABLEtable_nn ( id SERIALPRIMARY KEY, tag textNOT NULL);INSERT INTO table_nn ( tag ) VALUES ('TAG 1'), ('TAG 2'), ('TAG 3'), ('');-- NULL value wont be acceptedINSERT INTO table_nn ( tag ) VALUES (NULL);-- empty string aren't NULL valuesINSERT INTO table_nn ( tag ) VALUES ('');-- adding another column TEXT;ALTERTABLE table_nn ADD COLUMN is_enable TEXT;-- Updating values in new column to '' -- so that NULL constrain can be addedUPDATE table_nnSET is_enable =''WHERE is_enable ISNULL;-- adding null constraint on tableALTERTABLE public.table_nnALTER COLUMN is_enable SETNOT NULL;
UNIQUE
CREATETABLEtable_unique ( id SERIALPRIMARY KEY, emails TEXTUNIQUE);INSERT INTO table_unique ( emailS ) VALUES ('A@B.COM'),('C@D.COM');INSERT INTO table_unique ( emailS ) VALUES ('A@B.COM');-- error
CREATETABLEtable_default ( id SERIALPRIMARY KEY, is_enable TEXTDEFAULT'Y');INSERT INTO table_default ( id ) VALUES (1),(2);select*from table_default; id | is_enable ----+-----------1 | Y2 | YALTERTABLE public.table_defaultADD COLUMN tag text;ALTERTABLE public.table_defaultALTER COLUMN tag SETDEFAULT'N';INSERT INTO table_default ( id ) VALUES (5);select*from table_default; id | is_enable | tag ----+-----------+-----1 | Y | 2 | Y | 5 | Y | NALTERTABLE public.table_defaultALTER COLUMN tag DROPDEFAULT;Table"public.table_default" Column | Type | Collation | Nullable | Default-----------+---------+-----------+----------+------------------------------------------- id | integer | | not null | nextval('table_default_id_seq'::regclass) is_enable | text | | | 'Y'::text tag | text | | | Indexes:"table_default_pkey"PRIMARY KEY, btree (id)
Primary Key
Uniquely identifies each record in a database table
There can be more than one UNIQUE, but only one primary key
A primary key is a field in a table, which uniquely identifies each row/column in a database table
When multiple fields are used as a primary key, which may consist of single or multiple fields, also known