0% found this document useful (0 votes)
22 views76 pages

Advanced Structured Query Language

Uploaded by

Amanuel Kassa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
22 views76 pages

Advanced Structured Query Language

Uploaded by

Amanuel Kassa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 76

Sawla Polytechnic College

Module Title: Advanced Structured Query Language


Module code: EIS WDDBA4 M03 1123
Nominal duration: 100 Hours
• Introduction to the Module
• In this module, you will explore advanced SQL syntax and
functionalities that enable you to perform tasks such as aggregating
data, filtering results, joining multiple tables, and handling complex
queries.
• By the end of this module, you will have a comprehensive
understanding of advanced SQL techniques, equipping you with the
skills to efficiently manipulate and retrieve data from databases and
optimize query performance.
• This module covers the units:
Advanced SQL statement
SQL statements with functions
SQL statements with aggregation and filtering
Unit One: Advanced SQL statements
• This unit is developed to provide you the necessary information regarding the following content
• coverage and topics
• DBMS fundamentals
• Information-based database tools and equipment
• Functions of where clause
• Functions of order by clause
• Boolean operators
• Elimination of duplicated and null values
• Functions of join operator
• Functions of union operator
• Data control language
• Transaction control language
1.1. DBMS fundamentals
• A Database Management System (DBMS) is a software system that
allows users to create, define, manipulate and manage databases.
• It also manages security, data integrity and concurrency for
databases.
• The primary goal of a DBMS is to provide a way to store and retrieve
database information in convenient and efficient.
• The management system is important because without the existence
of some kind of rules and regulations it is not possible to maintain the
database.
• We have to select the particular attributes which should be included
in a particular table; the common attributes to create relationship
between two tables; if a new record has to be inserted or deleted
then which tables should have to be handled etc.
• These issues must be resolved by having some kind of rules to follow
in order to maintain the integrity of the database.
• Database systems are designed to manage large bodies of
information.
• Management of data involves both defining structures for storage of
information and providing mechanisms for the manipulation of
information.
• In addition, the database system must ensure the safety of the
information stored, despite system crashes or attempts at unauthorized
access.
• If data are to be shared among several users, the system must avoid
possible anomalous results.
• So Understanding the fundamentals of DBMS is crucial for anyone
working with databases, whether as a database administrator, data
analyst, or software developer.
• The following are common functions that a DBMS performs:
• 1. Data Organization: One of the primary functions of a DBMS is to
organize data in a structured manner.
• It provides a logical framework, known as a schema, which defines
the structure and relationships of the data.
• The schema includes tables, which consist of rows (records) and
columns (attributes). By organizing data into tables, DBMS ensures
data integrity, consistency, and easy access.
• 2. Data Retrieval: DBMS allows users to retrieve data from databases
using queries.
• Queries are written in a language called Structured Query Language
(SQL), which is a standard language for interacting with relational
databases.
• With SQL, users can specify the desired data, apply filters, join
multiple tables, and sort the results.
• DBMS optimizes query execution to ensure efficient retrieval of data.
• 3. Data Manipulation:
• DBMS enables users to manipulate data by performing various
operations such as inserting, updating, and deleting records.
• These operations ensure data consistency and integrity.
• DBMS also supports transactions, which are a set of operations that
are executed as a single unit.
• Transactions ensure that either all operations are successfully
completed, or none of them are applied, maintaining data integrity.

