0% found this document useful (0 votes)
20 views

SQL Constraints

Uploaded by

santoshdvg1997
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

SQL Constraints

Uploaded by

santoshdvg1997
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

SQL

Topperworld.in

Constraints

Constraints are the rules that we can apply on the type of data in a table. That
is, we can specify the limit on the type of data that can be stored in a particular
column in a table using constraints.

The available constraints in SQL are:

➢ NOT NULL: This constraint tells that we cannot store a null value in a
column. That is, if a column is specified as NOT NULL then we will not be
able to store null in this particular column any more.
➢ UNIQUE: This constraint when specified with a column, tells that all the
values in the column must be unique. That is, the values in any row of a
column must not be repeated.
➢ PRIMARY KEY: A primary key is a field which can uniquely identify each row
in a table. And this constraint is used to specify a field in a table as primary
key.
➢ FOREIGN KEY: A Foreign key is a field which can uniquely identify each row
in a another table. And this constraint is used to specify a field as Foreign
key.
➢ CHECK: This constraint helps to validate the values of a column to meet a
particular condition. That is, it helps to ensure that the value stored in a
column meets a specific condition.
➢ DEFAULT: This constraint specifies a default value for the column when no
value is specified by the user.

©Topperworld
SQL

❖ How to specify constraints?

We can specify constraints at the time of creating the table using CREATE
TABLE statement.

We can also specify the constraints after creating a table using ALTER TABLE
statement.

Syntax:
Below is the syntax to create constraints using CREATE TABLE statement at the
time of creating the table.

CREATE TABLE sample_table

column1 data_type(size) constraint_name,

column2 data_type(size) constraint_name,

column3 data_type(size) constraint_name,

....

);

sample_table: Name of the table to be created.

data_type: Type of data that can be stored in the field.

constraint_name: Name of the constraint.

Let us see each of the constraint in detail.

1. NOT NULL –

©Topperworld
SQL

If we specify a field in a table to be NOT NULL. Then the field will never accept
null value. That is, you will be not allowed to insert a new row in the table
without specifying any value to this field.
For example, the below query creates a table Student with the fields ID and
NAME as NOT NULL. That is, we are bound to specify values for these two fields
every time we wish to insert a new row.

CREATE TABLE table_Name

column1 data_type(size) NOT NULL,

column2 data_type(size) NOT NULL,

);

➢ SQL NOT NULL on CREATE a Table


In SQL, we can add NOT NULL constraints while creating a table.

For example, the “EMPID” will not accept NULL values when the EMPLOYEES
table is created because NOT NULL constraints are used with these columns.

Query:

CREATE TABLE Emp(

EmpID INT NOT NULL PRIMARY KEY,

Name VARCHAR (50),

Country VARCHAR(50),

Age int(2),

Salary int(10));

©Topperworld
SQL

Output:

2. UNIQUE –
This constraint helps to uniquely identify each row in the table. i.e. for a
particular column, all the rows should have unique values.

We can have more than one UNIQUE columns in a table.


For example, the below query creates a table Student where the field ID is
specified as UNIQUE. i.e, no two students can have the same ID.

➢ Important Points:

⚫ Evaluates to true on an empty subquery.


⚫ Returns true only if there are unique tuples present as the output of the
sub-query (two tuples are unique if the value of any attribute of the two
tuples differs).
⚫ Returns true if the sub-query has two duplicate rows with at least one
attribute as NULL.

CREATE TABLE table_name(


column1 datatype UNIQUE,
Column2 datatype,

);

©Topperworld
SQL

Example

Find all the courses in the Computer Science department that has only a single
instructor allotted to that course.

CourseID Name Department InstructorID

CSE505 Computer Network Computer Science 11071

CSE245 Operating System Computer Science 74505

CSE101 Programming Computer Science 12715

HSS505 Psychology Social Science 85017

EE475 Signals & Systems Electrical 22150

CSE314 DBMS Computer Science 44704

CSE505 Computer Network Computer Science 11747

CSE314 DBMS Computer Science 44715

©Topperworld
SQL

Without UNIQUE Constraint

Query:

SELECT C.COURSEID, C.NAME

FROM Course as C

