Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 65

MEDICAPS UNIVERSITY

DBMS
th
4 sem Notes
Unit II:

Relational database
A relational database is a type of database that organizes
data into rows and columns, which collectively form a table
where the data points are related to each other.
Data is typically structured across multiple tables, which can be joined
together via a primary key or a foreign key. These unique identifiers
demonstrate the different relationships which exist between tables, and these
relationships are usually illustrated through different types of data models.
Analysts use SQL queries to combine different data points and summarize
business performance, allowing organizations to gain insights, optimize
workflows, and identify new opportunities.

For example, imagine your company maintains a database table with


customer information, which contains company data at the account level.
There may also be a different table, which describes all the individual
transactions that align to that account. Together, these tables can provide
information about the different industries that purchase a specific software
product.

The columns (or fields) for the customer table might be Customer
ID, Company Name, Company Address, Industry etc.; the columns for a
transaction table might be Transaction Date, Customer ID, Transaction
Amount, Payment Method, etc. The tables can be joined together with the
common Customer ID field. You can, therefore, query the table to produce
valuable reports, such as a sales reports by industry or company, which can
inform messaging to prospective clients.

Relational databases are also typically associated with transactional


databases, which execute commands, or transactions, collectively. A popular
example that is used to illustrate this is a bank transfer. A defined amount is
withdrawn from one account, and then it is deposited within another. The
total amount of money is withdrawn and deposited, and this transaction
cannot occur in any kind of partial sense. Transactions have specific
properties. Represented by the acronym, ACID, ACID properties are defined
as:

Atomicity:
By this, we mean that either the entire transaction takes place at
once or doesn’t happen at all. There is no midway i.e.
transactions do not occur partially. Each transaction is
considered as one unit and either runs to completion or is not
executed at all. It involves the following two operations.
—Abort: If a transaction aborts, changes made to the database
are not visible.
—Commit: If a transaction commits, changes made are visible.
Atomicity is also known as the ‘All or nothing rule’.

Consider the following transaction T consisting of T1 and T2:


Transfer of 100 from account X to account Y.
If the transaction fails after completion of T1 but before
completion of T2.( say, after write(X) but before write(Y)), then
the amount has been deducted from X but not added to Y. This
results in an inconsistent database state. Therefore, the
transaction must be executed in its entirety in order to ensure
the correctness of the database state.

Consistency:

This means that integrity constraints must be maintained so that


the database is consistent before and after the transaction. It
refers to the correctness of a database. Referring to the example
above,
The total amount before and after the transaction must be
maintained.
Total before T occurs = 500 + 200 = 700.
Total after T occurs = 400 + 300 = 700.
Therefore, the database is consistent. Inconsistency occurs in
case T1 completes but T2 fails. As a result, T is incomplete.

Isolation:
This property ensures that multiple transactions can occur
concurrently without leading to the inconsistency of the database
state. Transactions occur independently without interference.
Changes occurring in a particular transaction will not be visible
to any other transaction until that particular change in that
transaction is written to memory or has been committed. This
property ensures that the execution of transactions concurrently
will result in a state that is equivalent to a state achieved these
were executed serially in some order.
Let X= 500, Y = 500.
Consider two transactions T and T”.

Suppose T has been executed till Read (Y) and then T’’ starts.
As a result, interleaving of operations takes place due to
which T’’ reads the correct value of X but the incorrect value
of Y and sum computed by
T’’: (X+Y = 50, 000+500=50, 500)
is thus not consistent with the sum at end of the transaction:
T: (X+Y = 50, 000 + 450 = 50, 450).
This results in database inconsistency, due to a loss of 50 units.
Hence, transactions must take place in isolation and changes
should be visible only after they have been made to the main
memory.

Durability:

This property ensures that once the transaction has completed


execution, the updates and modifications to the database are
stored in and written to disk and they persist even if a system
failure occurs. These updates now become permanent and are
stored in non-volatile memory. The effects of the transaction,
thus, are never lost.
Some important points:
Property Responsibility for maintaining properties

Atomicity Transaction Manager

Consistency Application programmer

Isolation Concurrency Control Manager

Durability Recovery Manager

The ACID properties, in totality, provide a mechanism to ensure


the correctness and consistency of a database in a way such
that each transaction is a group of operations that acts as a
single unit, produces consistent results, acts in isolation from
other operations, and updates that it makes are durably stored.

ACID properties are the four key characteristics that define the
reliability and consistency of a transaction in a Database
Management System (DBMS). The acronym ACID stands for
Atomicity, Consistency, Isolation, and Durability. Here is a brief
description of each of these properties:
1. Atomicity: Atomicity ensures that a transaction is treated as a
single, indivisible unit of work. Either all the operations within
the transaction are completed successfully, or none of them
are. If any part of the transaction fails, the entire transaction
is rolled back to its original state, ensuring data consistency
and integrity.
2. Consistency: Consistency ensures that a transaction takes
the database from one consistent state to another consistent
state. The database is in a consistent state both before and
after the transaction is executed. Constraints, such as unique
keys and foreign keys, must be maintained to ensure data
consistency.
3. Isolation: Isolation ensures that multiple transactions can
execute concurrently without interfering with each other.
Each transaction must be isolated from other transactions
until it is completed. This isolation prevents dirty reads, non-
repeatable reads, and phantom reads.
4. Durability: Durability ensures that once a transaction is
committed, its changes are permanent and will survive any
subsequent system failures. The transaction’s changes are
saved to the database permanently, and even if the system
crashes, the changes remain intact and can be recovered.
Overall, ACID properties provide a framework for ensuring data
consistency, integrity, and reliability in DBMS. They ensure that
transactions are executed in a reliable and consistent manner,
even in the presence of system failures, network issues, or other
problems. These properties make DBMS a reliable and efficient
tool for managing data in modern organizations.