• 4. Data Security:
• DBMS provides mechanisms to ensure data security and access control.
• It allows administrators to define user roles and privileges, restricting unauthorized
access to sensitive data.
• DBMS also supports encryption techniques to protect data during transmission and
storage.
• 5. Data Integrity and Consistency:
• DBMS enforces data integrity rules to maintain the accuracy and consistency of data.
• It supports constraints such as primary keys, foreign keys, and unique constraints to
ensure data integrity.
• DBMS also provides mechanisms for data validation and error handling.
• 6. Data Backup and Recovery:
• DBMS offers features for data backup and recovery to protect against
data loss.
• It allows administrators to schedule regular backups and restore data
in case of system failures or disasters.
• This ensures the availability and reliability of data.
1.2. Database tools and equipment
• When it comes to managing and manipulating data effectively,
selecting the right database tools and equipment is crucial.
• The choice of tools and equipment should align with the specific
information requirements of your organization or project.
• This process involves considering various factors such as data volume,
complexity, security needs, performance requirements, and
scalability.
• To begin with, it is essential to assess the data volume and complexity
of your project.
• If you are dealing with large datasets or complex data structures, you
may need a robust database management system (DBMS) that can
handle the workload efficiently.
• In such cases, relational database management systems (RDBMS) like
Oracle or Microsoft SQL Server are commonly used due to their ability
to handle structured data and perform complex queries.
• your organization deals with sensitive or confidential data, you should
prioritize tools that offer robust security features such as encryption,
access controls, and auditing capabilities.
• Database systems like PostgreSQL and Microsoft SQL Server provide
advanced security features to protect your data from unauthorized
access or breaches.
• Performance requirements play a significant role in determining the
appropriate database tools and equipment.
• Scalability is also a crucial factor to consider, especially if your project is
expected to grow in terms of data volume or user base.
• Tools like Apache Cassandra or MongoDB are known for their ability to
handle massive amounts of data and provide horizontal scalability,
allowing you to add more servers to accommodate increasing demands.
• In this module, we will be using Microsoft SQL Server as the database
management system for learning and practicing advanced SQL
concepts.
• SQL Server is a popular and widely-used open_source relational
database management system that provides a robust and scalable
platform for storing, managing, and retrieving data.
• SQL Server offers a comprehensive set of features and functionalities
that make it an ideal choice for learning advanced SQL.
• It supports a wide range of SQL commands and syntax, allowing us to
explore and practice various advanced techniques effectively.
• Additionally, SQL Server has excellent performance and reliability,
making it suitable for handling large datasets and complex queries.
• By using Microsoft SQL Server, you will gain hands-on experience with
a real-world database management system.
• You will learn how to set up and configure SQL, create and manage
databases, tables, and indexes, and execute SQL queries to
manipulate and retrieve data.
• This practical experience will not only deepen your understanding of
advanced SQL concepts but also prepare you for real-world scenarios
where SQL is commonly used.
1.3. Functions of where clause
• Retrieving data from a table The SQL WHERE clause is used to filter the
results obtained by the DML statements such as SELECT, UPDATE and
DELETE etc.
• It is used to extract only those records that fulfill a specified condition.
• We can retrieve the data from a single table or multiple tables (after join
operation) using the WHERE clause.
• You can use SQL to retrieve the columns of a database table with the
SELECT statement.
• You can retrieve all columns, a single column, or several specific columns.
• It is then up to your programming language to display that data.
• Questions you may have include:
How do you retrieve all columns?
How do you retrieve a single column?
How do you retrieve some columns?
• You can write a query to retrieve all the elements in a database table
by using the SELECT statement and wildcard (*) indicator.
• Select * from table_name;
• Note: It is standard practice to add ";" at the end of your SQL query.
• The most common query from a database is to collect or retrieve all the elements in a
specific column of the database table.
• Select column_name from table_name;
• You can also retrieve data from several columns by separating the column names with
a comma.
• Select column_1, column_2, column_7 from table_name;
• Note: Do not place a comma after the last item in the list, because it will result in an
error message.
• WHERE clause with SELECT statement Typically, the SELECT statement is used to
retrieve data from a table.
• If we use the WHERE clause with the SELECT statement, we can filter the rows to be
retrieved based on a specific condition (or expression).
• Example: Assume we have created a table named CUSTOMERS in SQL
database using CREATE TABLE statement and inserted some values.
The table created is as shown below.
ID Name A ge Address Salary
1 T ila h u n 32 G ulele 200 0
2 K ebe de 25 A rada 150 0
3 C h e m d e sa 23 L e m ik ura 200 0
4 F ule a 25 K ality 650 0
5 K em al 27 Y e ka 850 0
6 M om ona 22 L a fto 450 0
7 T ible tse 24 B o le 10000
• In the following query, we are fetching the ID, NAME and SALARY
fields from the CUSTOMERS table for the records where the SALARY is
greater than 2000.
• Select ID, Name, Salary from customers where salary > 2000;
ID Name Salary
4 F ule a 650 0
5 K em al 850 0
6 M om ona 450 0
7 T ible tse 10000
• WHERE clause with UPDATE statement
• The UPDATE statement is used to modify the existing records in a
table. Using the SQL WHERE clause with the UPDATE statement, we
can update particular records. If the WHERE clause is not used, the
UPDATE statement would affect all the records of a table. Following is
the syntax.
• Example: by using the previous customers table, we are incrementing
the salary of the customer named Ramesh by 1000 by using the
WHERE clause along with the UPDATE statement
• Update customer set salary= salary + 1000 where Name= ‘Tilahun’;
• Comparison operators in the WHERE clause
• SQL Comparison Operators test whether two given expressions are
the same or not. These operators are used in SQL conditional
statements while comparing one expression with another and they
return a Boolean value which can be either TRUE or FALSE. The result
of an SQL comparison operation can be UNKNOWN when one or
another operand has its value as NULL.
• Here is a list of all the comparison operators available in SQL.
• Example: by using the previous customers table, we can write a query
with a comparison operator
• Select * from customers where age != 25;
ID Name A ge Address Salary
1 T ila h u n 32 G ulele 200 0
3 C h e m d e sa 23 L e m ik ura 200 0
5 K em al 27 Y e ka 850 0
6 M om ona 22 L a fto 450 0
7 T ible tse 24 B o le 10000
• Select * from customers where age >= 25;
1.4. Functions of order by clause