WHERE UNIQUE (SELECT T.INSTRUCTORID

FROM Course as T

WHERE T.COURSEID = C.COURSEID

and C.DEPARTMENT = 'Computer Science');

By using UNIQUE Constraint

Query:

SELECT CourseID

FROM Instructor

WHERE CourseID LIKE 'CSE%'

GROUP BY CourseID

HAVING COUNT(DISTINCT Name) = 1;

COURSE_ID Name
Output:
CSE245 Operating System

CSE101 Programming

©Topperworld
SQL

3. PRIMARY KEY –
Primary Key is a field which uniquely identifies each row in the table.

If a field in a table as primary key, then the field will not be able to contain
NULL values as well as all the rows should have unique values for this field.

So, in other words we can say that this is combination of NOT NULL and
UNIQUE constraints.
A table can have only one field as primary key. Below query will create a table
named Student and specifies the field ID as primary key.

CREATE TABLE Student

ID int(6) NOT NULL UNIQUE,

NAME varchar(10),

ADDRESS varchar(20),

PRIMARY KEY(ID)

);

A primary key constraint depicts a key comprising one or more columns that
will help uniquely identify every tuple/record in a table.

Properties :

• No duplicate values are allowed, i.e. Column assigned as primary key


should have UNIQUE values only.
• NO NULL values are present in column with Primary key. Hence there
is Mandatory value in column having Primary key.

©Topperworld
SQL

• Only one primary key per table exist although Primary key may have
multiple columns.
• No new row can be inserted with the already existing primary key.
• Classified as : a) Simple primary key that has a Single column 2)
Composite primary key has Multiple column.
• Defined in Create table / Alter table statement.

The primary key can be created in a table using PRIMARY KEY constraint. It can
be created at two levels.

a) Column
b) Table.

➢ SQL PRIMARY KEY at Column Level :


If Primary key contains just one column, it should be defined at column
level.

The following code creates the Primary key “ID” on the person table.

Syntax :

Create Table Person

Id int NOT NULL PRIMARY KEY,

Name varchar2(20),

Address varchar2(50)

);

©Topperworld
SQL

Example:
To verify the working of Primary key :

Insert into Person values(1, 'Ajay', 'Mumbai');

Output :
1 row created

➢ SQL PRIMARY KEY at Table Level :

Whenever the primary key contains multiple columns it has to be specified at


Table level.

Syntax:

Create Table Person

(Id int NOT NULL,

Name varchar2(20),

Address varchar2(50),

PRIMARY KEY(Id, Name)

);

©Topperworld
SQL

4. FOREIGN KEY –
Foreign Key is a field in a table which uniquely identifies each row of a another
table.

That is, this field points to primary key of another table. This usually creates a
kind of link between the tables.

Consider the two tables as shown below:

Orders

O_ID ORDER_NO C_ID

1 2253 3

2 3325 3

3 4521 2

4 8532 1

Customers

C_ID NAME ADDRESS

1 RAMESH DELHI

2 SURESH NOIDA

3 DHARMESH GURGAON

As we can see clearly that the field C_ID in Orders table is the primary
key in Customers table, i.e. it uniquely identifies each row in the
Customers table. Therefore, it is a Foreign Key in Orders table.

©Topperworld
SQL

Syntax:
CREATE TABLE Orders

O_ID int NOT NULL,

ORDER_NO int NOT NULL,

C_ID int,

PRIMARY KEY (O_ID),

FOREIGN KEY (C_ID) REFERENCES Customers(C_ID)

5. CHECK-
Using the CHECK constraint we can specify a condition for a field, which should
be satisfied at the time of entering values for this field.
For example, the below query creates a table Student and specifies the
condition for the field AGE as (AGE >= 18 ). That is, the user will not be allowed
to enter any record in the table with AGE < 18.

CREATE TABLE Student

ID int(6) NOT NULL,

NAME varchar(10) NOT NULL,

AGE int NOT NULL CHECK (AGE >= 18)

);

©Topperworld
SQL

6.DEFAULT –
This constraint is used to provide a default value for the fields.

That is, if at the time of entering new records in the table if the user does not
specify any value for these fields then the default value will be assigned to
them.

Syntax:
CREATE TABLE tablename (Columnname DEFAULT ‘defaultvalue’ );

©Topperworld

You might also like