Advantages of ACID Properties in DBMS:


1. Data Consistency: ACID properties ensure that the data
remains consistent and accurate after any transaction
execution.
2. Data Integrity: ACID properties maintain the integrity of the
data by ensuring that any changes to the database are
permanent and cannot be lost.
3. Concurrency Control: ACID properties help to manage
multiple transactions occurring concurrently by preventing
interference between them.
4. Recovery: ACID properties ensure that in case of any failure
or crash, the system can recover the data up to the point of
failure or crash.

Disadvantages of ACID Properties in DBMS:

1. Performance: The ACID properties can cause a performance


overhead in the system, as they require additional processing
to ensure data consistency and integrity.
2. Scalability: The ACID properties may cause scalability issues
in large distributed systems where multiple transactions occur
concurrently.
3. Complexity: Implementing the ACID properties can increase
the complexity of the system and require significant expertise
and resources.
Overall, the advantages of ACID properties in DBMS
outweigh the disadvantages. They provide a reliable and
consistent approach to data
4. management, ensuring data integrity, accuracy, and
reliability. However, in some cases, the overhead of
implementing ACID properties can cause performance and
scalability issues. Therefore, it’s important to balance the
benefits of ACID properties against the specific needs and
requirements of the system.
Relational Algebra
Relational algebra is a procedural query language. It gives a step by
step process to obtain the result of the query. It uses operators to
perform queries.

Types of Relational operation

1. Select Operation:
o The select operation selects tuples that satisfy a given predicate.
o It is denoted by sigma (σ).

1. Notation: σ p(r)

Where:

σ is used for selection prediction


r is used for relation
p is used as a propositional logic formula which may use connectors
like: AND OR and NOT. These relational can use as relational operators
like =, ≠, ≥, <, >, ≤.
For example: LOAN Relation

BRANCH_NAME LOAN_N AMOUNT


O

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300

Input:

1. σ BRANCH_NAME="perryride" (LOAN)

Output:

BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

2. Project Operation:
o This operation shows the list of those attributes that we wish to
appear in the result. Rest of the attributes are eliminated from
the table.
o It is denoted by ∏.

1. Notation: ∏ A1, A2, An (r)

Where

A1, A2, A3 is used as an attribute name of relation r.

Example: CUSTOMER RELATION

NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn

Input:

1. ∏ NAME, CITY (CUSTOMER)

Output:
NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn

3. Union Operation:
o Suppose there are two tuples R and S. The union operation
contains all the tuples that are either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.

1. Notation: R ∪ S

A union operation must hold the following condition:

o R and S must have the attribute of the same number.


o Duplicate tuples are eliminated automatically.

Example:
DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO

Johnson A-101

Smith A-121

Mayes A-321

Turner A-176

Johnson A-273

Jones A-472

Lindsay A-284

BORROW RELATION

CUSTOMER_NAME LOAN_NO

Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11

Williams L-17
Input:

1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Johnson

Smith

Hayes

Turner

Jones

Lindsay

Jackson

Curry

Williams

Mayes

4. Set Intersection:
o Suppose there are two tuples R and S. The set intersection
operation contains all tuples that are in both R & S.
o It is denoted by intersection ∩.

1. Notation: R ∩ S

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_NAME (DEPOSITOR)

Output:

CUSTOMER_NAME

Smith

Jones

5. Set Difference:
o Suppose there are two tuples R and S. The set intersection
operation contains all tuples that are in R but not in S.
o It is denoted by intersection minus (-).

1. Notation: R - S

Example: Using the above DEPOSITOR table and BORROW table

Input:

1. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR)


Output:

CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

6. Cartesian product
o The Cartesian product is used to combine each row in one table
with each row in the other table. It is also known as a cross
product.
o It is denoted by X.

1. Notation: E X D

Example:
EMPLOYEE

EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B
DEPARTMENT

DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal

Input:

1. EMPLOYEE X DEPARTMENT

Output:

EMP_ID EMP_NAME EMP_DEPT DEPT_NO DEPT_NAME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales
3 John B C Legal

7. Rename Operation:
The rename operation is used to rename the output relation. It is
denoted by rho (ρ).

Example: We can use the rename operator to rename STUDENT


relation to STUDENT1.

1. ρ(STUDENT1, STUDENT)

Relational Calculus
There is an alternate way of formulating queries known as Relational
Calculus. 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. The relational calculus tells
what to do but never explains how to do. Most commercial relational
languages are based on aspects of relational calculus including SQL-
QBE and QUEL.

Why it is called Relational Calculus?


It is based on Predicate calculus, a name derived from branch of
symbolic language. A predicate is a truth-valued function with
arguments. On substituting values for the arguments, the function
result in an expression called a proposition. It can be either true or
false. It is a tailored version of a subset of the Predicate Calculus to
communicate with the relational database.
Many of the calculus expressions involves the use of Quantifiers.
There are two types of quantifiers:
ADVERTISEMENT

ADVERTISEMENT

o Universal Quantifiers: The universal quantifier denoted by ∀ is


read as for all which means that in a given set of tuples exactly all
tuples satisfy a given condition.
o Existential Quantifiers: The existential quantifier denoted by ∃
is read as for all which means that in a given set of tuples there is
at least one occurrences whose value satisfy a given condition.

