SQL Constraints
Introduction To SQL Constraints
Introduction:
In this article, you will learn what SQL constraints are.
SQL constraints states are used to limit the data that can go into a table. Constraints are used to make sure that the integrity of the data is in control in the database. It can be divided into following two types.
- Column level constraints
- Table level constraints
Column level constraints – These constraints are performed only to a single column.
Table-level constraints - These constraints are performed to the complete table.
Following are the most used constraints, which can be applied to a table-
NOT NULL Constraint:
This constraint fulfills a field to regularly store a value. This means that you cannot add a new data or update the data without adding a value.
DEFAULT Constraint:
Default constraints are a unique case of the column defaults. A column default is some value or function, which the column will take when an INSERT statement doesn't explicitly assign a particular value.
UNIQUE Constraint:
Unique constraint uniquely identifies, which means all the values in a column are different. Like a primary key, unique key provides a security for the uniqueness of a column or a set of columns. A primary key constraint naturally has a unique constraint characterized on it.
Primary Key:
Primary keys must store the unique values. Thus, this constraint defines a column or a collection of columns, which uniquely describes each row in the table. This column cannot accept null values. Many tables should have a primary key and each table can have only one primary key.
FOREIGN Key:
A foreign key is a column or bunch of columns in a database table, whose values match a Primary Key in a different table.
CHECK Constraint:
This constraint implements a condition to check the value being inserted into a record. If the statement composes to false, the record disobeys the constraint and isn't recorded into the table. You can generate this constraint with any logical language, which gives 0 or 1, based on the logical operators.
INDEX:
An index is a set of the ordered references to the rows of a table. It can contain the data from one or more columns of a table. An index upgrades the performance of the data retrieval by decreasing the number of the physical pages, which the database must enter in order to read a row in the database. Every index has a header, which contains the following information:
- The depth of the index.
- Number of the leaf pages.
- The selectivity factor.
Summary:
Thus, we learned that SQL constraints are used to limit the data, which are stored in the database.