Wednesday, April 19, 2017

Constraints in SQL Database

Today we will learn what are constraints in SQL. in our daily routine work we are using many constraints but in actual we don't know what are constrains. basically constraints are rules, such rules which are enforced on data column of a table. we can apply a constraint on a table or a column. these are used to check the accuracy of data and reliability of data in any circumstances.
So, let's have a look on constraints one by one which are mostly used in SQL.
NOT NULL Constraint − will make sure this column cannot be NULL.
For example we have a PRODUCTS table and we want to add NOT NULL constraint on PRICE Column:
ALTER TABLE PRODUCTS 
       MODIFY PRICE DECIMAL (18, 2) NOT NULL;


DEFAULT Constraint − it will set Default value for a column if none is given.
how to add Default Constraints:
ALTER TABLE PRODUCTS 
        MODIFY PRICE DECIMAL (18, 2) DEFAULT 10.00; 

To DROP a default Constraint we will use this query other than normal DROP constraint query:
ALTER TABLE PRODUCTS 
   ALTER COLUMN PRICE DROP DEFAULT;


UNIQUE Constraint − this will check Column Values are unique.
How to Add Unique Constraint:
ALTER TABLE PRODUCTS 
   MODIFY QTY INT NOT NULL UNIQUE;


PRIMARY Key − it will set unique identity for each row/record.
How to add:
ALTER TABLE PRODUCTS 
   ADD CONSTRAINT PK_PRODTID PRIMARY KEY (PROD_ID, PRODUCT_NAME);


FOREIGN Key − it will also Uniquely identifies a row/record for any given database table.
How to add:
ALTER TABLE ORDERS 
   ADD FOREIGN KEY ((PRODUCT_ID) REFERENCES PRODUCTS (PROD_ID);


CHECK Constraint − it used to check that all values of column are according to a specific condition.
How to Add:
ALTER TABLE PRODUCTS
   MODIFY QTY INT NOT NULL CHECK (QTY >= 2);


INDEX − Basically Indexes are used to retreive data from a table quickly.
How to Create Index:
CREATE INDEX idx_price
   ON PRODUCTS (PRICE);


Constraints can also be added while creating a table with CREATE TABLE Statement otherwise you can set later with ALTER TABLE statement.

Dropping Constraints:
We can also remove a constraint by using below query:
For example, to drop the primary key constraint in the PRODUCTS table, you can use the following command.
ALTER TABLE PRODUCTS DROP CONSTRAINT PK_PRODTID;

Comments and Suggestions are always Welcome!

No comments:

Post a Comment