0% found this document useful (0 votes)
119 views75 pages

Unit 2

The document discusses the relational model in database management systems (DBMS). The relational model represents data stored in relational databases as tables (relations) with rows (tuples) and columns (attributes). It defines key concepts like attributes, tuples, domains, relations, and introduces basic constraints like domain constraints and key integrity. The document also discusses anomalies that can occur with relations and how operations like joins, unions, differences work between relations in relational algebra.

Uploaded by

Raj Jaiswal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
119 views75 pages

Unit 2

The document discusses the relational model in database management systems (DBMS). The relational model represents data stored in relational databases as tables (relations) with rows (tuples) and columns (attributes). It defines key concepts like attributes, tuples, domains, relations, and introduces basic constraints like domain constraints and key integrity. The document also discusses anomalies that can occur with relations and how operations like joins, unions, differences work between relations in relational algebra.

Uploaded by

Raj Jaiswal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Relational Model in DBMS

Relational Model was proposed by E.F. Codd to model data in the form of
relations or tables. After designing the conceptual model of Database using
ER diagram, we need to convert the conceptual model in the relational model
which can be implemented using any RDBMS languages like Oracle SQL,
MySQL etc. So we will see what Relational Model is.
What is Relational Model?
Relational Model represents how data is stored in Relational Databases. A
relational database stores data in the form of relations (tables). Consider a
relation STUDENT with attributes ROLL_NO, NAME, ADDRESS, PHONE
and AGE shown in Table 1.

STUDENT
ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 18

IMPORTANT TERMINOLOGIES
• Attribute: Attributes are the properties that define a relation.
e.g.; ROLL_NO, NAME
• Relation Schema: A relation schema represents name of the
relation with its attributes. e.g.; STUDENT (ROLL_NO, NAME,
ADDRESS, PHONE and AGE) is relation schema for STUDENT. If
a schema has more than 1 relation, it is called Relational Schema.
• Tuple: Each row in the relation is known as tuple. The above
relation contains 4 tuples, one of which is shown as:
1 RAM DELHI 9455123451 18

• Relation Instance: The set of tuples of a relation at a particular


instance of time is called as relation instance. Table 1 shows the
relation instance of STUDENT at a particular time. It can change
whenever there is insertion, deletion or updation in the database.
• Degree: The number of attributes in the relation is known as
degree of the relation. The STUDENT relation defined above has
degree 5.
• Cardinality: The number of tuples in a relation is known as
cardinality. The STUDENT relation defined above has cardinality 4.
• Column: Column represents the set of values for a particular
attribute. The column ROLL_NO is extracted from relation
STUDENT.
ROLL_NO

• NULL Values: The value which is not known or unavailable is


called NULL value. It is represented by blank space. e.g.; PHONE
of STUDENT having ROLL_NO 4 is NULL.
Constraints in Relational Model
While designing Relational Model, we define some conditions which must
hold for data present in database are called Constraints. These constraints
are checked before performing any operation (insertion, deletion and
updation) in database. If there is a violation in any of constrains, operation
will fail.
Domain Constraints: These are attribute level constraints. An attribute can
only take values which lie inside the domain range. e.g,; If a constrains
AGE>0 is applied on STUDENT relation, inserting negative value of AGE will
result in failure.
Key Integrity: Every relation in the database should have atleast one set of
attributes which defines a tuple uniquely. Those set of attributes is called
key. e.g.; ROLL_NO in STUDENT is a key. No two students can have same
roll number. So a key has two properties:
• It should be unique for all tuples.
• It can’t have NULL values.
Referential Integrity: When one attribute of a relation can only take values
from other attribute of same relation or any other relation, it is called
referential integrity. Let us suppose we have 2 relations
STUDENT
ROLL_NO NAME ADDRESS PHONE AGE BRANCH_CODE

1 RAM DELHI 9455123451 18 CS

2 RAMESH GURGAON 9652431543 18 CS

3 SUJIT ROHTAK 9156253131 20 ECE

4 SURESH DELHI 18 IT

BRANCH
BRANCH_CODE BRANCH_NAME

CS COMPUTER SCIENCE

IT INFORMATION TECHNOLOGY

ECE ELECTRONICS AND COMMUNICATION ENGINEERING

CV CIVIL ENGINEERING

BRANCH_CODE of STUDENT can only take the values which are present in
BRANCH_CODE of BRANCH which is called referential integrity constraint.
The relation which is referencing to other relation is called REFERENCING
RELATION (STUDENT in this case) and the relation to which other relations
refer is called REFERENCED RELATION (BRANCH in this case).

ANOMALIES
An anomaly is an irregularity, or something which deviates from the expected
or normal state. When designing databases, we identify three types of
anomalies: Insert, Update and Delete.
Insertion Anomaly in Referencing Relation:
We can’t insert a row in REFERENCING RELATION if referencing attribute’s
value is not present in referenced attribute value. e.g.; Insertion of a student
with BRANCH_CODE ‘ME’ in STUDENT relation will result in error because
‘ME’ is not present in BRANCH_CODE of BRANCH.
Deletion/ Updation Anomaly in Referenced Relation:
We can’t delete or update a row from REFERENCED RELATION if value of
REFERENCED ATTRIBUTE is used in value of REFERENCING
ATTRIBUTE. e.g; if we try to delete tuple from BRANCH having
BRANCH_CODE ‘CS’, it will result in error because ‘CS’ is referenced by
BRANCH_CODE of STUDENT, but if we try to delete the row from BRANCH
with BRANCH_CODE CV, it will be deleted as the value is not been used by
referencing relation. It can be handled by following method:
ON DELETE CASCADE: It will delete the tuples from REFERENCING
RELATION if value used by REFERENCING ATTRIBUTE is deleted from
REFERENCED RELATION. e.g;, if we delete a row from BRANCH with
BRANCH_CODE ‘CS’, the rows in STUDENT relation with BRANCH_CODE
CS (ROLL_NO 1 and 2 in this case) will be deleted.
ON UPDATE CASCADE: It will update the REFERENCING ATTRIBUTE in
REFERENCING RELATION if attribute value used by REFERENCING
ATTRIBUTE is updated in REFERENCED RELATION. e.g;, if we update a
row from BRANCH with BRANCH_CODE ‘CS’ to ‘CSE’, the rows in
STUDENT relation with BRANCH_CODE CS (ROLL_NO 1 and 2 in this
case) will be updated with BRANCH_CODE ‘CSE’.
SUPER KEYS:
Any set of attributes that allows us to identify unique rows (tuples) in a given
relation are known as super keys. Out of these super keys we can always
choose a proper subset among these which can be used as a primary key.
Such keys are known as Candidate keys. If there is a combination of two or
more attributes which is being used as the primary key then we call it as a
Composite key.
Introduction of Relational Algebra in
DBMS
Relational Algebra is procedural query language, which takes Relation as
input and generate relation as output. Relational algebra mainly provides
theoretical foundation for relational databases and SQL.
Operators in Relational Algebra
Projection (π)
Projection is used to project required column data from a relation.

Example :
R
(A B C)
----------
1 2 4
2 2 3
3 2 3
4 3 4
π (BC)
B C
-----
2 4
2 3
3 4
Note: By Default projection removes duplicate data.

Selection (σ)
Selection is used to select required tuples of the relations.
for the above relation
σ (c>3)R
will select the tuples which have c more than 3.
Note: selection operator only selects the required tuples but does not display
them. For displaying, data projection operator is used.
For the above selected tuples, to display we need to use projection also.
π (σ (c>3)R ) will show following tuples.

A B C
-------
1 2 4
4 3 4

Union (U)
Union operation in relational algebra is same as union operation in set
theory, only constraint is for union of two relation both relation must have
same set of Attributes.

Set Difference (-)


Set Difference in relational algebra is same set difference operation as in set
theory with the constraint that both relation should have same set of
attributes.

Rename (ρ)
Rename is a unary operation used for renaming attributes of a relation.
ρ (a/b)R will rename the attribute ‘b’ of relation by ‘a’.

Cross Product (X)


Cross product between two relations let say A and B, so cross product
between A X B will results all the attributes of A followed by each attribute of
B. Each record of A will pairs with every record of B.
below is the example
A B
(Name Age Sex ) (Id Course)
------------------ -------------
Ram 14 M 1 DS
Sona 15 F 2 DBMS
kim 20 M

A X B
Name Age Sex Id Course
---------------------------------
Ram 14 M 1 DS
Ram 14 M 2 DBMS
Sona 15 F 1 DS
Sona 15 F 2 DBMS
Kim 20 M 1 DS
Kim 20 M 2 DBMS
Note: if A has ‘n’ tuples and B has ‘m’ tuples then A X B will have ‘n*m’
tuples.

Natural Join (⋈)


Natural join is a binary operator. Natural join between two or more relations
will result set of all combination of tuples where they have equal common
attribute.
Let us see below example

Emp Dep
(Name Id Dept_name ) (Dept_name Manager)
------------------------ ---------------------
A 120 IT Sale Y
B 125 HR Prod Z
C 110 Sale IT A
D 111 IT

