top of page

SQL Constraints

While creating tables we have to pass the constraints of the table. SQL Constraints are certain rules and limitation that we apply on the table.

Constraints
Explanation
DEFAULT
Default is use to give default value to a column if no value is passed to that column,
NOT NULL
It make sure that their are no null values present in that particular column.
UNIQUE
It make sure that all the records in a table our unique an doesn't allow duplicate values.
PRIMARY KEY
It is combination of not null constraints and unique constraints and it is use as a primary column of a table from which records can be access.
FOREIGN KEY
It is use to connect two tables and act as a reference and stop the column to delete the connection between tables.
CHECK
It is use to check and apply certain condition on a column or table.

Default Constraints

Default constraints are use to give the default values to a column.

EXAMPLE 

CREATE TABLE Customers (
    Customer_ID int,
    first_name char(20),
    last_name char(20),
    phone_number int,
   number_of_products int DEFAULT 0
);

NOT NULL Constraints

Not Null constraints is use to make sure there are no null values present in a column.

EXAMPLE 

CREATE TABLE Customers (
    Customer_ID int NOT NULL,
    first_name char(20),
    last_name char(20),
    phone_number int,
   number_of_products int
);

UNIQUE Constraints

Unique constraints are use to make sure all the values in a column are unique.

EXAMPLE 

CREATE TABLE Customers (
    Customer_ID int,
    first_name char(20),
    last_name char(20),
    phone_number int UNIQUE,
   number_of_products int
);

CHECK Constraints

Unique constraints are use to make sure all the values in a column are unique.

EXAMPLE 

CREATE TABLE Customers (
    Customer_ID int,
    first_name char(20),
    last_name char(20),
    Age int,
    phone_number int,
   number_of_products int,
   CHECK (age > 18)
);

PRIMARY KEY Constraints

PRIMARY KEY Constraints is a combination of not null and unique constraint. It is use to give the unique identification to the records.

EXAMPLE 

CREATE TABLE Customers (
    Customer_ID int PRIMARY KEY,
    first_name char(20),
    last_name char(20),
    phone_number int UNIQUE,
   number_of_products int
);

FOREIGN KEY Constraints

Foreign key constraint is use to build the relationship between two tables and we reference it to the primary key of other table.

Name of the referenced column and referencing column could be different but data type must be same.

EXAMPLE 

CREATE TABLE Purchases (
    Purchases_number int,
    Purchase_date Date,
    Customer_id int,
    Product_code char(20),
    FOREIGN KEY (Customer_id) REFERENCES Customers(customer_id)
);
bottom of page