Before using the concept of quantifiers in formulas, we need to know


the concept of Free and Bound Variables.

A tuple variable t is bound if it is quantified which means that if it


appears in any occurrences a variable that is not bound is said to be
free.

Free and bound variables may be compared with global and local
variable of programming languages.
Types of Relational calculus:

Tuple Relational Calculus (TRC) is a non-procedural query


language used in relational database management systems
(RDBMS) to retrieve data from tables. TRC is based on the
concept of tuples, which are ordered sets of attribute values that
represent a single row or record in a database table.
TRC is a declarative language, meaning that it specifies what
data is required from the database, rather than how to retrieve it.
TRC queries are expressed as logical formulas that describe the
desired tuples.
Syntax: The basic syntax of TRC is as follows:
{ t | P(t) }

where t is a tuple variable and P(t) is a logical formula that


describes the conditions that the tuples in the result must satisfy.
The curly braces {} are used to indicate that the expression is a
set of tuples.
For example, let’s say we have a table called “Employees” with
the following attributes:
Employee ID
Name

Salary

Department ID

To retrieve the names of all employees who earn more than


$50,000 per year, we can use the following TRC query:
{ t | Employees(t) ∧ t.Salary > 50000 }
In this query, the “Employees(t)” expression specifies that the
tuple variable t represents a row in the “Employees” table. The
“∧” symbol is the logical AND operator, which is used to combine
the condition “t.Salary > 50000” with the table selection.
The result of this query will be a set of tuples, where each tuple
contains the Name attribute of an employee who earns more
than $50,000 per year.
TRC can also be used to perform more complex queries, such
as joins and nested queries, by using additional logical operators
and expressions.
While TRC is a powerful query language, it can be more difficult
to write and understand than other SQL-based query languages,
such as Structured Query Language (SQL) . However, it is useful
in certain applications, such as in the formal verification of
database schemas and in academic research.
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 it.
Tuple Relational Query
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 a 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.

Domain Relational Calculus (DRC)


Domain Relational Calculus is similar to Tuple Relational
Calculus, where it makes a list of the attributes that are to be
chosen from the relations as per the conditions.
{<a1,a2,a3,.....an> | P(a1,a2,a3,.....an)}

where a1,a2,…an are the attributes of the relation and P is the


condition.

Tuple Relational Calculus Examples


Table Customer
Customer
name Street City

Saurabh A7 Patiala
Customer
name Street City

Mehak B6 Jalandhar

Sumiti D9 Ludhiana

Ria A5 Patiala

Table Branch
Branch
name Branch City

ABC Patiala

DEF Ludhiana

GHI Jalandhar

Table Account
Branch
Account number name Balance

1111 ABC 50000


Branch
Account number name Balance

1112 DEF 10000

1113 GHI 9000

1114 ABC 7000

Table Loan
Loan
number Branch name Amount

L33 ABC 10000

L35 DEF 15000

L49 GHI 9000

L98 DEF 65000

Table Borrower
Customer
name Loan number

Saurabh L33

Mehak L49

Ria L98

Table Depositor
Customer
name Account number

Saurabh 1111

Mehak 1113

Suniti 1114

Example 1: Find the loan number, branch, and amount of loans


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 a tuple variable.


Example 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

Example 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

Example 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

Difference between Tuple Relational Calculus (TRC)


and Domain Relational Calculus (DRC) :

S. Basis of Tuple Relational Calculus Domain Relational


No. Comparison (TRC) Calculus (DRC)

1. Definition The Tuple Relational The Domain Relational


Calculus (TRC) is used to Calculus (DRC) employs a
select tuples from a list of attributes from which
S. Basis of Tuple Relational Calculus Domain Relational
No. Comparison (TRC) Calculus (DRC)

relation. The tuples with to choose based on the


specific range values, tuples condition. It’s similar to
with certain attribute TRC, but instead of selecting
values, and so on can be entire tuples, it selects
selected. attributes.

In TRC, the variables In DRC, the variables


Representation
2. represent the tuples from represent the value drawn
of variables
specified relations. from a specified domain.

A domain is equivalent to
A tuple is a single element
column data type and any
3. Tuple/ Domain of relation. In database
constraints on the value of
terms, it is a row.
data.

This filtering variable uses This filtering is done based


4. Filtering
a tuple of relations. on the domain of attributes.

The predicate expression


DRC takes advantage of
condition associated with
domain variables and, based
the TRC is used to test
on the condition set, returns
5. Return Value every row using a tuple
the required attribute or
variable and return those
column that satisfies the
tuples that met the
criteria of the condition.
condition.

The query cannot be The query can be expressed


Membership
5. expressed using a using a membership
condition
membership condition. condition.

The QUEL or Query The QBE or Query-By-


Query
6. Language is a query Example is query language
Language
language related to it, related to it.
S. Basis of Tuple Relational Calculus Domain Relational
No. Comparison (TRC) Calculus (DRC)

It reflects traditional pre- It is more similar to logic as


7. Similarity
relational file structures. a modeling language.

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


8. Syntax
| Condition (T)} | P (a1, a2, a3, …, an)}

{T | EMPLOYEE (T) AND { | < EMPLOYEE >


9. Example
T.DEPT_ID = 10} DEPT_ID = 10 }

Focuses on selecting tuples Focuses on selecting values


10. Focus
from a relation from a relation