Emp ⋈ Dep

Name Id Dept_name Manager


-------------------------------
A 120 IT A
C 110 Sale Y
D 111 IT A

Conditional Join
Conditional join works similar to natural join. In natural join, by default
condition is equal between common attribute while in conditional join we can
specify the any condition such as greater than, less than, not equal
Let us see below example
R S
(ID Sex Marks) (ID Sex Marks)
------------------ --------------------
1 F 45 10 M 20
2 F 55 11 M 22
3 F 60 12 M 59
Join between R And S with condition R.marks >= S.marks

R.ID R.Sex R.Marks S.ID S.Sex S.Marks


-----------------------------------------------
1 F 45 10 M 20
1 F 45 11 M 22
2 F 55 10 M 20
2 F 55 11 M 22
3 F 60 10 M 20
3 F 60 11 M 22
3 F 60 12 M 59

Basic Operators in Relational Algebra


Relational Algebra is a procedural query language that takes relations as an input
and returns relation as an output. There are some basic operators which can be
applied on relations to produce required results which we will discuss one by
one. We will use STUDENT_SPORTS, EMPLOYEE, and STUDENT relations as given
in Table 1, Table 2, and Table 3 respectively to understand the various
operators.
Table 1: STUDENT_SPORTS

ROLL_NO SPORTS

1 Badminton

2 Cricket

2 Badminton

4 Badminton

Table 2: EMPLOYEE
EMP_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

5 NARESH HISAR 9782918192 22

6 SWETA RANCHI 9852617621 21


4 SURESH DELHI 9156768971 18

Table 3: STUDENT
ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18

Selection operator (σ): Selection operator is used to select tuples from a relation
based on some condition. Syntax:
σ (Cond)(Relation Name)
Extract students whose age is greater than 18 from STUDENT relation given in
Table 3
σ (AGE>18)(STUDENT)
RESULT:
ROLL_NO NAME ADDRESS PHONE AGE

3 SUJIT ROHTAK 9156253131 20

Projection Operator (∏): Projection operator is used to project particular


columns from a relation. Syntax:
∏(Column 1,Column 2….Column n)(Relation Name)
Extract ROLL_NO and NAME from STUDENT relation given in Table 3
∏(ROLL_NO,NAME)(STUDENT)
RESULT:

ROLL_NO NAME

1 RAM

2 RAMESH

3 SUJIT
4 SURESH

Note: If resultant relation after projection has duplicate rows, it will be removed.
For Example: ∏(ADDRESS)(STUDENT) will remove one duplicate row with value
DELHI and return three rows.
Cross Product(X): Cross product is used to join two relations. For every row of
Relation1, each row of Relation2 is concatenated. If Relation1 has m tuples and
and Relation2 has n tuples, cross product of Relation1 and Relation2 will have m
X n tuples. Syntax:
Relation1 X Relation2
To apply Cross Product on STUDENT relation given in Table 1 and
STUDENT_SPORTS relation given in Table 2,
STUDENT X STUDENT_SPORTS
RESULT:
ROLL_N ADDRES AG ROLL_N
O NAME S PHONE E O SPORTS

945512345 Badminto
1 RAM DELHI 1 18 1 n

945512345
1 RAM DELHI 1 18 2 Cricket

945512345 Badminto
1 RAM DELHI 1 18 2 n

945512345 Badminto
1 RAM DELHI 1 18 4 n

RAMES GURGAO 965243154 Badminto


2 H N 3 18 1 n

RAMES GURGAO 965243154


2 H N 3 18 2 Cricket

RAMES GURGAO 965243154 Badminto


2 H N 3 18 2 n

RAMES GURGAO 965243154 Badminto


2 H N 3 18 4 n
915625313 Badminto
3 SUJIT ROHTAK 1 20 1 n

915625313
3 SUJIT ROHTAK 1 20 2 Cricket

915625313 Badminto
3 SUJIT ROHTAK 1 20 2 n

915625313 Badminto
3 SUJIT ROHTAK 1 20 4 n

SURES 915676897 Badminto


4 H DELHI 1 18 1 n

SURES 915676897
4 H DELHI 1 18 2 Cricket

SURES 915676897 Badminto


4 H DELHI 1 18 2 n

SURES 915676897 Badminto


4 H DELHI 1 18 4 n

Union (U): Union on two relations R1 and R2 can only be computed if R1 and R2
are union compatible (These two relation should have same number of
attributes and corresponding attributes in two relations have same domain) .
Union operator when applied on two relations R1 and R2 will give a relation with
tuples which are either in R1 or in R2. The tuples which are in both R1 and R2
will appear only once in result relation. Syntax:
Relation1 U Relation2
Find person who are either student or employee, we can use Union operator
like:
STUDENT U EMPLOYEE
RESULT:
ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18


3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18

5 NARESH HISAR 9782918192 22

6 SWETA RANCHI 9852617621 21

Minus (-): Minus on two relations R1 and R2 can only be computed if R1 and R2
are union compatible. Minus operator when applied on two relations as R1-R2
will give a relation with tuples which are in R1 but not in R2. Syntax:
Relation1 - Relation2
Find person who are student but not employee, we can use minus operator like:
STUDENT - EMPLOYEE
RESULT:
ROLL_NO NAME ADDRESS PHONE AGE

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

Rename(ρ): Rename operator is used to give another name to a


relation. Syntax:
ρ(Relation2, Relation1)
To rename STUDENT relation to STUDENT1, we can use rename operator like:
ρ(STUDENT1, STUDENT)
If you want to create a relation STUDENT_NAMES with ROLL_NO and NAME from
STUDENT, it can be done using rename operator as:
ρ(STUDENT_NAMES, ∏(ROLL_NO, NAME)(STUDENT))

Relational Calculus
o Relational calculus is a non-procedural query language. In the non-procedural query
language, the user is concerned with the details of how to obtain the end results.
o The relational calculus tells what to do but never explains how to do.
Types of Relational calculus:

Tuple Relational Calculus (TRC) in


DBMS
Tuple Relational Calculus is a non-procedural query language unlike
relational algebra. Tuple Calculus provides only the description of the query
but it does not provide the methods to solve it. Thus, it explains what to do
but not how to do.
In Tuple Calculus, a query is expressed as
{t| P(t)}
where t = resulting tuples,
P(t) = known as Predicate and these are the conditions that are used to fetch
t
Thus, it generates set of all tuples t, such that Predicate P(t) is true for t.

P(t) may have various conditions logically combined with OR (∨), AND (∧),
NOT(¬).
It also uses quantifiers:
∃ t ∈ r (Q(t)) = ”there exists” a tuple in t in relation r such that predicate Q(t)
is true.
∀ t ∈ r (Q(t)) = Q(t) is true “for all” tuples in relation r.
Example:
Table-1: Customer
Customer name Street City

Saurabh A7 Patiala

Mehak B6 Jalandhar

Sumiti D9 Ludhiana

Ria A5 Patiala

Table-2: Branch
Branch name Branch city

ABC Patiala

DEF Ludhiana

GHI Jalandhar

Table-3: Account
Account number Branch name Balance

1111 ABC 50000

1112 DEF 10000

1113 GHI 9000

1114 ABC 7000

Table-4: Loan
Loan number Branch name Amount

L33 ABC 10000

L35 DEF 15000

L49 GHI 9000


Loan number Branch name Amount

L98 DEF 65000

Table-5: Borrower
Customer name Loan number

Saurabh L33

Mehak L49

Ria L98

Table-6: Depositor
Customer name Account number

Saurabh 1111

Mehak 1113

Sumiti 1114

Queries-1: Find the loan number, branch, amount of loans of greater than or
equal to 10000 amount.

{t| t ∈ loan ∧ t[amount]>=10000}


Resulting relation:

Loan number Branch name Amount

L33 ABC 10000

L35 DEF 15000

L98 DEF 65000

In the above query, t[amount] is known as tuple variable.


Queries-2: Find the loan number for each loan of an amount greater or
equal to 10000.
{t| ∃ s ∈ loan(t[loan number] = s[loan number]
∧ s[amount]>=10000)}
Resulting relation:

Loan number

L33

L35

L98

Queries-3: Find the names of all customers who have a loan and an account
at the bank.
{t | ∃ s ∈ borrower( t[customer-name] = s[customer-name])
∧ ∃ u ∈ depositor( t[customer-name] = u[customer-name])}
Resulting relation:

Customer name

Saurabh

Mehak

Queries-4: Find the names of all customers having a loan at the “ABC”
branch.
{t | ∃ s ∈ borrower(t[customer-name] = s[customer-name]
∧ ∃ u ∈ loan(u[branch-name] = “ABC” ∧ u[loan-number] = s[loan-
number]))}
Resulting relation:

Customer name

Saurabh

Domain Relational Calculus in DBMS


