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
CREATE TABLE table_nn ( id SERIAL PRIMARY KEY, tag text NOT 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;ALTER TABLE 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 IS NULL;-- adding null constraint on tableALTER TABLE public.table_nn ALTER COLUMN is_enable SET NOT NULL;
UNIQUE
CREATE TABLE table_unique ( id SERIAL PRIMARY KEY, emails TEXT UNIQUE);INSERT INTO table_unique ( emailS ) VALUES ('A@B.COM'),('C@D.COM');INSERT INTO table_unique ( emailS ) VALUES ('A@B.COM');-- error
CREATE TABLE table_default ( id SERIAL PRIMARY KEY, is_enable TEXT DEFAULT 'Y');INSERT INTO table_default ( id ) VALUES (1),(2);select*from table_default; id | is_enable ----+-----------1 | Y2 | YALTER TABLE public.table_default ADD COLUMN tag text;ALTER TABLE public.table_default ALTER COLUMN tag SET DEFAULT 'N';INSERT INTO table_default ( id ) VALUES (5);select*from table_default; id | is_enable | tag ----+-----------+-----1 | Y | 2 | Y | 5 | Y | NALTER TABLE public.table_default ALTER COLUMN tag DROP DEFAULT;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