Uses scalar variables (e.g.,


11. Variables Uses tuple variables (e.g., t)
a1, a2, …, an)

12. Expressiveness Less expressive More expressive

Easier to use for simple More difficult to use for


13. Ease of use
queries. simple queries.

Useful for selecting tuples Useful for selecting specific


that satisfy a certain values or for constructing
14. Use case
condition or for retrieving a more complex queries that
subset of a relation. involve multiple relations.

Difference between Relational Algebra and Relational


Calculus:
Basis of
S.NO Comparison Relational Algebra Relational Calculus

Relational Calculus is a
Language Type It is a Procedural language. Declarative (non-procedural)
1. language.

Relational Algebra means Relational Calculus means what


Procedure
2. how to obtain the result. result we have to obtain.

In Relational Algebra, the


order is specified in which In Relational Calculus, the order
Order
the operations have to be is not specified.
3. performed.

Relation Calculus can be domain-


Relational Algebra is
Domain dependent because of domain
independent of the domain.
4. relational calculus.

Relational Calculus is not nearer


Programming Relational Algebra is nearer
to programming language but to
language to a programming language.
5. natural language.

The SQL includes only


Inclusion in SQL is based to a greater extent
some features from the
SQL on the tuple relational calculus.
6. relational algebra.

Relational Algebra is one of


the languages in which
For a database language to be
queries can be expressed but
Relationally relationally complete, the query
the queries should also be
completeness written in it must be expressible
expressed in relational
in relational calculus.
calculus to be relationally
7. complete.

8. Query The evaluation of the query The order of operations does not
Basis of
S.NO Comparison Relational Algebra Relational Calculus

relies on the order


specification in which the matter in relational calculus for
Evaluation
operations must be the evaluation of queries.
performed.

For accessing the database,


For accessing the database,
relational algebra provides a
relational calculus provides a
solution in terms of what is
Database access solution in terms as simple as
required and how to get that
what is required and lets the
information by following a
system find the solution for that.
9. step-by-step description.

The completeness of a language


is measured in the manner that it
The expressiveness of any is least as powerful as calculus.
given language is judged That implies relation defined
Expressiveness
using relational algebra using some expression of the
operations as a standard. calculus is also definable by
some other expression, the
10. language is in question.

SQL:

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.
SQL commands are like instructions to a table. It is used to
interact with the database with some operations. It is also used
to perform specific tasks, functions, and queries of data. SQL
can perform various tasks like creating a table, adding data to
tables, dropping the table, modifying the table, set permission for
users.
These SQL commands are mainly categorized into five
categories:
1. DDL – Data Definition Language
2. DQL – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL – Transaction Control Language
Now, we will see all of these in detail.

DDL:
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:
 CREATE: This command is used to create the database or
its objects (like table, index, function, views, store procedure,
and triggers).
 DROP: This command is used to delete objects from the
database.
 ALTER: This is used to alter the structure of the database.
 TRUNCATE: This is used to remove all records from a table,
including all spaces allocated for the records are removed.
 COMMENT: This is used to add comments to the data
dictionary.
 RENAME: This is used to rename an object existing in the
database.
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.
DDL Commands :
In this section, We will cover the following DDL commands as
follows.
1. Create
2. Alter
3. truncate
4. drop
5. Rename
Let’s discuss it one by one.
Command-1 :
CREATE :
This command is used to create a new table in SQL. The user
has to give information like table name, column names, and their
datatypes.
Syntax –
CREATE TABLE table_name
(
column_1 datatype,
column_2 datatype,
column_3 datatype,
....
);

Example –
We need to create a table for storing Student information of a
particular College. Create syntax would be as below.
CREATE TABLE Student_info
(
College_Id number(2),
College_name varchar(30),
Branch varchar(10)
);

Command-2 :
ALTER :
This command is used to add, delete or change columns in the
existing table. The user needs to know the existing table name
and can do add, delete or modify tasks easily.
Syntax –
Syntax to add a column to an existing table.
ALTER TABLE table_name
ADD column_name datatype;

Example –
In our Student_info table, we want to add a new column for
CGPA. The syntax would be as below as follows.
ALTER TABLE Student_info
ADD CGPA number;

Command-3 :
TRUNCATE :
This command is used to remove all rows from the table, but the
structure of the table still exists.
Syntax –
Syntax to remove an existing table.
TRUNCATE TABLE table_name;

Example –
The College Authority wants to remove the details of all students
for new batches but wants to keep the table structure. The
command they can use is as follows.
TRUNCATE TABLE Student_info;

Command-4 :
DROP :
This command is used to remove an existing table along with its
structure from the Database.
Syntax –
Syntax to drop an existing table.
DROP TABLE table_name;

Example –
If the College Authority wants to change their Database by
deleting the Student_info Table.
DROP TABLE Student_info;

Command -5
RENAME:
It is possible to change name of table with or without data in it
using simple RENAME command.
We can rename any table object at any point of time.
Syntax –
RENAME TABLE <Table Name> To <New_Table_Name>;

Example:
If you want to change the name of the table from Employee to
Emp we can use rename command as
RENAME TABLE Employee To EMP;

DML(Data Manipulation Language)


The SQL commands that deal 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.

Types of Data Manipulation Language


There are basically two types of Data Manipulation Language.
These are mentioned below. We have described them in the
difference between format.
1. High-Level or Non-Procedural DML
2. Low-Level or Procedural DML
High-Level or Non-Procedural DML vs Low-level or
Procedural DML
High-Level or Non-Procedural Low-level or
DML Procedural DML