Domain Relational Calculus is a non-procedural query language equivalent
in power to Tuple Relational Calculus. Domain Relational Calculus provides
only the description of the query but it does not provide the methods to solve
it. In Domain Relational Calculus, a query is expressed as,
{ < x1, x2, x3, ..., xn > | P (x1, x2, x3, ..., xn ) }
where, < x1, x2, x3, …, xn > represents resulting domains variables and P (x 1,
x2, x3, …, xn ) represents the condition or formula equivalent to the Predicate
calculus.

Predicate Calculus Formula:


1. Set of all comparison operators
2. Set of connectives like and, or, not
3. Set of quantifiers
Example:

Table-1: Customer
Customer name Street City

Debomit Kadamtala Alipurduar

Sayantan Udaypur Balurghat

Soumya Nutanchati Bankura

Ritu Juhu Mumbai

Table-2: Loan
Loan number Branch name Amount

L01 Main 200

L03 Main 150

L10 Sub 90

L08 Main 60

Table-3: Borrower
Customer name Loan number

Ritu L01

Debomit L08
Customer name Loan number

Soumya L03

Query-1: Find the loan number, branch, amount of loans of greater than or
equal to 100 amount.
{≺l, b, a≻ | ≺l, b, a≻ ∈ loan ∧ (a ≥ 100)}
Resulting relation:

Loan number Branch name Amount

L01 Main 200

L03 Main 150

Query-2: Find the loan number for each loan of an amount greater or equal
to 150.
{≺l≻ | ∃ b, a (≺l, b, a≻ ∈ loan ∧ (a ≥ 150)}
Resulting relation:

Loan number

L01

L03

Query-3: Find the names of all customers having a loan at the “Main” branch
and find the loan amount .
{≺c, a≻ | ∃ l (≺c, l≻ ∈ borrower ∧ ∃ b (≺l, b, a≻ ∈ loan ∧ (b =
“Main”)))}
Resulting relation:

Customer Name Amount

Ritu 200

Debomit 60

Soumya 150

Note:
The domain variables those will be in resulting relation must appear before |
within ≺ and ≻ and all the domain variables must appear in which order they
are in original relation or table.
Difference between Tuple Relational
Calculus (TRC) and Domain Relational
Calculus (DRC)
1. Tuple Relational Calculus (TRC) :
A tuple relational calculus is a non procedural query language which
specifies to select the tuples in a relation. It can select the tuples with range
of values or tuples for certain attribute values etc. The resulting relation can
have one or more tuples.
Notation :
{T | P (T)} or {T | Condition (T)}
-where T is resulting tuples and P(T) is a condition used to fetch T.
Example :

{T | EMPLOYEE (T) AND T.DEPT_ID = 10}


This select all the tuples of employee name who work for Department 10.
2. Domain Relational Calculus (DRC) :
A domain relational calculus uses list of attribute to be selected from the
relation based on the condition. It is same as TRC, but differs by selecting
the attributes rather than selecting whole tuples.
Notation :
{ a1, a2, a3, ..., an | P (a1, a2, a3, ..., an) }
-Where a1, a2, a3, … an are attributes of the relation and P is the condition.
Example :
{ | < EMPLOYEE > DEPT_ID = 10 }
select EMP_ID and EMP_NAME of employees who work for department 10.

Difference between Tuple Relational Calculus (TRC) and Domain


Relational Calculus (DRC) :
Tuple Relational Calculus (TRC) Domain Relational Calculus (DRC)

In TRS, the variables represent the tuples In DRS, the variables represent the value drawn
from specified relation. from specified domain.

A tuple is a single element of relation.In A domain is equivalent to column data type and
database term, it is a row. any constraints on value of data.
Tuple Relational Calculus (TRC) Domain Relational Calculus (DRC)

In this filtering variable uses tuple of In this filtering is done based on the domain of
relation. attributes.

Notation : Notation :
{T | P (T)} or {T | Condition (T)} { a1, a2, a3, …, an | P (a1, a2, a3, …, an)}

Example :
{T | EMPLOYEE (T) AND T.DEPT_ID Example :
= 10} { | < EMPLOYEE > DEPT_ID = 10 }

Structured Query Language (SQL)


Structured Query Language is a standard Database language which is used
to create, maintain and retrieve the relational database. Following are some
interesting facts about SQL.
• SQL is case insensitive. But it is a recommended practice to use
keywords (like SELECT, UPDATE, CREATE, etc) in capital letters
and use user defined things (liked table name, column name, etc) in
small letters.
• We can write comments in SQL using “–” (double hyphen) at the
beginning of any line.
• SQL is the programming language for relational databases
(explained below) like MySQL, Oracle, Sybase, SQL Server,
Postgre, etc. Other non-relational databases (also called NoSQL)
databases like MongoDB, DynamoDB, etc do not use SQL
• Although there is an ISO standard for SQL, most of the
implementations slightly vary in syntax. So we may encounter
queries that work in SQL Server but do not work in MySQL.
.
What is Relational Database?
Relational database means the data is stored as well as retrieved in the form
of relations (tables). Table 1 shows the relational database with only one
relation called STUDENT which
stores ROLL_NO, NAME, ADDRESS, PHONE and AGE of students.

STUDENT
ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18


2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18

TABLE 1
These are some important terminologies that are used in terms of relation.
Attribute: Attributes are the properties that define a relation.
e.g.; ROLL_NO, NAME etc.
Tuple: Each row in the relation is known as tuple. The above relation
contains 4 tuples, one of which is shown as:
1 RAM DELHI 9455123451 18

Degree: The number of attributes in the relation is known as degree of the


relation. The STUDENT relation defined above has degree 5.
Cardinality: The number of tuples in a relation is known as cardinality.
The STUDENT relation defined above has cardinality 4.
Column: Column represents the set of values for a particular attribute. The
column ROLL_NO is extracted from relation STUDENT.

ROLL_NO

The queries to deal with relational database can be categories as:


Data Definition Language: It is used to define the structure of the database.
e.g; CREATE TABLE, ADD COLUMN, DROP COLUMN and so on.
Data Manipulation Language: It is used to manipulate data in the relations.
e.g.; INSERT, DELETE, UPDATE and so on.
Data Query Language: It is used to extract the data from the relations. e.g.;
SELECT
So first we will consider the Data Query Language. A generic query to
retrieve from a relational database is:
1. SELECT [DISTINCT] Attribute_List FROM R1,R2….RM
2. [WHERE condition]
3. [GROUP BY (Attributes)[HAVING condition]]
4. [ORDER BY(Attributes)[DESC]];
Part of the query represented by statement 1 is compulsory if you want to
retrieve from a relational database. The statements written inside [] are
optional. We will look at the possible query combination on relation shown in
Table 1.
Case 1: If we want to retrieve attributes ROLL_NO and NAME of all
students, the query will be:
SELECT ROLL_NO, NAME FROM STUDENT;

ROLL_NO NAME

1 RAM

2 RAMESH

3 SUJIT

4 SURESH

Case 2: If we want to retrieve ROLL_NO and NAME of the students


whose ROLL_NO is greater than 2, the query will be:
SELECT ROLL_NO, NAME FROM STUDENT
WHERE ROLL_NO>2;

ROLL_NO NAME

3 SUJIT

4 SURESH

CASE 3: If we want to retrieve all attributes of students, we can write * in


place of writing all attributes as:
SELECT * FROM STUDENT
WHERE ROLL_NO>2;

ROLL_NO NAME ADDRESS PHONE AGE

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 9156768971 18


CASE 4: If we want to represent the relation in ascending order by AGE, we
can use ORDER BY clause as:

SELECT * FROM STUDENT ORDER BY AGE;

ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

4 SURESH DELHI 9156768971 18

3 SUJIT ROHTAK 9156253131 20

Note: ORDER BY AGE is equivalent to ORDER BY AGE ASC. If we want to


retrieve the results in descending order of AGE, we can use ORDER
BY AGE DESC.
CASE 5: If we want to retrieve distinct values of an attribute or group of
attribute, DISTINCT is used as in:
SELECT DISTINCT ADDRESS FROM STUDENT;

ADDRESS

DELHI

GURGAON

ROHTAK

If DISTINCT is not used, DELHI will be repeated twice in result set. Before
understanding GROUP BY and HAVING, we need to understand
aggregations functions in SQL.
AGGRATION FUNCTIONS: Aggregation functions are used to perform
mathematical operations on data values of a relation. Some of the common
aggregation functions used in SQL are:
• COUNT: Count function is used to count the number of rows in a
relation. e.g;
SELECT COUNT (PHONE) FROM STUDENT;

COUNT(PHONE)
4

•SUM: SUM function is used to add the values of an attribute in a


relation. e.g;
SELECT SUM (AGE) FROM STUDENT;
SUM(AGE)

74

In the same way, MIN, MAX and AVG can be used. As we have seen
above, all aggregation functions return only 1 row.
AVERAGE: It gives the average values of the tupples. It is also defined as
sum divided by count values.
Syntax: AVG (attribute name )
OR
Syntax:SUM(attributename)/COUNT(attributename)
The above mentioned syntax also retrieves the average value of tupples.
MAXIMUM:It extracts the maximum value among the set of tupples.
Syntax:MAX(attributename)
MINIMUM:It extracts the minimum value amongst the set of all the tupples.
Syntax:MIN(attributename)
GROUP BY: Group by is used to group the tuples of a relation based on an
attribute or group of attribute. It is always combined with aggregation function
which is computed on group. e.g.;
SELECT ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);
In this query, SUM(AGE) will be computed but not for entire table but for
each address. i.e.; sum of AGE for address DELHI(18+18=36) and similarly
for other address as well. The output is:
ADDRESS SUM(AGE)