• The SQL ORDER BY clause is used to sort the data in either ascending
or descending order, based on one or more columns. This clause can sort
data by a single column or by multiple columns.
• Sorting by multiple columns can be helpful when you need to sort data
hierarchically, such as sorting by state, city, and then by the person's
name.
• ORDER BY is used with the SQL SELECT statement and is usually
specified after the WHERE, HAVING, and GROUP BY clauses.
• Following are the important points about ORDER BY Clause
• To sort the data in ascending order, we use the keyword ASC.
• To sort the data in descending order, we use the keyword DESC.
• In addition to sorting records in ascending order or descending
order, the ORDER BY clause can also sort the data in a database
table in a preferred order.
• Example: by using the previous product table
• Sort the products from highest to lowest price
 SELECT * FROM Products ORDER BY Price DESC;
• Sort the products from lowest to highest price
 SELECT * FROM Products ORDER BY Price ASC;
• Sort the products alphabetically by using Product name
SELECT * FROM Products ORDER BY Product_Name;
• Sort the products by Product Name in reverse order
 SELECT * FROM Products ORDER BY Product_Name DESC;
1.5. Boolean operators
• Boolean operators in SQL are logical operators used to combine or
manipulate conditions in a query.
Operator Description
ALL TRUE if all of the sub query values meet the condition
AND TRUE if all the condition separated by AND is true
ANY TRUE if any of the sub query values meet the condition
BETWEEN TRUE if the operand is within the range of comparisons
EXISTS TRUE if the sub query returns one or more records
IN TRUE if the operand is equal to one of a list of expressions
LIKE TRUE if the operand matches a pattern
NOT Displays a record if the condition(s) is NOT TRUE
OR TRUE if any of the conditions separated by OR is true
• Example: Assume we have created a table named CUSTOMERS in SQL
database using CREATE TABLE statement and inserted some values.
The table created is as shown below.
• ID Name A ge Address Salary
1 T ila h u n 32 G ulele 200 0
2 K ebe de 25 A rada 150 0
3 C h e m d e sa 23 L e m ik ura 200 0
4 F ule a 25 K ality 650 0
5 K em al 27 Y e ka 850 0
6 M om ona 22 L a fto 450 0
7 T ible tse 24 B o le 10000
• SQL ALL Operator The ALL operator:
Returns a Boolean value as a result
 Returns TRUE if ALL of the sub query values meet the condition
 It is used with SELECT, WHERE and HAVING statements
• ALL means that the condition will be true only if the operation is true
for all values in the range.
• ALL operator syntax
SELECT ALL column_name(s) FROM table_name WHERE condition;
• WHERE clause with AND, OR operators
• We can use AND and OR operators together in SQL to combine
multiple conditions in a WHERE clause to filter rows that meets the
specified criteria.
• The AND operator will make sure only those rows are filtered that
satisfy all the conditions and the OR operator will filter records that
satisfy any one of the specified conditions.
• However, this is only used when specifying one condition is not
enough to filter all the required rows.
• Following is the syntax for using the AND and OR operators in a
WHERE clause
WHERE (condition1 OR condition2) AND condition3;
• Example: by using the previous customers table, we are retrieving all
rows from the CUSTOMERS table based on some conditions.
• The parentheses control the order of evaluation so that the OR
operator is applied first, followed by the AND operator.
 Select * from customers where (age = 25 OR salary < 4500) AND