It is also labelled as set-at-a-time or series It is also labelled as track-at-


oriented DML. a-time DML.
High-Level or Non-Procedural Low-level or
DML Procedural DML

It can be used on its own for precisely It must be integrated to a


specifying complex operations in the general-purpose
database. programming language.

It is prescriptive in nature. It is indispensable in nature.

It demands that a user must


It demands that a user must clearly state
clearly state which data is
which data is needed without clarifying how
needed and how to obtain
and when to obtain those data.
those data.

For Example: Every SQL statement is a For Example: DB2’s SQL


prescriptive command. PL, Oracle’s PL/SQL.

Characteristics of DML
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:

Following are the four main DML commands in SQL:

1. SELECT Command
2. INSERT Command
3. UPDATE Command
4. DELETE Command
SELECT DML Command
SELECT is the most important data manipulation command in
Structured Query Language. The SELECT command shows the records
of the specified table. It also shows the particular record of a particular
column by using the WHERE clause.

Syntax of SELECT DML command

1. SELECT column_Name_1, column_Name_2, ….., column_Name_N FRO


M Name_of_table;

Here, column_Name_1, column_Name_2, ….., column_Name_N are


the names of those columns whose data we want to retrieve from the
table.

If we want to retrieve the data from all the columns of the table, we
have to use the following SELECT command:

1. SELECT * FROM table_name;

Examples of SELECT Command


Example 1: This example shows all the values of every column
from the table.

1. SELECT * FROM Student;

This SQL statement displays the following values of the student table:

Student_ID Student_Name Student_Marks


BCA1001 Abhay 85

BCA1002 Anuj 75

BCA1003 Bheem 60

BCA1004 Ram 79

BCA1005 Sumit 80

Example 2: This example shows all the values of a specific column


from the table.

1. SELECT Emp_Id, Emp_Salary FROM Employee;

This SELECT statement displays all the values


of Emp_Salary and Emp_Id column of Employee table:

Emp_Id Emp_Salary

201 25000

202 45000

203 30000

204 29000
205 40000

Example 3: This example describes how to use the WHERE clause


with the SELECT DML command.

Let's take the following Student table:

Student_ID Student_Name Student_Marks

BCA1001 Abhay 80

BCA1002 Ankit 75

BCA1003 Bheem 80

BCA1004 Ram 79

BCA1005 Sumit 80

If you want to access all the records of those students whose marks is
80 from the above table, then you have to write the following DML
command in SQL:

1. SELECT * FROM Student WHERE Stu_Marks = 80;

The above SQL query shows the following table in result:


Student_ID Student_Name Student_Marks

BCA1001 Abhay 80

BCA1003 Bheem 80

BCA1005 Sumit 80

INSERT DML Command


INSERT is another most important data manipulation command in
Structured Query Language, which allows users to insert data in
database tables.

Syntax of INSERT Command

1. INSERT INTO TABLE_NAME ( column_Name1 , column_Name2 , colu


mn_Name3 , .... column_NameN ) VALUES (value_1, value_2, value_3, ..
.. value_N ) ;

Examples of INSERT Command


Example 1: This example describes how to insert the record in the
database table.

Let's take the following student table, which consists of only 2 records
of the student.

Stu_Id Stu_Name Stu_Marks Stu_Age


101 Ramesh 92 20

201 Jatin 83 19

Suppose, you want to insert a new record into the student table. For
this, you have to write the following DML INSERT command:

1. INSERT INTO Student (Stu_id, Stu_Name, Stu_Marks, Stu_Age) VALUE


S (104, Anmol, 89, 19);

UPDATE DML Command


UPDATE is another most important data manipulation command in
Structured Query Language, which allows users to update or modify
the existing data in database tables.

Syntax of UPDATE Command

1. UPDATE Table_name SET [column_name1= value_1, ….., column_name


N = value_N] WHERE CONDITION;

Here, 'UPDATE', 'SET', and 'WHERE' are the SQL keywords, and
'Table_name' is the name of the table whose values you want to
update.

Examples of the UPDATE command


Example 1: This example describes how to update the value of a
single field.
Let's take a Product table consisting of the following records:

Product_Id Product_Name Product_Price Product_Quantity

P101 Chips 20 20

P102 Chocolates 60 40

P103 Maggi 75 5

P201 Biscuits 80 20

P203 Namkeen 40 50

Suppose, you want to update the Product_Price of the product whose


Product_Id is P102. To do this, you have to write the following DML
UPDATE command:

1. UPDATE Product SET Product_Price = 80 WHERE Product_Id = 'P102'


;

Example 2: This example describes how to update the value of


multiple fields of the database table.

Let's take a Student table consisting of the following records:

Stu_Id Stu_Name Stu_Marks Stu_Age


101 Ramesh 92 20

201 Jatin 83 19

202 Anuj 85 19

203 Monty 95 21

102 Saket 65 21

103 Sumit 78 19

104 Ashish 98 20

Suppose, you want to update Stu_Marks and Stu_Age of that student


whose Stu_Id is 103 and 202. To do this, you have to write the
following DML Update command:

1. UPDATE Student SET Stu_Marks = 80, Stu_Age = 21 WHERE Stu_Id =


103 AND Stu_Id = 202;

DELETE DML Command


DELETE is a DML command which allows SQL users to remove single
or multiple existing records from the database tables.

This command of Data Manipulation Language does not delete the


stored data permanently from the database. We use the WHERE clause
with the DELETE command to select specific rows from the table.
Syntax of DELETE Command