DELHI 36

GURGAON 18

ROHTAK 20

If we try to execute the query given below, it will result in error because
although we have computed SUM(AGE) for each address, there are more
than 1 ROLL_NO for each address we have grouped. So it can’t be
displayed in result set. We need to use aggregate functions on columns after
SELECT statement to make sense of the resulting set whenever we are
using GROUP BY.
SELECT ROLL_NO, ADDRESS, SUM(AGE) FROM STUDENT
GROUP BY (ADDRESS);
NOTE: An attribute which is not a part of GROUP BY clause can’t be used
for selection. Any attribute which is part of GROUP BY CLAUSE can be used
for selection but it is not mandatory. But we could use attributes which are
not a part of the GROUP BY clause in an aggregrate function.

SQL | DDL, DQL, DML, DCL and TCL


Commands
Structured Query Language(SQL) as we all know is the database language by
the use of which we can perform certain operations on the existing database
and also we can use this language to create a database. SQL uses certain
commands like Create, Drop, Insert, etc. to carry out the required tasks.
These SQL commands are mainly categorized into four categories as:

1. DDL – Data Definition Language


2. DQl – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
Though many resources claim there to be another category of SQL
clauses TCL – Transaction Control Language. So we will see in detail
about TCL as well.
DDL (Data Definition Language):
DDL or Data Definition Language actually consists of the SQL commands that
can be used to define the database schema. It simply deals with descriptions
of the database schema and is used to create and modify the structure of
database objects in the database.DDL is a set of SQL commands used to
create, modify, and delete database structures but not data. These commands
are normally not used by a general user, who should be accessing the
database via an application.
List of DDL commands:
1. It contains of commands which defines the data. The commands
are:
• create: It is used to create a table.
Syntax:
create table
tablename(attribute1 datatype......attributen datatype);
• drop: It is used to delete the table including all the attributes.
Syntax:
drop table tablename;
• alter: alter is a reserve word which modifies the structure of the
table.
Syntax:
alter table
tablename add(new column1 datatype......new columnx datatype);
• rename: A table name can be changed using the reserver
‘rename’
Syntax:
rename old table name to new table name;
TRUNCATE
TRUNCATE statement is a Data Definition Language (DDL) operation that is
used to mark the extents of a table for deallocation (empty for reuse). The
result of this operation quickly removes all data from a table, typically
bypassing a number of integrity enforcing mechanisms. It was officially
introduced in the SQL:2008 standard.
The TRUNCATE TABLE mytable statement is logically (though not
physically) equivalent to the DELETE FROM mytable statement (without a
WHERE clause).
Syntax:

TRUNCATE TABLE table_name;


table_name: Name of the table to be truncated.
DATABASE name - student_data
DROP vs TRUNCATE
• Truncate is normally ultra-fast and its ideal for deleting data from a
temporary table.
• Truncate preserves the structure of the table for future use, unlike
drop table where the table is deleted with its full structure.
• Table or Database deletion using DROP statement cannot be
rolled back, so it must be used wisely.
Queries
• To delete the whole database
• DROP DATABASE student_data;
After running the above query whole database will be deleted.
• To truncate Student_details table from student_data database.
• TRUNCATE TABLE Student_details;
After running the above query Student_details table will be
truncated, i.e, the data will be deleted but the structure will remain
in the memory for further operations.
DQL (Data Query Language):
DQL statements are used for performing queries on the data within schema
objects. The purpose of the DQL Command is to get some schema relation
based on the query passed to it. We can define DQL as follows it is a
component of SQL statement that allows getting data from the database and
imposing order upon it. It includes the SELECT statement. This command
allows getting the data out of the database to perform operations with it. When
a SELECT is fired against a table or tables the result is compiled into a further
temporary table, which is displayed or perhaps received by the program i.e. a
front-end.
List of DQL:
• SELECT: It is used to retrieve data from the database.
Select is the most commonly used statement in SQL. The SELECT
Statement in SQL is used to retrieve or fetch data from a database. We can
fetch either the entire table or according to some specified rules. The data
returned is stored in a result table. This result table is also called result-set.
With the SELECT clause of a SELECT command statement, we specify the
columns that we want to be displayed in the query result and, optionally,
which column headings we prefer to see above the result table.
The select clause is the first clause and is one of the last clauses of the
select statement that the database server evaluates. The reason for this is
that before we can determine what to include in the final result set, we need
to know all of the possible columns that could be included in the final result
set.
Sample Table:

Basic Syntax:

SELECT column1,column2 FROM table_name


column1 , column2: names of the fields of the table
table_name: from where we want to fetch
This query will return all the rows in the table with fields column1 , column2.
• To fetch the entire table or all the fields in the table:
SELECT * FROM table_name;
• Query to fetch the fields ROLL_NO, NAME, AGE from the table
Student:
SELECT ROLL_NO, NAME, AGE FROM Student;
Output:
ROLL_NONAME Age
1 Ram 18

2 RAMESH 18

3 SUJIT 20

4 SURESH 18

• To fetch all the fields from the table Student:


SELECT * FROM Student;
Output:
ROLL_NONAME ADDRESS PHONE Age
1 Ram Delhi XXXXXXXXXX 18

2 RAMESH GURGAON XXXXXXXXXX 18

3 SUJIT ROHTAK XXXXXXXXXX 20

4 SURESH Delhi XXXXXXXXXX 18

DML(Data Manipulation Language):


The SQL commands that deals with the manipulation of data present in the
database belong to DML or Data Manipulation Language and this includes
most of the SQL statements. It is the component of the SQL statement that
controls access to data and to the database. Basically, DCL statements are
grouped with DML statements.
List of DML commands:
• INSERT : It is used to insert data into a table.
• UPDATE: It is used to update existing data within a table.
• DELETE : It is used to delete records from a database table.
• LOCK: Table control concurrency.
• CALL: Call a PL/SQL or JAVA subprogram.
• EXPLAIN PLAN: It describes the access path to data.
Characteristics :
It performs interpret-only data queries. It is used in a database schema to
recall and manipulate the information. DML It is a dialect which is used to
select, insert, delete and update data in a database.
Data Manipulation Language (DML) commands are as follows:
1. SELECT Command –
This command is used to get data out of the database. It helps
users of the database to access from an operating system, the
significant data they need. It sends a track result set from one
tables or more.
Syntax :
SELECT *
FROM <table_name>;
Example :

SELECT *
FROM students;

OR

SELECT *
FROM students
where due_fees <=20000;
2. INSERT Command –
This command is used to enter the information or values into a row.
We can connect one or more records to a single table within a
repository using this instruction. This is often used to connect an
unused tag to the documents.
Syntax :
INSERT INTO <table_name> ('column_name1' <datatype>,
'column_name2' <datatype>)

VALUES ('value1', 'value2');


Example :
INSERT INTO students ('stu_id' int, 'stu_name' varchar(20),
'city' varchar(20))

VALUES ('1', 'Nirmit', 'Gorakhpur');


3. UPDATE Command –
This command is used to alter existing table records. Within a table,
it modifies data from one or more records. This command is used to
alter the data which is already present in a table.
Syntax :
UPDATE <table_name>
SET <column_name = value>

WHERE condition;
Example :
UPDATE students

SET due_fees = 20000

WHERE stu_name = 'Mini';


4. DELETE Command –
It deletes all archives from a table. This command is used to erase
some or all of the previous table’s records. If we do not specify the
‘WHERE’ condition then all the rows would be erased or deleted.
Syntax :
DELETE FROM <table_name>

WHERE <condition>;
Example :
DELETE FROM students

WHERE stu_id = '001';


Advantages :
1. DML statements could alter the data that is contained or stored in
the database.
2. It delivers effective human contact with the machine.
3. User could specify what data is required.
4. DML aims to have many different varieties and functionalities
between vendors providing databases.
Disadvantages :
1. We cannot use DML to change the structure of the database.
2. Limit table view i.e., it could conceal some columns in tables.
3. Access the data without having the data stored in the object.
4. Unable to build or erase lists or sections using DML.

Data Controlling Language (DCL)


Data Controlling Language (DCL) helps users to retrieve and modify the data
stored in the database with some specified queries. Grant and Revoke
belong to these types of commands of the Data controlling Language. DCL is
a component of SQL commands.
1. Grant :
SQL Grant command is specifically used to provide privileges to database
objects for a user. This command also allows users to grant permissions to
other users too.
Syntax:
grant privilege_name on object_name
to {user_name | public | role_name}
Here privilege_name is which permission has to be granted, object_name is
the name of the database object, user_name is the user to which access
should be provided, the public is used to permit access to all the users.

