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, whereas table level constraints are
applied to the whole table.
Following are commonly used constraints available in SQL. These
constraints have already been discussed in SQL - RDBMS Concepts chapter but its worth to revise them at this point.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
The DEFAULT constraint can also
be used to insert system values, by using functions like GETDATE():
CREATE TABLE Orders (
ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);
·
CHECK Constraint: The
CHECK constraint ensures that all values in a column satisfy certain
conditions.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK
(Age>=18));
Constraints can be
specified when a table is created with the CREATE TABLE statement or you can
use ALTER TABLE statement to create constraints even after the table is
created.
Dropping Constraints:
Any constraint that you have
defined can be dropped using the ALTER TABLE command with the DROP CONSTRAINT
option.
For example, to drop the
primary key constraint in the EMPLOYEES table, you can use the following
command:
ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK;
Some implementations may
provide shortcuts for dropping certain constraints. For example, to drop the
primary key constraint for a table in Oracle, you can use the following
command:
ALTER TABLE EMPLOYEES DROP PRIMARY KEY;
Some implementations allow you
to disable constraints. Instead of permanently dropping a constraint from the
database, you may want to temporarily disable the constraint and then enable it
later.
Integrity Constraints:
Integrity constraints are used
to ensure accuracy and consistency of data in a relational database. Data
integrity is handled in a relational database through the concept of
referential integrity.
There are many types of
integrity constraints that play a role in referential integrity (RI). These
constraints include Primary Key, Foreign Key, Unique Constraints and other
constraints mentioned above.
No comments:
Post a Comment