1. DELETE FROM Table_Name WHERE condition;

Examples of DELETE Command


Example 1: This example describes how to delete a single record
from the table.

Let's take a Product table consisting of the following records:

Product_Id Product_Name Product_Price Product_Quantity

P101 Chips 20 20

P102 Chocolates 60 40

P103 Maggi 75 5

P201 Biscuits 80 20

P203 Namkeen 40 50

Suppose, you want to delete that product from the Product table
whose Product_Id is P203. To do this, you have to write the following
DML DELETE command:

1. DELETE FROM Product WHERE Product_Id = 'P202' ;


Example 2: This example describes how to delete the multiple
records or rows from the database table.

Let's take a Student table consisting of the following records:

Stu_Id Stu_Name Stu_Mark Stu_Age


s

101 Ramesh 92 20

201 Jatin 83 19

202 Anuj 85 19

203 Monty 95 21

102 Saket 65 21

103 Sumit 78 19

104 Ashish 98 20

Suppose, you want to delete the record of those students whose


Marks is greater than 70. To do this, you have to write the following
DML Update command:

1. DELETE FROM Student WHERE Stu_Marks > 70 ;


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

Triggers in SQL Server


A trigger is a set of SQL statements that reside in system memory with
unique names. It is a specialized category of stored procedure that is
called automatically when a database server event occurs. Each trigger
is always associated with a table.

A trigger is called a special procedure because it cannot be called


directly like a stored procedure. The key distinction between the
trigger and procedure is that a trigger is called automatically when a
data modification event occurs against a table. A stored procedure, on
the other hand, must be invoked directly.

The following are the main characteristics that distinguish triggers


from stored procedures:

o We cannot manually execute/invoked triggers.


o Triggers have no chance of receiving parameters.
o A transaction cannot be committed or rolled back inside a
trigger.

Syntax of Trigger
We can create a trigger in SQL Server by using the CREATE
TRIGGER statement as follows:

1. CREATE TRIGGER schema.trigger_name


2. ON table_name
3. AFTER {INSERT, UPDATE, DELETE}
4. [NOT FOR REPLICATION]
5. AS
6. {SQL_Statements}

The parameter descriptions of this syntax illustrate below:

schema: It is an optional parameter that defines which schema the


new trigger belongs to.

trigger_name: It is a required parameter that defines the name for the


new trigger.

table_name: It is a required parameter that defines the table name to


which the trigger applies. Next to the table name, we need to write the
AFTER clause where any events like INSERT, UPDATE, or DELETE could
be listed.

NOT FOR REPLICATION: This option tells that SQL Server does not
execute the trigger when data is modified as part of a replication
process.
SQL_Statements: It contains one or more SQL statements that are
used to perform actions in response to an event that occurs.

When we use triggers?


Triggers will be helpful when we need to execute some events
automatically on certain desirable scenarios. For example, we have a
constantly changing table and need to know the occurrences of
changes and when these changes happen. If the primary table made
any changes in such scenarios, we could create a trigger to insert the
desired data into a separate table.

Example of Trigger in SQL Server


Let us understand how we can work with triggers in the SQL Server.
We can do this by first creating a table named 'Employee' using the
below statements:

1. CREATE TABLE Employee


2. (
3. Id INT PRIMARY KEY,
4. Name VARCHAR(45),
5. Salary INT,
6. Gender VARCHAR(12),
7. DepartmentId INT
8. )

Next, we will insert some record into this table as follows:

1. INSERT INTO Employee VALUES (1,'Steffan', 82000, 'Male', 3),


2. (2,'Amelie', 52000, 'Female', 2),
3. (3,'Antonio', 25000, 'male', 1),
4. (4,'Marco', 47000, 'Male', 2),
5. (5,'Eliana', 46000, 'Female', 3)

We can verify the insert operation by using the SELECT statement. We


will get the below output:

1. SELECT * FROM Employee;

We will also create another table named 'Employee_Audit_Test' to


automatically store transaction records of each operation, such as
INSERT, UPDATE, or DELETE on the Employee table:

1. CREATE TABLE Employee_Audit_Test


2. (
3. Id int IDENTITY,
4. Audit_Action text
5. )

Now, we will create a trigger that stores transaction records of


each insert operation on the Employee table into the
Employee_Audit_Test table. Here we are going to create the insert
trigger using the below statement:

1. CREATE TRIGGER trInsertEmployee


2. ON Employee
3. FOR INSERT
4. AS
5. BEGIN
6. Declare @Id int
7. SELECT @Id = Id from inserted
8. INSERT INTO Employee_Audit_Test
9. VALUES ('New employee with Id = ' + CAST(@Id AS VARCHAR(10))
+ ' is added at ' + CAST(Getdate() AS VARCHAR(22)))
10. END

After creating a trigger, we will try to add the following record into the
table:

1. INSERT INTO Employee VALUES (6,'Peter', 62000, 'Male', 3)

If no error is found, execute the SELECT statement to check the audit


records. We will get the output as follows:

We are going to create another trigger to store transaction records


of each delete operation on the Employee table into the
Employee_Audit_Test table. We can create the delete trigger using the
below statement:

1. CREATE TRIGGER trDeleteEmployee


2. ON Employee
3. FOR DELETE
4. AS
5. BEGIN
6. Declare @Id int
7. SELECT @Id = Id from deleted
8. INSERT INTO Employee_Audit_Test
9. VALUES ('An existing employee with Id = ' + CAST(@Id AS VARCHA
R(10)) + ' is deleted at ' + CAST(Getdate() AS VARCHAR(22)))
10. END