2. Revoke :
Revoke command withdraw user privileges on database objects if any
granted. It does operations opposite to the Grant command. When a
privilege is revoked from a particular user U, then the privileges granted to all
other users by user U will be revoked.
Syntax:
revoke privilege_name on object_name
from {user_name | public | role_name}
Example:
grant insert,
select on accounts to Ram
By the above command user ram has granted permissions on accounts
database object like he can query or insert into accounts.
revoke insert,
select on accounts from Ram
By the above command user ram’s permissions like query or insert on
accounts database object has been removed.
To know the exact syntax and how are they used click here.
Differences between Grant and Revoke commands:

S.NO Grant Revoke

This DCL command grants This DCL command removes permissions


permissions to the user on the if any granted to the users on database
1 database objects. objects.

2 It assigns access rights to users. It revokes the useraccess rights of users.

If access for one user is removed; all the


For each user you need to particular permissions provided by that
3 specify the permissions. users to others will be removed.

When the access is


decentralized granting If decentralized access removing the
4 permissions will be easy. granted permissions is difficult.

Though many resources claim there to be another category of SQL clauses


TCL – Transaction Control Language. So we will see in detail about TCL as
well. TCL commands deal with the transaction within the database.
List of TCL commands:

• COMMIT: Commits a Transaction.


• ROLLBACK: Rollbacks a transaction in case of any error occurs.
• SAVEPOINT:Sets a savepoint within a transaction.
• SET TRANSACTION: Specify characteristics for the transaction.
• Following commands are used to control transactions. It is important to
note that these statements cannot be used while creating tables and
are only used with the DML Commands such as – INSERT, UPDATE
and DELETE.

• 1. BEGIN TRANSACTION: It indicates the start point of an explicit or


local transaction.
• Syntax:
• BEGIN TRANSACTION transaction_name ;
• 2. SET TRANSACTION: Places a name on a transaction.
• Syntax:
• SET TRANSACTION [ READ WRITE | READ ONLY ];
• 3. COMMIT: If everything is in order with all statements within a single
transaction, all changes are recorded together in the database is
called committed. The COMMIT command saves all the transactions
to the database since the last COMMIT or ROLLBACK command.

• Syntax:

• COMMIT;
• Example: Sample table 1


• Following is an example which would delete those records from the
table which have age = 20 and then COMMIT the changes in the
database.
Queries:
• DELETE FROM Student WHERE AGE = 20;
• COMMIT;

• Output:
Thus, two rows from the table would be deleted and the SELECT
statement would look like,


• 4. ROLLBACK: If any error occurs with any of the SQL grouped
statements, all changes need to be aborted. The process of reversing
changes is called rollback. This command can only be used to undo
transactions since the last COMMIT or ROLLBACK command was
issued.
Syntax:

• ROLLBACK;

• Example:
From the above example Sample table1,
Delete those records from the table which have age = 20 and then
ROLLBACK the changes in the database.
Queries:

• DELETE FROM Student WHERE AGE = 20;


• ROLLBACK;
• Output:


• 5. SAVEPOINT: creates points within the groups of transactions in
which to ROLLBACK.
A SAVEPOINT is a point in a transaction in which you can roll the
transaction back to a certain point without rolling back the entire
transaction.

• Syntax for Savepoint command:

• SAVEPOINT SAVEPOINT_NAME;
• This command is used only in the creation of SAVEPOINT among all
the transactions.
In general ROLLBACK is used to undo a group of transactions.
Syntax for rolling back to Savepoint command:

• ROLLBACK TO SAVEPOINT_NAME;

• you can ROLLBACK to any SAVEPOINT at any time to return the
appropriate data to its original state.
Example:
From the above example Sample table1,
Delete those records from the table which have age = 20 and then
ROLLBACK the changes in the database by keeping Savepoints.
Queries:

• SAVEPOINT SP1;
• //Savepoint created.
• DELETE FROM Student WHERE AGE = 20;
• //deleted
• SAVEPOINT SP2;
• //Savepoint created.

• Here SP1 is first SAVEPOINT created before deletion. In this example
one deletion have taken place.
After deletion again SAVEPOINT SP2 is created.
Output:


• Deletion have been taken place, let us assume that you have changed
your mind and decided to ROLLBACK to the SAVEPOINT that you
identified as SP1 which is before deletion.
deletion is undone by this statement,

• ROLLBACK TO SP1;
• //Rollback completed.


• 6. RELEASE SAVEPOINT:- This command is used to remove a
SAVEPOINT that you have created.
Syntax:

• RELEASE SAVEPOINT SAVEPOINT_NAME



• Once a SAVEPOINT has been released, you can no longer use the
ROLLBACK command to undo transactions performed since the last
SAVEPOINT.
• It is used to initiate a database transaction and used to specify
characteristics of the transaction that follows.

SQL Set Operation


The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation


1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union
o The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
o In the union operation, all the number of datatype and columns must be same in both
the tables on which UNION operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.

Syntax

1. SELECT column_name FROM table1


2. UNION
3. SELECT column_name FROM table2;

Example:

The First table

ID NAME
1 Jack

2 Harry

3 Jackson

The Second table

ID NAME

3 Jackson

4 Stephan

5 David

Union SQL query will be:

1. SELECT * FROM First


2. UNION
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

4 Stephan

5 David
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.

Syntax:

1. SELECT column_name FROM table1


2. UNION ALL
3. SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:

1. SELECT * FROM First


2. UNION ALL
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

3 Jackson

4 Stephan

5 David

3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.

Syntax

1. SELECT column_name FROM table1


2. INTERSECT
3. SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

1. SELECT * FROM First


2. INTERSECT
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

3 Jackson

4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display the
rows which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.

Syntax:

1. SELECT column_name FROM table1


2. MINUS
3. SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:


1. SELECT * FROM First
2. MINUS
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

SQL Aggregate Functions


o SQL aggregation function is used to perform the calculations on multiple rows of a
single column of a table. It returns a single value.
o It is also used to summarize the data.

Types of SQL Aggregation Function

1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It can work
on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.

Syntax

1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )

Sample table:

PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example: COUNT()

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;

Output:

10

Example: COUNT with WHERE

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;

Output:

Example: COUNT() with DISTINCT

1. SELECT COUNT(DISTINCT COMPANY)


2. FROM PRODUCT_MAST;

Output:

Example: COUNT() with GROUP BY

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;

Output:

Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;

Output:
Com1 5
Com2 3

2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric
fields only.

Syntax

1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )

Example: SUM()

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;

Output:

670

Example: SUM() with WHERE

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;

Output:

320

Example: SUM() with GROUP BY

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;

Output:

Com1 150
Com2 170

Example: SUM() with HAVING


1. SELECT COMPANY, SUM(COST)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=170;

Output:

Com1 335
Com3 170

3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG
function returns the average of all non-Null values.

Syntax

1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )

Example:

1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;

Output:

67.00

4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.

Syntax

1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )

Example:

1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30

5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.

Syntax

1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )

Example:

1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;

Output:

10

SQL NULL Values


In SQL there may be some records in a table that do not have values or data for
every field. This could be possible because at a time of data entry information is
not available. So SQL supports a special value known as NULL which is used to
represent the values of attributes that may be unknown or not apply to a tuple.
SQL places a NULL value in the field in the absence of a user-defined value. For
example, the Apartment_number attribute of an address applies only to address
that are in apartment buildings and not to other types of residences.
Importance of NULL value:
• It is important to understand that a NULL value is different from a zero
value.
• A NULL value is used to represent a missing value, but that it usually has
one of three different interpretations:
• The value unknown (value exists but is not known)
• Value not available (exists but is purposely withheld)
• Attribute not applicable (undefined for this tuple)
• It is often not possible to determine which of the meanings is intended.
Hence, SQL does not distinguish between the different meanings of
NULL.
Principles of NULL values:

• Setting a NULL value is appropriate when the actual value is unknown,


or when a value would not be meaningful.
• A NULL value is not equivalent to a value of ZERO if the data type is a
number and is not equivalent to spaces if the data type is character.
• A NULL value can be inserted into columns of any data type.
• A NULL value will evaluate NULL in any expression.
• Suppose if any column has a NULL value, then UNIQUE, FOREIGN key,
CHECK constraints will ignore by SQL.
In general, each NULL value is considered to be different from every other NULL
in the database. When a NULL is involved in a comparison operation, the result is
considered to be UNKNOWN. Hence, SQL uses a three-valued logic with
values True, False, and Unknown. It is, therefore, necessary to define the results of
three-valued logical expressions when the logical connectives AND, OR, and NOT
are used.

How to test for NULL Values?


SQL allows queries that check whether an attribute value is NULL. Rather than
using = or to compare an attribute value to NULL, SQL uses IS and IS NOT. This is
because SQL considers each NULL value as being distinct from every other NULL
value, so equality comparison is not appropriate.
Now, consider the following Employee Table,
Suppose if we find the Fname, Lname of the Employee having no Super_ssn then
the query will be:
Query
SELECT Fname, Lname FROM Employee WHERE Super_ssn IS NULL;
Output:

