Constraints
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 accepted
INSERT INTO table_nn ( tag ) VALUES (NULL);
-- empty string aren't NULL values
INSERT 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 added
UPDATE table_nn
SET is_enable = '' WHERE is_enable IS NULL;
-- adding null constraint on table
ALTER TABLE public.table_nn
ALTER COLUMN is_enable SET NOT NULL;UNIQUE
Adding Unique Constraint on column
DEFAULT CONSTRAINT
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
as composite key.
Composite Primary Key
Foreign Key
CHECK Constraint
Example
Last updated
Was this helpful?