After creating a trigger, we will delete a record from the Employee


table:

DELETE FROM Employee WHERE Id = 2;

If no error is found, it gives the message as below:

In both the triggers code, you will notice these lines:

1. SELECT @Id = Id from inserted


2. SELECT @Id = Id from deleted
Here inserted and deleted are special tables used by the SQL Server.
The inserted table keeps the copy of the row when you insert a new
row into the actual table. And the deleted table keeps the copy of the
row you have just deleted from the actual table.

Types of SQL Server Triggers


We can categorize the triggers in SQL Server in mainly three types:

1. Data Definition Language (DDL) Triggers


2. Data Manipulation Language (DML) Triggers
3. Logon Triggers

DDL Triggers
DDL triggers are fired in response to the DDL events, such as CREATE,
ALTER, and DROP statements. We can create these triggers at the
database level or server level, depending on the type of DDL events. It
can also be executed in response to certain system-defined stored
procedures that do DDL-like operations.

The DDL triggers are useful in the following scenario:

o When we need to prevent the database schema from changing


o When we need to audit changes made in the database schema
o When we need to respond to a change made in the database
schema

DML Triggers
DML triggers are fired in response to DML events like INSERT,
UPDATE, and DELETE statements in the user's table or view. It can also
be executed in response to DML-like operations performed by system-
defined stored procedures.

The DML triggers can be classified into two types:

o After Triggers
o Instead Of Triggers
After Triggers

After trigger fires, when SQL Server completes the triggering action
successfully, that fired it. Generally, this trigger is executed when a
table completes an insert, update or delete operations. It is not
supported in views. Sometimes it is known as FOR triggers.

We can classify this trigger further into three types:

1. AFTER INSERT Trigger


2. AFTER UPDATE Trigger
3. AFTER DELETE Trigger
Example: When we insert data into a table, the trigger associated with
the insert operation on that table will not fire until the row has passed
all constraints, such as the primary key constraint. SQL Server cannot
fire the AFTER trigger when the data insertion failed.

The following is illustration of the After Triggers syntax in SQL


Server:

1. CREATE TRIGGER schema_name.trigger_name


2. ON table_name
3. AFTER {INSERT | UPDATE | DELETE}
4. AS
5. BEGIN
6. -- Trigger Statements
7. -- Insert, Update, Or Delete Statements
8. END

Instead of Triggers
Instead of Trigger fires before SQL Server begins to execute the
triggering operation that triggered it. It means that no condition
constraint check is needed before the trigger runs. As a result, even if
the constraint check fails, this trigger will fire. It is the opposite of the
AFTER trigger. We can create the INSTEAD OF triggers on a table that
executes successfully but doesn't contain the table's actual insert,
update, or delete operations.

We can classify this trigger further into three types:

1. INSTEAD OF INSERT Trigger


2. INSTEAD OF UPDATE Trigger
3. INSTEAD OF DELETE Trigger

Example: When we insert data into a table, the trigger associated with
the insert operation on that table will fire before the data has passed
all constraints, such as the primary key constraint. SQL Server also fires
the Instead of Trigger if the data insertion fails.

The following is an illustration of the Instead of Triggers syntax in


SQL Server:

1. CREATE TRIGGER schema_name.trigger_name


2. ON table_name
3. INSTEAD OF {INSERT | UPDATE | DELETE}
4. AS
5. BEGIN
6. -- trigger statements
7. -- Insert, Update, or Delete commands
8. END

Logon Triggers
Logon triggers are fires in response to a LOGON event. The LOGON
event occurs when a user session is generated with an SQL Server
instance, which is made after the authentication process of logging is
completed but before establishing a user session. As a result, the SQL
Server error log will display all messages created by the trigger,
including error messages and the PRINT statement messages. If
authentication fails, logon triggers do not execute. These triggers may
be used to audit and control server sessions, such as tracking login
activity or limiting the number of sessions for a particular login.

Advantages of Triggers
The following are the advantages of using triggers in SQL Server:
o Triggers set database object rules and roll back if any change
does not satisfy those rules. The trigger will inspect the data and
make changes if necessary.
o Triggers help us to enforce data integrity.
o Triggers help us to validate data before inserted or updated.
o Triggers help us to keep a log of records.
o Triggers increase SQL queries' performance because they do not
need to compile each time they are executed.
o Triggers reduce the client-side code that saves time and effort.
o Triggers are easy to maintain.

Disadvantages of Triggers
The following are the disadvantages of using triggers in SQL Server:

o Triggers only allow using extended validations.


o Triggers are invoked automatically, and their execution is
invisible to the user. Therefore, it isn't easy to troubleshoot what
happens in the database layer.
o Triggers may increase the overhead of the database server.
o We can define the same trigger action for multiple user actions
such as INSERT and UPDATE in the same CREATE TRIGGER
statement.
o We can create a trigger in the current database only, but it can
reference objects outside the current database.
Cursors in SQL
A Cursor is a temporary memory that is allocated by the database
server at the time of performing the Data Manipulation Language
operations on a table, such as INSERT, UPDATE and DELETE etc. It
is used to retrieve and manipulate data stored in the SQL table.
In MySQL, you cannot declare a cursor directly outside of a stored
procedure or function. Cursors are generally declared within stored
procedures, functions, or blocks of SQL code in MySQL database.

Using cursors, we can perform multiple operations on each row of a


