Wa0007.
Wa0007.
com
Unit-2
Relational Model in DBMS
Relational model can represent as a table with columns and rows. Each row is known as a tuple. Each
table of the column has a name or attribute.
Attribute: It contains the name of a column in a particular table. Each attribute Ai must have a
domain, dom(Ai)
Relational instance: In the relational database system, the relational instance is represented by a
finite set of tuples. Relation instances do not have duplicate tuples.
Relational schema: A relational schema contains the name of the relation and name of all columns or
attributes.
Relational key: In the relational key, each row has one or more attributes. It can identify the row in
the relation uniquely.
o In the given table, NAME, ROLL_NO, PHONE_NO, ADDRESS, and AGE are the attributes.
o The instance of schema STUDENT has 5 tuples.
o t3 = <Laxman, 33289, 8583287182, Gurugram, 20>
Properties of Relations
o Name of the relation is distinct from all other relations.
o Each relation cell contains exactly one atomic (single) value
o Each attribute contains a distinct name
o Attribute domain has no significance
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.
1. Select Operation:
1. Notation: σ p(r)
Where:
Input:
1. σ BRANCH_NAME="perryride" (LOAN)
Output:
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 ∏.
Where
Input:
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
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:
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
Input:
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
Input:
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
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:
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)
Join Operations:
A Join operation combines related tuples from different relations, if and only if a given join condition
is satisfied. It is denoted by ⋈.
Example:
EMPLOYEE
EMP_CODE EMP_NAME
101 Stephan
102 Jack
103 Harry
SALARY
EMP_CODE SALARY
101 50000
102 30000
103 25000
Result
1. Natural Join:
o A natural join is the set of tuples of all combinations in R and S that are equal on their
common attribute names.
o It is denoted by ⋈.
Example: Let's use the above EMPLOYEE table and SALARY table:
Input:
Output:
EMP_NAME SALARY
Stephan 50000
Jack 30000
Harry 25000
2. Outer Join:
The outer join operation is an extension of the join operation. It is used to deal with missing
information.
Example:
EMPLOYEE
FACT_WORKERS
Input:
1. (EMPLOYEE ⋈ FACT_WORKERS)
Output:
o Left outer join contains the set of tuples of all combinations in R and S that are equal on their
common attribute names.
o In the left outer join, tuples in R have no matching tuples in S.
o It is denoted by ⟕.
Input:
1. EMPLOYEE ⟕ FACT_WORKERS
o Right outer join contains the set of tuples of all combinations in R and S that are equal on
their common attribute names.
o In right outer join, tuples in S have no matching tuples in R.
o It is denoted by ⟖.
Input:
1. EMPLOYEE ⟖ FACT_WORKERS
Output:
o Full outer join is like a left or right join except that it contains all rows from both tables.
o In full outer join, tuples in R that have no matching tuples in S and tuples in S that have no
matching tuples in R in their common attribute name.
o It is denoted by ⟗.
Input:
1. EMPLOYEE ⟗ FACT_WORKERS
Output:
3. Equi join:
It is also known as an inner join. It is the most common join. It is based on matched data as per the
equality condition. The equi join uses the comparison operator(=).
Example:
CUSTOMER RELATION
CLASS_ID NAME
1 John
2 Harry
3 Jackson
PRODUCT
PRODUCT_ID CITY
1 Delhi
2 Mumbai
3 Noida
Input:
1. CUSTOMER ⋈ PRODUCT
Output:
1 John 1 Delhi
2 Harry 2 Mumbai
3 Harry 3 Noida
Integrity Constraints
o Integrity constraints are a set of rules. It is used to maintain the quality of information.
o Integrity constraints ensure that the data insertion, updating, and other processes have to be
performed in such a way that data integrity is not affected.
o Thus, integrity constraint is used to guard against accidental damage to the database.
1. Domain constraints
o Domain constraints can be defined as the definition of a valid set of values for an attribute.
o The data type of domain includes string, character, integer, time, date, currency, etc. The
value of the attribute must be available in the corresponding domain.
Example:
o The entity integrity constraint states that primary key value can't be null.
o This is because the primary key value is used to identify individual rows in relation and if the
primary key has a null value, then we can't identify those rows.
o A table can contain a null value other than the primary key field.
Example:
Example:
4. Key constraints
o Keys are the entity set that is used to identify an entity within its entity set uniquely.
o An entity set can have multiple keys, but out of which one key will be the primary key. A
primary key can contain a unique and null value in the relational table.
Example:
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.
Many of the calculus expressions involves the use of Quantifiers. There are two types of
quantifiers:
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.
Notation:
Where
For example:
Output: This query selects the tuples from the AUTHOR relation. It returns a tuple with 'name' from
Author who has written an article on 'database'.
TRC (tuple relation calculus) can be quantified. In TRC, we can use Existential (∃) and Universal
Quantifiers (∀).
For example:
Output: This query will yield the same result as the previous one.
Notation:
Where
For example:
Output: This query will yield the article, page, and subject from the relational javatpoint, where the
subject is a database.
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
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
Item8 Com1 3 10 30
Item9 Com2 2 25 50
1. FROM PRODUCT_MAST;
Output:
10
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
Output:
Output:
Com1 5
Com2 3
Com3 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
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 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:
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;
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:
Built-in functions are sometimes referred to as individual registers. It can be used anywhere that a
literal can appear.
If a SELECT statement that contains a built-in function references a table name, then the result of the
query contains one row for every row of the table that satisfies the search condition.
Some common built-in functions are listed below with examples, such as
S. Function Example
No.
Important Rule:
o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause,
HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and
the inner query is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be
used to perform the same function as ORDER BY command.
Syntax
1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. ( SELECT column_name from table_name WHERE ... );
Example
1 John 20 US 2000.00
4 Alina 29 UK 6500.00
1. SELECT *
2. FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE
5. WHERE SALARY > 4500);
4 Alina 29 UK 6500.00
Syntax:
Example
Now use the following syntax to copy the complete EMPLOYEE table into the EMPLOYEE_BKP
table.
Syntax
1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);
Example
Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table.
The given example updates the SALARY by .25 times in the EMPLOYEE table for all employee
whose AGE is greater than or equal to 29.
1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
4. WHERE AGE >= 29);
This would impact three rows, and finally, the EMPLOYEE table would have the following records.
1 John 20 US 2000.00
4 Alina 29 UK 1625.00
Syntax
Example
Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE table.
The given example deletes the records from the EMPLOYEE table for all EMPLOYEE whose AGE
is greater than or equal to 29.
This would impact three rows, and finally, the EMPLOYEE table would have the following records.
1 John 20 US 2000.00
The following query finds employees whose salary is greater than the average salary of all employees:
SELECT
employee_id,
first_name,
last_name,
salary
FROM
employees
WHERE
In this example, the subquery is used in the WHERE clause. There are some points that you can see
from this query:
First, you can execute the subquery that returns the average salary of all employees independently.
SELECT
AVG(salary)
FROM
employees;
Code language: SQL (Structured Query Language) (sql)
Second, the database system needs to evaluate the subquery only once.
Third, the outer query makes use of the result returned from the subquery. The outer query depends on
the subquery for its value. However, the subquery does not depend on the outer query. Sometimes, we
call this subquery is a plain subquery.
Unlike a plain subquery, a correlated subquery is a subquery that uses the values from the outer query.
Also, a correlated subquery may be evaluated once for each row selected by the outer query. Because
of this, a query that uses a correlated subquery may be slow.
The following query finds all employees whose salary is higher than the average salary of the
employees in their departments:
SELECT
employee_id,
first_name,
last_name,
salary,
department_id
FROM
employees e
WHERE
salary > (SELECT
AVG(salary)
FROM
employees
WHERE
department_id = e.department_id)
ORDER BY
department_id ,
first_name ,
last_name;
Code language: SQL (Structured Query Language) (sql)
SELECT
employee_id,
first_name,
last_name,
salary,
department_id
FROM
employees e
WHERE
salary >
...
Code language: SQL (Structured Query Language) (sql)
SELECT
AVG( list_price )
FROM
products
WHERE
category_id = p.category_id
Code language: SQL (Structured Query Language) (sql)
For each employee, the database system has to execute the correlated subquery once to calculate the
average salary of the employees in the department of the current employee.
The following query returns the employees and the average salary of all employees in their
departments:
SELECT
employee_id,
first_name,
last_name,
department_name,
salary,
(SELECT
ROUND(AVG(salary),0)
FROM
employees
WHERE
department_id = e.department_id) avg_salary_in_department
FROM
employees e
INNER JOIN
departments d ON d.department_id = e.department_id
ORDER BY
department_name,
first_name,
last_name;
Code language: SQL (Structured Query Language) (sql)
For each employee, the database system has to execute the correlated subquery once to calculate the
average salary by the employee’s department.
We often use a correlated subquery with the EXISTS operator. For example, the following query
returns all employees who have no dependents:
SELECT
employee_id,
first_name,
last_name
FROM
employees e
WHERE
NOT EXISTS( SELECT
*
FROM
dependents d
WHERE
d.employee_id = e.employee_id)
ORDER BY first_name ,
last_name;
Code language: SQL (Structured Query Language) (sql)
In this tutorial, you have learned about the SQL correlated subquery and how to apply it to form a
complex query.
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG())
to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F
ADVERTISEMENT
The following SQL statement lists the number of customers in each country, sorted high to low:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Try it Yourself »
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
10248 90 5 1996-07-04
10249 81 6 1996-07-05
10250 34 4 1996-07-08
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate
functions.
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F
The following SQL statement lists the number of customers in each country. Only include countries
with more than 5 customers:
The following SQL statement lists the number of customers in each country, sorted high to low (Only
include countries with more than 5 customers):
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F
The following SQL statement lists the number of customers in each country, sorted high to low (Only
include countries with more than 5 customers):
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
ANY means that the condition will be true if the operation is true for any of the values in the range.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
ALL means that the condition will be true only if the operation is true for all values in the range.
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
1 Chais 1 1 10 boxes x
2 Chang 1 1 24 - 12 oz b
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
6 10250 41 10
7 10250 51 35
8 10250 65 15
9 10251 22 6
10 10251 57 15
ADVERTISEMENT
The following SQL statement lists the ProductName if it finds ANY records in the OrderDetails table
has Quantity larger than 99 (this will return TRUE because the Quantity column has some values
larger than 99):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 99);
Try it Yourself »
The following SQL statement lists the ProductName if it finds ANY records in the OrderDetails table
has Quantity larger than 1000 (this will return FALSE because the Quantity column has no values
larger than 1000):
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 1000);
The EXISTS operator returns TRUE if the subquery returns one or more records.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
1 Chais 1 1 10 boxes x 2
2 Chang 1 1 24 - 12 oz bo
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans
3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor
The following SQL statement returns TRUE and lists the suppliers with a product price equal to 22:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price = 22);
Table of Content:
1) What is View in SQL
2) Types of View in SQL
3) Syntax of View
4) Difference between Complex and Simple View
5) What is the purpose of SQL?
What is View in SQL: A view is a little over than a SQL declaration with a name that is saved in
the database. A view is essentially a table inside the form of a preset SQL query.
A view can include all of the rows in a table or only a subset of the rows in a table. A view could be
built from one or more tables, depending on the SQL query used to build the view.
Views, a form of the virtual table, enable users to achieve the following:
Data from several tables may be summarized and utilized to make reports.
Data should be structured in a way that consumers or groups of users find natural or simple.
Perspective on Dynamic Management: These were added to SQL Server in 2005. Through these
views, the administrator may obtain information about the server state in order to diagnose issues,
track the health of the test server, and modify performance. The Database-scoped Dynamic
Management View is saved in each database, but the Server-scoped Dynamic Management View is
only saved in the Master database.
The Information Schema database is an ANSI standard collection of views that may be found in
both SQL Server and MySQL. Other database management systems have either the same or
comparable database implementation. It gives key sectors to database and object information (tables,
restrictions, processes, views...) maintained on the client.
You might simply use this information to:
Examine the contents of the server and/or the database.
As a result, this database may be quite handy in some circumstances, particularly if you are in a DBA
job.
Automated processes and wrote some complicated code.
Examine to ensure that everything is as it should be.
View Catalog: These are employed to return data from the SQL server. Catalog views are a quick and
easy method to get, show, and alter custom types of information. Unfortunately, they do not provide
any detail on storage, duplicate, or maintenance plans, amongst many other things. Such views are
used to retrieve database metadata, and the names and field names are descriptive, making it easier for
a user to ask what is anticipated.
User-Defined Views: These are all the perspectives that users specify. User Defined Views are
classified into two kinds: Simple Views and Complex Views.
Indexed Views: An indexed view is created when you construct a distinct principal theme on a
consumer view. It increases query performance for queries that combine a large number of rows. They
are ineffective in situations when the data is regularly changed.
Syntax of View:
To construct data views, just use the Construct VIEW method. A single table, numerous tables, or
maybe another view can be used to construct a view. To build a view, a client must have the necessary
system rights for the selected project.
The fundamental syntax for CREATE VIEW is as tries to follow:
Simple View:
Contains just one base table or is made up of only one table.
DML operations might be carried out using a basic view.
Simple views do not have grouped by, distinct, pseudo columns like row num, or expression-defined
columns.
SQL (Structured Query Language) is a computer language that is used to store, alter, and retrieve
information from a database.
The database accepted practice is SQL. SQL is the database dialect that is used by all Relational
Database Management Systems (RDMS), including Oracle, MySQL, Sybase, MS Access, Informix,
Postgres, and SQL.
Now let us take a deeper dive into the TCL commands of SQL with the help of examples. All the
queries in the examples will be written using the MySQL database.
1. COMMIT
COMMIT command in SQL is used to save all the transaction-related changes permanently to the
disk. Whenever DDL commands such as INSERT, UPDATE and DELETE are used, the changes
made by these commands are permanent only after closing the current session. So before closing the
session, one can easily roll back the changes made by the DDL commands. Hence, if we want the
changes to be saved permanently to the disk without closing the session, we will use the commit
command.
Syntax:
1. COMMIT;
Example:
Now, we will execute the following query to insert multiple records at the same time in the t_school
table.
We will now execute the SELECT query to verify the execution of the INSERT INTO query executed
above.
After executing the SELECT query on the t_school table, you will get the following output:
The output of the SELECT query shows that all the records are inserted successfully.
We will execute the COMMIT command to save the results of the operations carried on the t_school
table.
1. mysql> COMMIT;
Autocommit is by default enabled in MySQL. To turn it off, we will set the value of autocommit as 0.
MySQL, by default, commits every query the user executes. But if the user wishes to commit only the
specific queries instead of committing every query, then turning off the autocommit is useful.
2. SAVEPOINT
We can divide the database operations into parts. For example, we can consider all the insert related
queries that we will execute consecutively as one part of the transaction and the delete command as
the other part of the transaction. Using the SAVEPOINT command in SQL, we can save these
different parts of the same transaction using different names. For example, we can save all the insert
related queries with the savepoint named INS. To save all the insert related queries in one savepoint,
we have to execute the SAVEPOINT query followed by the savepoint name after finishing the insert
command execution.
Syntax:
1. SAVEPOINT savepoint_name;
3. ROLLBACK
While carrying a transaction, we must create savepoints to save different parts of the transaction.
According to the user's changing requirements, he/she can roll back the transaction to different
savepoints. Consider a scenario: We have initiated a transaction followed by the table creation and
record insertion into the table. After inserting records, we have created a savepoint INS. Then we
executed a delete query, but later we thought that mistakenly we had removed the useful record.
Therefore in such situations, we have an option of rolling back our transaction. In this case, we have
to roll back our transaction using the ROLLBACK command to the savepoint INS, which we have
created before executing the DELETE query.
Syntax:
1. ROLLBACK TO savepoint_name;
Example 1:
Now, we will execute the following query to insert multiple records at the same time in the t_school
table.
We will now execute the SELECT query to verify the execution of the INSERT INTO query executed
above.
After executing the SELECT query on the t_school table, you will get the following output:
The output of the SELECT query shows that all the records are inserted successfully.
As we know, the SAVEPOINT command in SQL is used to save the different parts of the same
transaction using different names. Consider till this point as one part of our transaction. We will save
this part using a savepoint named Insertion.
Now, we will execute the update command on the t_school table to set the Number_Of_Students as
9050 for the record with ID 5.
To verify that the record with ID 5 now has the Number_Of_Students as 9050, we will execute the
SELECT query.
After executing the SELECT query on the t_school table, you will get the following output:
The output of the SELECT query shows that the record with ID 5 is updated successfully.
Consider the update operation as one part of our transaction. We will save this part using a savepoint
named Updation.
Suddenly, our requirement changed, and we realized that we had updated a record that was not
supposed to be. In such a scenario, we need to roll back our transaction to the savepoint, which was
created prior to the execution of the UPDATE command.
We didn't need the updation carried on the record. Hence, we have rolled back to the savepoint named
Insertion.
For confirming that we have got the same t_school table that we had before carrying out the updation
operation, we will again execute the SELECT query.
The SELECT query output confirms that the transaction is now successfully rolled back to the
savepoint 'Insertion'.
Example 2:
Now, we will execute the following query to insert multiple records at the same time in the customer
table.
We will now execute the SELECT query to verify the execution of the INSERT INTO query executed
above.
After executing the SELECT query on the t_school table, you will get the following output:
The output of the SELECT query shows that all the records are inserted successfully.
As we know, the SAVEPOINT command in SQL is used to save the different parts of the same
transaction using different names. Consider till this point as one part of our transaction. We will save
this part using a savepoint named Insertion.
We will execute the delete command on the customer table to remove the record with ID 5.
We will execute the SELECT query to verify that the record with ID 5 has been removed.
The output of the SELECT query shows that the record with ID 5 is removed successfully.
Consider the delete operation as one part of our transaction. We will save this part using a savepoint
named Deletion.
Suddenly, our requirement changed, and we realized that we had deleted a record that was not
supposed to be. In such a scenario, we need to roll back our transaction to the savepoint, which was
created prior to the execution of the DELETE command.
We didn't need the deletion carried on the record. Hence, we have rolled back to the savepoint named
Insertion.
For confirming that we have got the same customer table that we had before carrying out the deletion
operation, we will again execute the SELECT query.
The SELECT query output confirms that the transaction is now successfully rolled back to the
savepoint 'Insertion'.