Friday 11 November 2016

SQL Constraints

Constraints

- Constraints are the rules enforced on data columns on table. 
- These are used to limit the type of data that can go into a table. 
- 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 where as table level constraints are applied to the whole table.

NOT NULL Constraint


-  It will ensures that a column cannot have NULL value.

By default, a column can hold NULL values. If you do not want a column to have a NULL value, then you need to define such constraint on this column specifying that NULL is now not allowed for that column.








DEFAULT Constraint


  It will provide a default value for a column when the INSERT INTO statement does not provide a specific value.



Here, SALARY column is set to 5000.00 by default, so in case INSERT INTO statement does not provide a value for this column, then by default this column would be set to 5000.00.




UNIQUE Constraint



It will prevent two records from having identical values in a particular column.


 Here, ID column is set to UNIQUE, so that you can not have two records with same ID.



Primary Key Constraint


- Primary keys must contain unique values. 
- A primary key column cannot have NULL values.
- A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key.




Foreign Key Constraint


- A foreign key is a key used to link two tables together. This is sometimes called a referencing key.
- Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table.
The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in the second table.





If ORDERS table has already been created, and the foreign key has not yet been set, use the syntax for specifying a foreign key by altering a table.





CHECK Constraint



The CHECK Constraint enables a condition to check the value being entered into a record. If the condition evaluates to false, the record violates the constraint and isn't entered into the table.

Example:

For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here, we add a CHECK with AGE column, so that you can not have any CUSTOMER below 18 years:









            Thanks for taking your valuable time to read my blog.! - Syed Sadiq Ali



















No comments: