SQL Constraints: Using Create Command
SQL Constraints: Using Create Command
SQL Constraints: Using Create Command
Constraints are the rules enforced on the data columns of a 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.
Using Create command: When a table is created with the CREATE TABLE
statement we can specify constraints. Constraints could be either on a 1. Column level or
2. Table level
Column level : Constraints can be specified at the time of column definition. Column-
level constraints refer to a single column in the table and do not specify a column name
(except check constraints). They refer to the column that they follow.
Syntax: create table table name(col1 datatype constraint constraint name constraint
type,
Table level: Table-level constraints refer to one or more columns in the table. Table-
level constraints specify the names of the columns to which they apply. Table level
constraints are applied to the whole table
Using Alter command: We can use the ALTER TABLE statement to add
constraints even after the table is created.
Syntax:
Alter table table name add constraint constraint name constraint type(column
name);
Following are some of the most commonly used constraints available in SQL.
NOT NULL Constraint − Ensures that a column cannot have a NULL value.
DEFAULT Constraint − Provides a default value for a column when none is specified.
FOREIGN Key − Uniquely identifies a row/record in any of the given database table.
CHECK Constraint − The CHECK constraint ensures that all the values in a column
satisfies certain conditions.
INDEX − Used to create and retrieve data from the database very quickly.
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.
If a table has a primary key defined on any field(s), then you cannot have two records
having the same value of that field(s)
Unique Constraint:
The UNIQUE constraint ensures that all values in a column are different. Both the
UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE
constraint..We can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the
PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table containing the
candidate key is called the referenced or parent table.
The default value will be added to all new records IF no other value is specified.
Syntax:
Dropping Constraints
Any constraint that you have defined can be dropped using the ALTER TABLE
command with the DROP CONSTRAINT option