result set, with or without returning the original data.

Properties of Cursors

Following are the properties of MySQL Cursors −

 READ ONLY − We cannot update or modify any records in the


table using the MySQL cursors. We can just fetch and process
data from a table.
 Non-Scrollable − We can retrieve records from a table in a single
direction, i.e. from the first record or the last. We cannot move
backward or jump to a specific position within the result set.
 Asensitive Cursor − An asensitive cursor operates directly on the
actual data in the database, it does not create a copy of the
data. If any change is made to the data by other connections,
it can affect the data that the cursor is working with.
In addition to the Asensitive cursor there is another type known
as Insensitive Cursor. An insensitive cursor uses a temporary copy of
the data. Therefore, these cursors are insensitive (not affected) to
the changes that are made in the table.

Life Cycle of the Cursor

There are four steps to manage these cursors. Following diagram


illustrates the lifecycle of an SQL cursor −
Now, let us discuss the phases of life cycle of the cursor one-by-
one.

Declare Cursor Statement


In MySQL we can declare a cursor using the DECLARE statement
and associate it with a SELECT statement to retrieve records from a
database table.

However, this SELECT statement associated with a cursor does not


use the INTO clause, as it's purpose is to fetch and process rows
rather than assigning values to variables.

Syntax
Following is the syntax to declare a cursor in MySQL database −

DECLARE cursor_name CURSOR FOR select_statement;


Open Cursor Statement

After declaring a cursor in MySQL, the next step is to open the


cursor using the OPEN statement. It initializes the result-set,
allowing us to fetch and process rows from the associated SELECT
statement in the cursor.

Syntax
Following is the syntax to open a cursor in MySQL database −

OPEN cursor_name;
Fetch Cursor Statement

Then, we can use the FETCH statement to retrieve the current row
pointed by the cursor, and with each FETCH, the cursor moves to
the next row in the result set. This allows us to process each row
one by one.

Syntax
Following is the syntax to fetch a cursor in MySQL database −

FETCH cursor_name INTO variable_list;


Close Cursor Statement

Once all the rows are fetched, we must close the cursor to release
the memory associated with it. We can do this using the CLOSE
statement.

Syntax
Following is the syntax to close a cursor in MySQL database −

CLOSE cursor_name;

Example
In this example, let us see how to manage a cursor in a stored
procedure.

Assume we have created a table with the name CUSTOMERS using


the CREATE TABLE statement as follows −
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)

);
Now, let us insert some records into the CUSTOMERS table using
the INSERT statement as follows −
INSERT INTO CUSTOMERS VALUES
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),

(2, 'Khilan', 25, 'Delhi', 1500.00 ),

(3, 'Kaushik', 23, 'Kota', 2000.00 ),

(4, 'Chaitali', 25, 'Mumbai', 6500.00 );

Now, we will create a backup table named 'CUSTOMERS_BACKUP' to


store customer data −

CREATE TABLE CUSTOMERS_BACKUP (


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
PRIMARY KEY (ID)

);
Here, we are creating a stored procedure named FetchCustomers to
fetch customer names from the CUSTOMERS table and inserting
them one by one into the BACKUP table. We are using a cursor to
iterate through the rows and a handler to detect the end of the
result-set, ensuring all names are processed −

ensuring all names are processed −

DELIMITER //
CREATE PROCEDURE FetchCustomers()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE customer_id INT;
DECLARE customer_name VARCHAR(255);
DECLARE auto_id INT;

-- Declare cursor
DECLARE MY_CURSOR CURSOR FOR
SELECT id, name FROM CUSTOMERS;

-- Declare exit handler


DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

-- Open cursor
OPEN MY_CURSOR;

-- Fetch and insert rows


read_loop: LOOP
FETCH MY_CURSOR INTO customer_id, customer_name;
IF done = 1 THEN
LEAVE read_loop;
END IF;

-- Insert the fetched data into the backup table


INSERT INTO customers_backup VALUES (customer_id, customer_name);

-- Get the last auto-generated ID used in the insertion


SET auto_id = LAST_INSERT_ID();

END LOOP;

-- Close cursor
CLOSE MY_CURSOR;
END //
DELIMITER ;

Once we create the procedure successfully, we can execute it using


the CALL statement as shown below −

CALL FetchCustomers();

Verification
You can verify the contents of the CUSTOMERS_BACKUP table using
the SELECT statement as shown below −

SELECT * FROM CUSTOMERS_BACKUP;

The contents of the table would be −

ID NAME

1 Ramesh

2 Khilan

3 Kaushik

4 Chaitali

Difference between Cursor and Trigger:


S.NO Cursor Trigger

It is a pointer which is used to control


It is a program which gets executed in response to
1. the context area and also to go
occurrence of some events.
through the records in the database.

2. A cursor can be created within a A trigger cannot be created within a cursor.


trigger by writing the declare
S.NO Cursor Trigger

statement inside the trigger.

It gets created in response to


3. execution of SQL statement thus it is It is a previously stored program.
not previously stored.

The main function of the cursor is


The main function of trigger is to maintain the
4. retrieval of rows from the result set
integrity of the database.
one at a time (row by row).

A trigger is executed in response to a DDL


A cursor is activated and thus created
5. statement, DML statement or any database
in response to any SQL statement.
operation.

The main disadvantage of cursor is


The main disadvantage of trigger is that they are
that it uses more resources each time
6. hard to view which makes the debugging really
and thus results in network round
difficult.
trip.

You might also like