(name = 'Chemdesa' OR name = 'Momona');
• SQL ANY Operator The ANY operator:
• Returns a Boolean value as a result
• Returns TRUE if ANY of the sub query values meet the condition ANY
means that the condition will be true if the operation is true for any of the
values in the range.
• ANY operator 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 (=, <>, !=, >,
>=, <=).
• Example: in the following example if we want to retrieve name of the
customers whose salary is 2000, we can write this query
• SELECT Name FROM customers WHERE ID = ANY (SELECT ID FROM
customers WHERE salary=2000);
Name
Tilahun

Chemdesa
• SQL BETWEEN Operator
• The BETWEEN operator is a logical operator in SQL, that is used to retrieve the
data within a specified range.
• The retrieved values can be integers, characters, or dates.
• You can use the BETWEEN operator to replace a combination of "greater than
equal AND less than equal" conditions.
• SELECT column_name(s) FROM table_name WHERE column_name BETWEEN
value1 AND value2;
• Example: by using the previous customers table, we can write a query that will
display all customers whose age is between 20 and 30.
• Select * from customers where age between 20 and 30;
ID Name A ge Address Salary
2 K ebe de 25 A rada 150 0
3 C h e m d e sa 23 L e m ik ura 200 0
4 F ule a 25 K ality 650 0
5 K em al 27 Y e ka 850 0
6 M om ona 22 L a fto 450 0
7 T ible tse 24 B o le 10000

Example: by using the previous customers table, we can write a query