Now if we find the Count of the number of Employees having Super_ssn.


Query:

SELECT COUNT(*) AS Count FROM Employee WHERE Super_ssn IS NOT NULL;


Output:

Domain constraints in DBMS


In DBMS, constraints are the set of rules that ensures that when an
authorized user modifies the database they do not disturb the data
consistency and the constraints are specified within the DDL commands like
“alter” and “create” command. There are several types of constraints
available in DBMS and they are:
• Domain constraints
• Entity Integrity constraints
• Referential Integrity constraints
• Key constraints
In this article, we will only discuss domain constraints.
Domain Constraints

Domain Constraints are user-defined columns that help the user to enter the
value according to the data type. And if it encounters a wrong input it gives
the message to the user that the column is not fulfilled properly. Or in other
words, it is an attribute that specifies all the possible values that the attribute
can hold like integer, character, date, time, string, etc. It defines the domain
or the set of values for an attribute and ensures that the value taken by the
attribute must be an atomic value(Can’t be divided) from its domain.
Domain Constraint = data type(integer / character/date / time /
string / etc.) +
Constraints(NOT NULL / UNIQUE / PRIMARY KEY /
FOREIGN KEY / CHECK / DEFAULT)
Type of domain constraints:
There are two types of constraints that come under domain constraint and
they are:
1. Domain Constraints – Not Null: Null values are the values that are
unassigned or we can also say that which are unknown or the missing
attribute values and by default, a column can hold the null values. Now as
we know that the Not Null constraint restricts a column to not accept the null
values which means it only restricts a field to always contain a value which
means you cannot insert a new record or update a record without adding a
value into the field.
Example: In the ’employee’ database, every employee must have a name
associated with them.
Create table employee
(employee_id varchar(30),
employee_name varchar(30) not null,
salary NUMBER);
2. Domain Constraints – Check: It defines a condition that each row must
satisfy which means it restricts the value of a column between ranges or we
can say that it is just like a condition or filter checking before saving data into
a column. It ensures that when a tuple is inserted inside the relation must
satisfy the predicate given in the check clause.
Example: We need to check whether the entered id number is greater than 0
or not for the employee table.
Create table employee
(employee_id varchar(30) not null check(employee_id > 0),
employee_name varchar(30),
salary NUMBER);
The above example creates CHECK constraints on the employee_id column
and specifies that the column employee_id must only include integers
greater than 0.

Note: In DBMS a table is a combination of rows and columns in which we


have some unique attribute names associated with it. And basically, a
domain is a unique set of values present in a table. Let’s take an example,
suppose we have a table student which consists of 3 attributes as NAME,
ROLL NO, and MARKS. Now ROLL NO attributes can have only numbers
associated with them and they won’t contain any alphabet. So we can say
that it contains the domain of integer only and it can be only a positive
number greater than 0.
Example 1:
Creating a table “student” with the “ROLL” field having a value greater than
0.
Domain:

Table:

The above example will only accept the roll no. which is greater than 0.
Example 2:
Creating a table “Employee” with the “AGE” field having a value greater than
18.
Domain:

Table:
The above example will only accept the Employee with an age greater than
18.

Referential Integrity constraint


A referential integrity constraint is also known as foreign key constraint. A foreign
key is a key whose values are derived from the Primary key of another table.

The table from which the values are derived is known as Master or Referenced Table
and the Table in which values are inserted accordingly is known as Child or
Referencing Table, In other words, we can say that the table containing the foreign
key is called the child table, and the table containing the Primary key/candidate
key is called the referenced or parent table. When we talk about the database
relational model, the candidate key can be defined as a set of attribute which can have
zero or more attributes.

The syntax of the Master Table or Referenced table is:

1. CREATE TABLE Student (Roll int PRIMARY KEY, Name varchar(25) , Course varc
har(10) );

Here column Roll is acting as Primary Key, which will help in deriving the value of
foreign key in the child table.

The syntax of Child Table or Referencing table is:


1. CREATE TABLE Subject (Roll int references Student, SubCode int, SubName va
rchar(10) );

In the above table, column Roll is acting as Foreign Key, whose values are derived
using the Roll value of Primary key from Master table.

Foreign Key Constraint OR Referential Integrity constraint.


There are two referential integrity constraint:

Insert Constraint: Value cannot be inserted in CHILD Table if the value is not lying in
MASTER Table

Delete Constraint: Value cannot be deleted from MASTER Table if the value is lying
in CHILD Table

Suppose you wanted to insert Roll = 05 with other values of columns in SUBJECT Table,
then you will immediately see an error "Foreign key Constraint Violated" i.e. on
running an insertion command as:

Insert into SUBJECT values(5, 786, OS); will not be entertained by SQL due to
Insertion Constraint ( As you cannot insert value in a child table if the value is not
lying in the master table, since Roll = 5 is not present in the master table, hence it will
not be allowed to enter Roll = 5 in child table )

Similarly, if you want to delete Roll = 4 from STUDENT Table, then you will immediately
see an error "Foreign key Constraint Violated" i.e. on running a deletion command
as:

Delete from STUDENT where Roll = 4; will not be entertained by SQL due to
Deletion Constraint. ( As you cannot delete the value from the master table if the
value is lying in the child table, since Roll = 5 is present in the child table, hence it will
not be allowed to delete Roll = 5 from the master table, lets if somehow we managed
to delete Roll = 5, then Roll = 5 will be available in child table which will ultimately
violate insertion constraint. )

ON DELETE CASCADE.

As per deletion constraint: Value cannot be deleted from the MASTER Table if the value
is lying in CHILD Table. The next question comes can we delete the value from the
master table if the value is lying in the child table without violating the deletion
constraint? i.e. The moment we delete the value from the master table the value
corresponding to it should also get deleted from the child table.

The answer to the above question is YES, we can delete the value from the master table
if the value is lying in the child table without violating the deletion constraint, we have
to do slight modification while creating the child table, i.e. by adding on delete
cascade.

TABLE SYNTAX

1. CREATE TABLE Subject (Roll int references Student on delete cascade, SubCod
e int, SubName varchar(10) );

In the above syntax, just after references keyword( used for creating foreign key), we
have added on delete cascade, by adding such now, we can delete the value from the
master table if the value is lying in the child table without violating deletion constraint.
Now if you wanted to delete Roll = 5 from the master table even though Roll = 5 is
lying in the child table, it is possible because the moment you give the command to
delete Roll = 5 from the master table, the row having Roll = 5 from child table will also
get deleted.
The above two tables STUDENT and SUBJECT having four values each are shown, now
suppose you are looking to delete Roll = 4 from STUDENT( Master ) Table by writing
a SQL command: delete from STUDENT where Roll = 4;

The moment SQL execute the above command the row having Roll = 4 from SUBJECT(
Child ) Table will also get deleted, The resultant STUDENT and SUBJECT table will
look like:
From the above two tables STUDENT and SUBJECT, you can see that in both the table
Roll = 4 gets deleted at one go without violating deletion constraint.

Sometimes a very important question is asked in interviews that: Can Foreign Key have
NULL values?

The answer to the above question is YES, it may have NULL values, whereas the Primary
key cannot be NULL at any cost. To understand the above question practically let's
understand below the concept of delete null.

ON DELETE NULL.

As per deletion constraint: Value cannot be deleted from the MASTER Table if the value
is lying in CHILD Table. The next question comes can we delete the value from the
master table if the value is lying in the child table without violating the deletion
constraint? i.e. The moment we delete the value from the master table the value
corresponding to it should also get deleted from the child table or can be replaced
with the NULL value.

The answer to the above question is YES, we can delete the value from the master table
if the value is lying in child table without violating deletion constraint by inserting NULL
in the foreign key, we have to do slight modification while creating child table, i.e. by
adding on delete null.

TABLE SYNTAX:
1. CREATE TABLE Subject (Roll int references Student on delete null, SubCode in
t, SubName varchar(10) );

In the above syntax, just after references keyword( used for creating foreign key), we
have added on delete null, by adding such now, we can delete the value from the
master table if the value is lying in the child table without violating deletion constraint.
Now if you wanted to delete Roll = 4 from the master table even though Roll =4 is
lying in the child table, it is possible because the moment you give the command to
delete Roll = 4 from the master table, the row having Roll = 4 from child table will get
replaced by a NULL value.

The above two tables STUDENT and SUBJECT having four values each are shown, now
suppose you are looking to delete Roll = 4 from STUDENT( Master ) Table by writing
a SQL command: delete from STUDENT where Roll = 4;

The moment SQL execute the above command the row having Roll = 4 from SUBJECT(
Child ) Table will get replaced by a NULL value, The resultant STUDENT and
SUBJECT table will look like:
From the above two tables STUDENT and SUBJECT, you can see that in table STUDENT
Roll = 4 get deleted while the value of Roll = 4 in the SUBJECT table is replaced by
NULL. This proves that the Foreign key can have null values. If in the case in SUBJECT
Table, column Roll is Primary Key along with Foreign Key then in that case we could
not make a foreign key to have NULL values.

