Constraints:
->Constraints are the rules enforced on data columns on table.
-> These are used to prevent invalid data from being entered into the database. This ensures the accuracy and reliability of the data in the database.
->Constraints could be column level or table level.
-> Column level constraints are applied only to one column whereas table level constraints are applied to the whole table.
Primary Key:
A primary key is a column or a group of columns that is used to identify a row uniquely in a table.
Syntax:
ALTER TABLE TABLE_NAME ADD PRIMARY KEY (column_1, column_2);
Eg:
Alter table Employee add primary key(emp_id);
-> If we want a column in a table as primary key and we want the field is auto-incremented by 1 then
Syntax:
ALTER TABLE vendors ADD COLUMN ID SERIAL PRIMARY KEY;
Drop Primary Key:
ALTER TABLE TABLE_NAME DROP CONSTRAINT primary_key_constraint_name;
-> To get the name of the primary key available in a table
select constraint_name from information_schema.table_constraints where table_name = ‘attribute’ and constraint_type = ‘PRIMARY KEY’;
-> If we do not specify any name to the contraint by default the name will be tanle_name_pkey
Foreign Key:
A foreign key constraint specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table.
Syntax:
ALTER TABLE manager ADD CONSTRAINT fkey_constraint FOREIGN KEY (user_id) REFERENCES users (uid) ON DELETE CASCADE;
-> Here the user_id column of of manager table is referencing the uid column of users table.
-> Before any modification in the uid column of the user table we must modify the user_id column of the manager table.
NOT NULL:
Syntax:
ALTER TABLE table_name ALTER COLUMN column_name SET NOT NULL;
Note: Before adding not null constraint to the alredy existing table make sure to update the existing data in the column to be not null.
Default:
-> To set a value by default this constraint should be used.
Syntax:
Alter Table Table_name alter column_name set DEFAULT ‘TC’::character varying;
Eg:
ALTER TABLE ONLY service ALTER COLUMN service_type SET DEFAULT ‘DATA’;
Unique:
-> It is used to make sure that every row in the column must have an unique value.
Syntax:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, … column_n);
Eg:
ADD CONSTRAINT unique_key UNIQUE (name,type,description);
Drop Unique :
ALTER TABLE attribute drop CONSTRAINT unique_key;