that will display all customers whose name starts between the a and g.
Select * from customers where name between ‘a’ and ‘g’;
ID Name A ge Address Salary
3 C h e m d e sa 23 L e m ik ura 200 0
4 F u le a 25 K ality 650 0
• NOT BETWEEN Operator
• The NOT BETWEEN operator in SQL works in exactly opposite to the
BETWEEN operator. This is used to retrieve the data which is not
present in the specified range.
• Example: Select * from customers where age not between 20 and 30;
ID Name A ge Address Salary
1 T ila h u n 32 G ulele 200 0
• SQL EXISTS Operator
• The EXISTS operator is used to test for the existence of any record in a
sub query. It returns TRUE if the sub query returns one or more
records.
• EXISTS operator Syntax
• SELECT column_name(s) FROM table_name WHERE EXISTS (SELECT
column_name FROM table_name WHERE condition);
• WHERE clause with IN operator Using the IN operator you can specify
the list of values or sub query in the where clause.
• If you use WHERE and IN with the SELECT statement, it allows us to
retrieve the rows in a table that match any of the values in the
specified list.
• Following is the syntax for it Example: by using the previous
customers table, suppose you want to display records with NAME
values Khilan, Hardik and Muffy from the CUSTOMERS table, you can
use the following query
• Select * from customers where name in (‘Tilahun', 'Chemdesa', 'momona');
ID Name A ge Address Salary
1 T ila h u n 32 G ulele 300 0
3 C h e m d e sa 23 L e m ik ura 200 0
6 M om ona 22 L a fto 450 0

• WHERE clause with NOT IN operator The WHERE clause with NOT IN
operator is the negation of WHERE clause with the IN operator.
• If you use WHERE with the IN operator, the DML statement will act on the
list of values (of a column) specified
• Whereas, if you use WHERE with the NOT IN operator, the DML operation is
performed on the values (of a column) that are not there in the specified list
• Example: by using the previous customers table, we are displaying the
records from CUSTOMERS table, where AGE is NOT equal to 25, 23
and 22.
• Select * from customers where age NOT IN (25, 23, 22);
ID Name A ge Address Salary
1 T ila h u n 32 G ulele 200 0
5 K em al 27 Y e ka 850 0
7 T ible tse 24 B o le 10000
• SQL LIKE Operator
• The LIKE operator is used in a WHERE clause to search for a specified
pattern in a column.
• There are two wildcards often used in conjunction with the LIKE
operator:
• The percent sign % represents zero, one, or multiple characters
• The underscore sign _ represents one, single character LIKE operator
syntax
• SELECT column1, column2, ... FROM table_name WHERE columnN LIKE
pattern;
• Example: by using the previous customers table, we can write a query
which would display all the records where the name starts with K and
is at least 3 characters in length
• Select * from customers where name LIKE 'K__%';
ID Name A ge Address Salary
2 K ebe de 25 A rada 150 0
5 K em al 27 Y e ka 850 0
• SQL NOT Operator
• The NOT operator is used in combination with other operators to give
the opposite result, also called the negative result.
• NOT operator syntax
SELECT column1, column2, ... FROM table_name WHERE NOT
condition;
1.6. Elimination of duplicated and
null values
• Duplicated values Duplicates can be a big problem in SQL databases
as they can slow down query performance and waste valuable storage
space.
• When the result set from a SELECT statement contains duplicate rows,
you may want to remove them and keep every row data to be unique
for a column or combination of columns.
• You can use the DISTINCT identifier to eliminate duplicate records
from the result set. Consider the following facts when using DISTINCT
identifier in a SELECT statement:
• In a SELECT statement, include DISTINCT keyword after the SELECT
clause.
• Multiple columns can be specified after DISTINCT keyword.
• In this case, the result set contains distinct combination of data from
these columns.
• DISTINCT keyword syntax
• SELECT DISTINCT column1, column2, ... FROM table_name;
• Null Value
• A null value indicates no value. It means that the column value is
absent in a row. A null value is not the same as a blank space or a zero
value.
• A zero value is an integer and a blank space is a character while a null
value is the one that has been left blank.
• To exclude the null values from a table we need to use IS NOT NULL
operator with the WHERE clause.
• IS NOT NULL Operator is used to test for non-empty values.
• IS NOT NULL operator syntax:
• SELECT column_names FROM table_name WHERE column_name IS
NOT NULL;
1.7. Functions of join operator
• A JOIN clause is used to combine rows from two or more tables,
based on a related column between them.
• The INNER JOIN keyword selects records that have matching values in
both tables.
• It is the most common type of join.
• Inner joins combine records from two tables whenever there are
matching values in a field common to both tables.
• Inner Join clause in SQL Server creates a new table (not physical) by
combining rows that have matching values in two or more tables.
• This join is based on a logical relationship (or a common field)
between the tables and is used to retrieve data that appears in both
tables.
• INNER JOIN operator syntax
• SELECT column_name(s) FROM table1 INNER JOIN table2 ON
table1.column_name = table2.column_name;
• SQL LEFT JOIN Keyword
• The LEFT JOIN keyword returns all records from the left table (table1),
and the matching records from the right table (table2).
• select Employee.Empname,Job_position.jop_title,
• Job_position.salary,Department.DepName from
• Employee inner join Job_position on
Job_position.job_id=Employee.job_id
• inner join Department on Job_position.DepId=Department.DepId
• Insert data to all tables
• Write a Query that displays employee name, job title, salary and department name of
female employee
• Display employees whose date of birth is less than 1995 and greater than 1987 and who
works in systemadmin
• Update the salary of employee by adding 1000 which salary is below 4000
• Display employees id ,name,department name and salary and display the result in
descending order of salary
• Retrieve the list of department with job position where salary is greater than or equal to
5000?
• write a query which would display all the employee records where the name starts with M
and is at least 7 characters in length
• solution
• 4 select Employee.Empname,Job_position.jop_title,
• Job_position.salary,Department.DepName from
• Employee inner join Job_position on Job_position.job_id=Employee.job_id
• inner join Department on Job_position.DepId=Department.DepId where sex='F'
• 5 SELECT * FROM Employee WHERE BDate BETWEEN '1987/07/16' and'1995/08/20';
• 6 update Job_position set salary=salary+1000 where salary<4000
• 7 select Employee.empId,Department.DepName,
• Job_position.salary from Employee inner join Job_position
• on Job_position.job_id= Employee.job_id inner join Department
• on Department.DepId=Job_position.DepId order by salary desc
• 8 SELECT DepName FROM Department WHERE DepId = ANY(SELECT DepId FROM Job_position
WHERE salary>=5000);
• 9 Select * from Employee where Empname LIKE ‘m______%';
• The result is 0 records from the right side, if there is no match.
• LEFT JOIN keyword syntax
• SELECT column_name(s) FROM table1 LEFT JOIN table2 ON
table1.column_name = table2.column_name;
• Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.

• Figure 1.1. Left Join


• SQL RIGHT JOIN Keyword
• The RIGHT JOIN keyword returns all records from the right table
(table2), and the matching records from the left table (table1). The
result is 0 records from the left side, if there is no match.
• RIGHT JOIN Syntax
• SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON
table1.column_name = table2.column_name;
• Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
• Figure 1.2. Right Join
• SQL FULL OUTER JOIN Keyword
• The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.
• Tip: FULL OUTER JOIN and FULL JOIN are the same. FULL OUTER JOIN Syntax
• SELECT column_name(s)
• FROM table1 FULL OUTER JOIN table2
• ON table1.column_name = table2.column_name WHERE condition;
• Figure 1.3. Full outer Join
• Note: FULL OUTER JOIN can potentially return very large result-sets!

•t
1.8. Functions of union operator
• The UNION operator is used to combine the result-set of two or more SELECT
statements.
• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order
• UNION operator syntax
• SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM
table2;
• UNION operator with where clause syntax
• SELECT column_name(s) FROM table1 WHERE condition1 UNION SELECT
column_name(s) FROM table2 WHERE condition2
1.9. Data control language
• DCL stands for Data Control Language in Structured Query Language
(SQL).
• As the name suggests these commands are used to control privilege
in the database.
• The privileges (Right to access the data) are required for performing
all the database operations like creating tables, views, or sequences.
• DCL command is a statement that is used to perform the work related
to the rights, permissions, and other control of the database system.
• Need Of DCL commands
• Unauthorized access to the data should be prevented in order to
achieve security in our database
• DCL commands maintain the database effectively than anyone else
other than database administrator is not allowed to access the data
without permission.
• These commands provide flexibility to the data administrator to set
and remove database permissions in granular fashion.
• GRANT This command is used to grant permission to the user to
perform a particular operation on a particular object.
• If you are a database administrator and you want to restrict user
accessibility such as one who only views the data or may only update
the data.
• You can give the privilege permission to the users according to your
wish.
• Syntax:
• GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER,
ANOTHER_USER;
• REVOKE This command is used to take permission/access back from
the user.
• If you want to return permission from the database that you have
granted to the users at that time you need to run REVOKE command.
• Syntax:
• REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
1.10. Transaction control language
• Transactions group a set of tasks into a single execution unit.
• Each transaction begins with a specific job and ends when all the tasks in the
group successfully completed.
• If any of the tasks fail, the transaction fails. Therefore, a transaction has only
two results: success or failure.
• BEGIN: Incomplete steps result in the failure of the transaction.
• A database transaction, by definition, must be atomic, consistent, isolated,
and durable.
• These are popularly known as ACID properties.
• These properties can ensure the concurrent execution of multiple transactions
without conflict.
• Properties of Transaction
• Atomicity: The outcome of a transaction can either be completely
successful or completely unsuccessful. The whole transaction must be
rolled back if one part of it fails.
• Consistency: Transactions maintain integrity restrictions by moving
the database from one valid state to another.
• Isolation: Concurrent transactions are isolated from one another,
assuring the accuracy of the data.
• Durability: Once a transaction is committed, its modifications remain
in effect even in the event of a system failure.
• 1. COMMIT This command is used to save the data permanently. Whenever
we perform any of the DML command like -INSERT, DELETE or UPDATE, these
can be rollback if the data is not stored permanently. So, in order to be at the
safer side COMMIT command is used.  Syntax: commit;
• 2. ROLLBACK This command is used to get the data or restore the data to the
last savepoint or last committed state. If due to some reasons the data
inserted, deleted or updated is not correct, you can roll back the data to a
particular savepoint or if savepoint is not done, then to the last committed
state.  Syntax: rollback;
• 3. SAVEPOINT This command is used to save the data at a particular point
temporarily, so that whenever needed can be rollback to that particular point.
 Syntax: Savepoint A;
• Example: Consider the following student table

• UPDATE STUDENT SET NAME = ‘Sherlock’ WHERE NAME = ‘Jolly’;


• COMMIT;
• ROLLBACK;
• By using the above command, you can update the record and save it
permanently by using COMMIT command.
• Now after COMMIT:

• If commit was not performed then the changes made by the update
command can be rollback. Now if no COMMIT is performed.
• UPDATE STUDENT SET NAME = ‘Sherlock’ WHERE STUDENT_NAME = ‘Jolly’;
• After update command the table will be:

• Now if ROLLBACK is performed on the above table:


• rollback;
• After Rollback:
• If on the above table savepoint is performed:
• INSERT into STUDENT VALUES ('Jack', 95);
• Commit;
• UPDATE NAME SET NAME= ‘Rossie’ WHERE marks= 70;
• SAVEPOINT A;
• INSERT INTO STUDENT VALUES (‘Zack’, 76);
• SAVEPOINT B;
• INSERT INTO STUDENT VALUES (‘Bruno’, 85);
• SAVEPOINT C;
• SELECT * FROM STUDENT;
• Now if we Rollback to SAVEPOINT B: Rollback to B;
• The resulting Table will be-
• Now if we Rollback to SAVEPOINT A: Rollback to A;
• The resulting Table will be-

You might also like