Difference between Assertions and


Triggers in DBMS
1. What are Assertions?
When a constraint involves 2 (or) more tables, the table constraint
mechanism is sometimes hard and results may not come as expected. To
cover such situation SQL supports the creation of assertions that are
constraints not associated with only one table. And an assertion statement
should ensure a certain condition will always exist in the database. DBMS
always checks the assertion whenever modifications are done in the
corresponding table.
Syntax –

CREATE ASSERTION [ assertion_name ]


CHECK ( [ condition ] );
Example –
CREATE TABLE sailors (sid int,sname varchar(20), rating int,primary
key(sid),
CHECK(rating >= 1 AND rating <=10)
CHECK((select count(s.sid) from sailors s) + (select
count(b.bid)from boats b)<100) );
In the above example, we enforcing CHECK constraint that the number of
boats and sailors should be less than 100. So here we are able to CHECK
constraints of two tables simultaneously.

2. What are Triggers?


A trigger is a database object that is associated with the table, it will be
activated when a defined action is executed for the table. The trigger can be
executed when we run the following statements:
1. INSERT
2. UPDATE
3. DELETE
And it can be invoked before or after the event.
Syntax –
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Example –
create trigger t1 before UPDATE on sailors
for each row
begin
if new.age>60 then
set new.age=old.age;
else
set new.age=new.age;
end if;
end;
$
In the above example, we are creating triggers before updates. so, if the new
age is greater than 60 we should not update else we should update. We can
call this trigger by using “$” symbol.
Difference between Assertions and Triggers :
S.No Assertions Triggers

We can use Assertions when we


know that the given particular We can use Triggers even particular
1. condition is always true. condition may or may not be true.

When the SQL condition is not


met then there are chances to an
entire table or even Database to Triggers can catch errors if the condition
2. get locked up. of the query is not true.

Assertions are not linked to It helps in maintaining the integrity


specific table or event. It constraints in the database tables,
performs task specified or especially when the primary key and
3. defined by the user. foreign key constraint are not defined.

Assertions do not maintain any Triggers maintain track of all changes


4. track of changes made in table. occurred in table.

Assertions have small syntax They have large Syntax to indicate each
5. compared to Triggers. and every specific of the created trigger.

Modern databases do not use Triggers are very well used in modern
6. Assertions. databases.

Assertions can’t modify the data and they are not linked to any specific
tables or events in the database but Triggers are more powerful because
they can check conditions and also modify the data within the tables inside a
database, unlike assertions.

SQL | Views
Views in SQL are kind of virtual tables. A view also has rows and columns as they
are in a real table in the database. We can create a view by selecting fields from
one or more tables present in the database. A View can either have all the rows of
a table or specific rows based on certain condition.
In this article we will learn about creating , deleting and updating Views.
Sample Tables:
StudentDetails
StudentMarks

CREATING VIEWS
We can create View using CREATE VIEW statement. A View can be created from
a single table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;

view_name: Name for the View


table_name: Name of the table
condition: Condition to select rows
Examples:
• Creating View from a single table:
• In this example we will create a View named DetailsView
from the table StudentDetails.
Query:
• CREATE VIEW DetailsView AS
• SELECT NAME, ADDRESS
• FROM StudentDetails
• WHERE S_ID < 5;
To see the data in the View, we can query the view in the
same manner as we query a table.
SELECT * FROM DetailsView;
Output:

• In this example, we will create a view named StudentNames


from the table StudentDetails.
Query:
• CREATE VIEW StudentNames AS
• SELECT S_ID, NAME
• FROM StudentDetails
• ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames;
Output:

• Creating View from multiple tables: In this example we will create a


View named MarksView from two tables StudentDetails and
StudentMarks. To create a View from multiple tables we can simply
include multiple tables in the SELECT statement. Query:
• CREATE VIEW MarksView AS
• SELECT StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS
• FROM StudentDetails, StudentMarks
• WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View MarksView:
SELECT * FROM MarksView;
Output:

DELETING VIEWS
We have learned about creating a View, but what if a created View is not needed
any more? Obviously we will want to delete it. SQL allows us to delete an existing
View. We can delete or drop a View using the DROP statement.
Syntax:
DROP VIEW view_name;

view_name: Name of the View which we want to delete.


For example, if we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;
UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any one of
these conditions is not met, then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not
include GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex
queries.
5. The view should be created from a single table. If the view is created
using multiple tables then we will not be allowed to update the view.
• We can use the CREATE OR REPLACE VIEW statement to add or
remove fields from a view.
Syntax:

• CREATE OR REPLACE VIEW view_name AS


• SELECT column1,coulmn2,..
• FROM table_name
• WHERE condition;
For example, if we want to update the view MarksView and add the
field AGE to this View from StudentMarks Table, we can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS,
StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
If we fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:

• Inserting a row in a view:


We can insert a row in a View in a same way as we do in a table. We can
use the INSERT INTO statement of SQL to insert a row in a
View.Syntax:
• INSERT INTO view_name(column1, column2 , column3,..)
• VALUES(value1, value2, value3..);

• view_name: Name of the View


Example:
In the below example we will insert a new row in the View DetailsView
which we have created above in the example of “creating views from a
single table”.
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

• Deleting a row from a View:


Deleting rows from a view is also as simple as deleting rows from a
table. We can use the DELETE statement of SQL to delete rows from a
view. Also deleting a row from a view first delete the row from the
actual table and the change is then reflected in the view.Syntax:
• DELETE FROM view_name
• WHERE condition;

• view_name:Name of view from where we want to delete rows


• condition: Condition to select rows
Example:
In this example we will delete the last row from the view DetailsView
which we just added in the above example of inserting rows.
DELETE FROM DetailsView
WHERE NAME="Suresh";
If we fetch all the data from DetailsView now as,
SELECT * FROM DetailsView;
Output:

WITH CHECK OPTION


The WITH CHECK OPTION clause in SQL is a very useful clause for views. It is
applicable to a updatable view. If the view is not updatable, then there is no
meaning of including this clause in the CREATE VIEW statement.
• The WITH CHECK OPTION clause is used to prevent the insertion of
rows in the view where the condition in the WHERE clause in CREATE
VIEW statement is not satisfied.
• If we have used the WITH CHECK OPTION clause in the CREATE VIEW
statement, and if the UPDATE or INSERT clause does not satisfy the
conditions then they will return an error.
Example:
In the below example we are creating a View SampleView from StudentDetails
Table with WITH CHECK OPTION clause.
CREATE VIEW SampleView AS
SELECT S_ID, NAME
FROM StudentDetails
WHERE NAME IS NOT NULL
WITH CHECK OPTION;
In this View if we now try to insert a new row with null value in the NAME
column then it will give an error because the view is created with the condition
for NAME column as NOT NULL.
For example,though the View is updatable but then also the below query for this
View is not valid:
INSERT INTO SampleView(S_ID)
VALUES(6);
NOTE: The default value of NAME column is null.
Uses of a View :
A good database should contain views due to the given reasons:
1. Restricting data access –
Views provide an additional level of table security by restricting access
to a predetermined set of rows and columns of a table.
2. Hiding data complexity –
A view can hide the complexity that exists in a multiple table join.
3. Simplify commands for the user –
Views allows the user to select information from multiple tables
without requiring the users to actually know how to perform a join.
4. Store complex queries –
Views can be used to store complex queries.
5. Rename Columns –
Views can also be used to rename the columns without affecting the
base tables provided the number of columns in view must match the
number of columns specified in select statement. Thus, renaming helps
to to hide the names of the columns of the base tables.
6. Multiple view facility –
Different views can be created on the same table for different users.
Nested Queries in SQL
In nested queries, a query is written inside a query. The result of inner query is
used in execution of outer query. We will use STUDENT, COURSE,
STUDENT_COURSE tables for understanding nested queries.

STUDENT
S_ID S_NAME S_ADDRESS S_PHONE S_AGE
S1 RAM DELHI 9455123451 18

S2 RAMESH GURGAON 9652431543 18

S3 SUJIT ROHTAK 9156253131 20

S4 SURESH DELHI 9156768971 18

COURSE
C_ID C_NAME

C1 DSA

C2 Programming

C3 DBMS

STUDENT_COURSE
S_ID C_ID

S1 C1

S1 C3

S2 C1

S3 C2
S4 C2

S4 C3

There are mainly two types of nested queries:

• Independent Nested Queries: In independent nested queries, query


execution starts from innermost query to outermost queries. The
execution of inner query is independent of outer query, but the result
of inner query is used in execution of outer query. Various operators
like IN, NOT IN, ANY, ALL etc are used in writing independent nested
queries.

IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or
‘DBMS’, we can write it with the help of independent nested query and
IN operator. From COURSE table, we can find
out C_ID for C_NAME ‘DSA’ or DBMS’ and we can use these C_IDs for
finding S_IDs from STUDENT_COURSE TABLE.

