You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Primary keys use to uniquely identify the record in a table
Creating Table with Primary Key Constaints
CREATETABLEperson(
id BIGSERIALNOT NULLPRIMARY KEY, /* BIGSERIAL will increment value itself */
firstName VARCHAR(40) NOT NULL,
lastName VARCHAR(40) NOT NULL,
gender VARCHAR(6) NOT NULL,
dateOfBirth DATENOT NULL
);
Remove Primary key constraint from table
By doing so, we can add as many records with same id.
\d person;
ALTERTABLE person DROP CONSTRAINT person_pkey;
Adding Primary key constaint in a table
ALTERTABLE person ADD PRIMARY KEY (id); -- PRIMARY KEY is constraint-- it will not work, if there are any duplicated primary key value in a table, to fix this we've to remove duplicate values from table
Unique Constraint, unique value for a give column
-- Suppose we want to add unique constraint on email, so new user cannot use the same email twice in a databaseSELECT email, COUNT(*) from person GROUP BY email;
SELECT email, COUNT(*) from person GROUP BY email HAVINGCOUNT(*) >1; -- get email count which are not unique.-- Add email constraintALTERTABLE person ADD CONSTRAINT unique_email_address UNIQUE (email);
-- Now if we try to add record with existed email, will throws errorALTERTABLE person DROP CONSTRAINT unique_email_address;
Another way to add a Unique Constraint
ALTERTABLE person add UNIQUE(email); -- only difference, Postgres will create contraint name by itself
Check constraint, suppose you want to add constraint on a column for specific values, for eg. gender i.e Male and Female
-- list distinct gendersSELECT DISTINCT gender FROM person;
ALTERTABLE person ADD CONSTRAINT gender_constraint CHECK (gender IN ('Genderqueer','Bigender','Genderfluid','Male','Non-binary','Polygender','Female','Agender'));
ALTERTABLE person ADD CONSTRAINT gender_constraint CHECK (gender IN ('Male','Female'));
ALTERTABLE person ADD CONSTRAINT gender_constraint CHECK (gender ='Male'OR gender ='Female');
-- drop constraintALTERTABLE person DROP CONSTRAINT gender_constraint;