STEP 1: Finding C_ID for C_NAME =’DSA’ or ‘DBMS’


Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’

STEP 2: Using C_ID of step 1 for finding S_ID


Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME = ‘DSA’
or C_NAME=’DBMS’);

The inner query will return a set with members C1 and C3 and outer
query will return those S_IDs for which C_ID is equal to any member of
set (C1 and C3 in this case). So, it will return S1, S2 and S4.
Note: If we want to find out names of STUDENTs who have either
enrolled in ‘DSA’ or ‘DBMS’, it can be done as:
Select S_NAME from STUDENT where S_ID IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’
or C_NAME=’DBMS’));

NOT IN: If we want to find out S_IDs of STUDENTs who have neither
enrolled in ‘DSA’ nor in ‘DBMS’, it can be done as:
Select S_ID from STUDENT where S_ID NOT IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’
or C_NAME=’DBMS’));

The innermost query will return a set with members C1 and C3. Second
inner query will return those S_IDs for which C_ID is equal to any
member of set (C1 and C3 in this case) which are S1, S2 and S4. The
outermost query will return those S_IDs where S_ID is not a member of
set (S1, S2 and S4). So it will return S3.

• Co-related Nested Queries: In co-related nested queries, the output of


inner query depends on the row which is being currently executed in
outer query. e.g.; If we want to find out S_NAME of STUDENTs who are
enrolled in C_ID ‘C1’, it can be done with the help of co-related nested
query as:
Select S_NAME from STUDENT S where EXISTS
( select * from STUDENT_COURSE SC where S.S_ID=SC.S_ID and
SC.C_ID=’C1’);

For each row of STUDENT S, it will find the rows


from STUDENT_COURSE where S.S_ID = SC.S_ID and SC.C_ID=’C1’. If
for a S_ID from STUDENT S, atleast a row exists
in STUDENT_COURSE SC with C_ID=’C1’, then inner query will return
true and corresponding S_ID will be returned as output
Control methods of Database Security
Database Security means to keep sensitive information safe and prevent
the loss of data. Security of data base is controlled by Database
Administrator (DBA).
The following are the main control measures are used to provide security of
data in databases:
1. Authentication
2. Access control
3. Inference control
4. Flow control
5. Database Security applying Statistical Method
6. Encryption
These are explained as following below.

1. Authentication :
Authentication is the process of confirmation that whether the user
log in only according to the rights provided to him to perform the
activities of data base. A particular user can login only up to his
privilege but he can’t access the other sensitive data. The privilege
of accessing sensitive data is restricted by using Authentication .
By using these authentication tools for biometrics such as retina
and figure prints can prevent the data base from
unauthorized/malicious users.
2. Access Control :
The security mechanism of DBMS must include some provisions for
restricting access to the data base by unauthorized users. Access
control is done by creating user accounts and to control login
process by the DBMS. So, that database access of sensitive data is
possible only to those people (database users) who are allowed to
access such data and to restrict access to unauthorized persons.
The database system must also keep the track of all operations
performed by certain user throughout the entire login time.
3. Inference Control :
This method is known as the countermeasures to statistical
database security problem.It is used to prevent the user from
completing any inference channel. This method protect the
sensitive information from indirect disclosure.
Inferences are of two types, identity disclosure or attribute
disclosure.
4. Flow Control :
This prevents information from flowing in a way that it reaches
unauthorized users. Channels are the pathways for information to
flow implicitly in ways that violate the privacy policy of a company
are called covert channels.
5. Database Security applying Statistical Method :
Statistical database security focuses on the protection of
confidential individual values stored in and used for statistical
purposes and used to retrieve the summaries of values based on
categories. They do not permit to retrieve the individual information.
This allows to access the database to get statistical information
about the number of employees in the company but not to access
the detailed confidential/personal information about specific
individual employee.
6. Encryption :
This method is mainly used to protect sensitive data (such as credit
card numbers, OTP numbers) and other sensitive numbers. The
data is encoded using some encoding algorithms.
An unauthorized user who tries to access this encoded data will
face difficulty in decoding it, but authorized users are given
decoding keys to decode data.

Challenges of database security in


DBMS
Seeing the vast increase in volume and speed of threats to databases and many
information assets, research efforts need to be consider to the following issues
such as data quality, intellectual property rights, and database survivability.
Let’s discuss them one by one.
1. Data quality –

• The database community basically needs techniques and some


organizational solutions to assess and attest the quality of data. These
techniques may include the simple mechanism such as quality stamps
that are posted on different websites. We also need techniques that will
provide us more effective integrity semantics verification tools for
assessment of data quality, based on many techniques such as record
linkage.
• We also need application-level recovery techniques to automatically
repair the incorrect data.
• The ETL that is extracted transform and load tools widely used for
loading the data in the data warehouse are presently grappling with
these issues.
2. Intellectual property rights –
As the use of Internet and intranet is increasing day by day, legal and
informational aspects of data are becoming major concerns for many
organizations. To address this concerns watermark technique are used which
will help to protect content from unauthorized duplication and distribution by
giving the provable power to the ownership of the content.
Traditionally they are dependent upon the availability of a large domain within
which the objects can be altered while retaining its essential or important
properties.
However, research is needed to access the robustness of many such techniques
and the study and investigate many different approaches or methods that aimed
to prevent intellectual property rights violation.
3. Database survivability –
Database systems need to operate and continued their functions even with the
reduced capabilities, despite disruptive events such as information warfare
attacks
A DBMS in addition to making every effort to prevent an attack and detecting one
in the event of the occurrence should be able to do the following:
• Confident:
We should take immediate action to eliminate the attacker’s access to
the system and to isolate or contain the problem to prevent further
spread.
• Damage assessment:
Determine the extent of the problem, including failed function and
corrupted data.
• Recover:
Recover corrupted or lost data and repair or reinstall failed function to
reestablish a normal level of operation.
• Reconfiguration:
Reconfigure to allow the operation to continue in a degraded mode
while recovery proceeds.
• Fault treatment:
To the extent possible, identify the weakness exploited in the attack
and takes steps to prevent a recurrence.
What is Stored Procedures in SQL ?
Stored Procedures are created to perform one or more DML operations on
Database. It is nothing but the group of SQL statements that accepts some input
in the form of parameters and performs some task and may or may not returns a
value.
Syntax : Creating a Procedure

CREATE or REPLACE PROCEDURE name(parameters)


IS
variables;
BEGIN
//statements;
END;
The most important part is parameters. Parameters are used to pass values to
the Procedure. There are 3 different types of parameters, they are as follows:
1. IN:
This is the Default Parameter for the procedure. It always receives the
values from calling program.
2. OUT:
This parameter always sends the values to the calling program.
3. IN OUT:
This parameter performs both the operations. It Receives value from as
well as sends the values to the calling program.
Example:
Imagine a table named with emp_table stored in Database. We are Writing a
Procedure to update a Salary of Employee with 1000.

CREATE or REPLACE PROCEDURE INC_SAL(eno IN NUMBER, up_sal OUT


NUMBER)
IS
BEGIN
UPDATE emp_table SET salary = salary+1000 WHERE emp_no = eno;
COMMIT;
SELECT sal INTO up_sal FROM emp_table WHERE emp_no = eno;
END;

• Declare a Variable to Store the value coming out from Procedure :

VARIABLE v NUMBER;

• Execution of the Procedure:

EXECUTE INC_SAL(1002, :v);



• To check the updated salary use SELECT statement:

SELECT * FROM emp_table WHERE emp_no = 1002;



• or Use print statement :

PRINT :v

Difference between Trigger and
Procedure in DBMS
1. Procedures :
A procedure is a combination of SQL statements written to perform a
specified tasks. It helps in code re-usability and saves time and lines of code.
2. Triggers :
A trigger is a special kind of procedure which executes only when some
triggering event such as INSERT, UPDATE, DELETE operations occurs in a
table.
Difference between Triggers and Procedures :
Triggers Procedures

A Procedure is explicitly called by


A Trigger is implicitly invoked whenever user/application using statements or commands
any event such as INSERT, DELETE, such as exec, EXECUTE, or simply
UPDATE occurs in a TABLE. procedure_name

Only nesting of triggers can be achieved


in a table. We cannot define/call a trigger We can define/call procedures inside another
inside another trigger. procedure.

In a database, syntax to define a trigger: In a database, syntax to define a procedure:


CREATE TRIGGER TRIGGER_NAME CREATE PROCEDURE PROCEDURE_NAME

Transaction statements such as


COMMIT, ROLLBACK, SAVEPOINT All transaction statements such as COMMIT,
are not allowed in triggers. ROLLBACK are allowed in procedures.

Triggers are used to maintain referencial


integrity by keeping a record of activities Procedures are used to perform tasks defined or
performed on the table. specified by the users.

We cannot return values in a trigger.


Also, as an input, we cannot pass values We can return 0 to n values. However, we can
as a parameter. pass values as parameters.

You might also like