0% found this document useful (0 votes)
42 views23 pages

Extra Material of DBMS For Students

A transaction is a unit of work performed against a database that ensures data integrity. Transactions have properties like atomicity, consistency, isolation, and durability. SQL uses commands like COMMIT, ROLLBACK, and SAVEPOINT to control transactions. COMMIT saves changes, ROLLBACK undoes changes, and SAVEPOINT allows rolling back to a point in a transaction without rolling back the entire transaction.

Uploaded by

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

Extra Material of DBMS For Students

A transaction is a unit of work performed against a database that ensures data integrity. Transactions have properties like atomicity, consistency, isolation, and durability. SQL uses commands like COMMIT, ROLLBACK, and SAVEPOINT to control transactions. COMMIT saves changes, ROLLBACK undoes changes, and SAVEPOINT allows rolling back to a point in a transaction without rolling back the entire transaction.

Uploaded by

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

SQL - Transactions

A transaction is a unit of work that is performed against a database. Transactions are units or
sequences of work accomplished in a logical order, whether in a manual fashion by a user or
automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example,
if you are creating a record or updating a record or deleting a record from the table,
then you are performing a transaction on that table. It is important to control these
transactions to ensure the data integrity and to handle database errors.
Practically, you will club many SQL queries into a group and you will execute all of them
together as a part of a transaction.

Properties of Transactions
Transactions have the following four standard properties, usually referred to by the acronym
ACID.
 Atomicity − ensures that all operations within the work unit are completed
successfully. Otherwise, the transaction is aborted at the point of failure and all the
previous operations are rolled back to their former state.
 Consistency − ensures that the database properly changes states upon a successfully
committed transaction.
 Isolation − enables transactions to operate independently of and transparent to each
other.
 Durability − ensures that the result or effect of a committed transaction persists in
case of a system failure.

Transaction Control
The following commands are used to control transactions.
 COMMIT − to save the changes.
 ROLLBACK − to roll back the changes.
 SAVEPOINT − creates points within the groups of transactions in which to ROLLBACK.
 SET TRANSACTION − Places a name on a transaction.

Transactional Control Commands


Transactional control commands are only used with the DML Commands such as - INSERT,
UPDATE and DELETE only. They cannot be used while creating tables or dropping them
because these operations are automatically committed in the database.
The COMMIT Command
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.
The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database. The COMMIT command saves all the transactions to the
database since the last COMMIT or ROLLBACK command.
The syntax for the COMMIT command is as follows.
COMMIT;

Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example which would delete those records from the table which have age =
25 and then COMMIT the changes in the database.
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> COMMIT;

Thus, two rows from the table would be deleted and the SELECT statement would produce
the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The ROLLBACK Command
The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database. This command can only be used to undo
transactions since the last COMMIT or ROLLBACK command was issued.
The syntax for a ROLLBACK command is as follows −
ROLLBACK;

Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would delete those records from the table which have the age
= 25 and then ROLLBACK the changes in the database.
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> ROLLBACK;

Thus, the delete operation would not impact the table and the SELECT statement would
produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The SAVEPOINT Command
A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain
point without rolling back the entire transaction.
The syntax for a SAVEPOINT command is as shown below.
SAVEPOINT SAVEPOINT_NAME;

This command serves only in the creation of a SAVEPOINT among all the transactional
statements. The ROLLBACK command is used to undo a group of transactions.
The syntax for rolling back to a SAVEPOINT is as shown below.
ROLLBACK TO SAVEPOINT_NAME;

Following is an example where you plan to delete the three different records from the
CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can
ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state.
Example
Consider the CUSTOMERS table having the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

The following code block contains the series of operations.


SQL> SAVEPOINT SP1;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
SQL> SAVEPOINT SP2;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
SQL> SAVEPOINT SP3;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.
Now that the three deletions have taken place, let us assume that you have changed your
mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2
was created after the first deletion, the last two deletions are undone −
SQL> ROLLBACK TO SP2;
Rollback complete.

Notice that only the first deletion took place since you rolled back to SP2.
SQL> SELECT * FROM CUSTOMERS;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
6 rows selected.

The RELEASE SAVEPOINT Command


The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have
created.
The syntax for a RELEASE SAVEPOINT command is as follows.
RELEASE SAVEPOINT SAVEPOINT_NAME;

Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to
undo transactions performed since the last SAVEPOINT.

**QUERY AND SUBQUERY

A sub query is a query within a query.

A subquery is a form of an SQL statement that appears inside another SQL statement. It is
also called nested query.

Inner query executes first then the outer query executes.

Main / Outer query is called Parent query. Sub / Inner query is called Child query. The
parent query uses the rows returned by the child query i.e. subquery.

Subquery can be used to:


1. Insert records in target table
2. Create tables and insert records in created tables
3. Update records in target table
4. Create views
5. Provide values for conditions in WHERE, HAVING, IN and so on used with SELECT,
UPDATE and DELETE statement

A subquery is usually added within the WHERE Clause of another SQL SELECT statement.

User can use the comparison operators such as >, <, or =. The comparison operator can also
be a multiple-row operator, such as IN, ANY, or ALL.

*TYPES OF SUBQUERY

1. Single-Row Subquery Returns zero or one row

2. Multiple-Row Subquery Returns one or more rows

3. Multiple column subquery Returns one or more columns

4. Correlated Subquery A subquery becomes correlated subquery when the


subquery references a column from a table in the
parent query.
A correlated subquery is evaluated once for each

row processed by the parent statement. Parent


statement can be SELECT, UPDATE or DELETE.

5. Nested subqueries Subqueries are placed within another subqueries.

1. SINGLE-ROW SUBQUERY

Single-Row Subquery returns only one row from inner query. Single-Row

Subquery uses Single-Row operator like >, <, >=, <=, <>, !=, = Most commonly

used single row operator is =. Example:

To select all employees who are working in same department in which ALLEN is working

SELECT * FROM EMP


WHERE DEPTNO = (SELECT DEPTNO FROM EMP WHERE ENAME = 'ALLEN');
The sub query retrieves only one value (the department number in which ALLEN is working).

Note: This query may fail if EMP table has more than one employee having name ALLEN.

To select all employees who earn more than FORD.

SELECT * FROM EMP


WHERE SAL > (SELECT SAL FROM EMP WHERE ENAME = 'FORD');

The sub query retrieves only one value (the salary of FORD).

2. MULTIPLE-ROW SUBQUERY

Multiple-Row Subquery returns more than one row from inner query.

Multiple-Row Subquery uses Multiple-Row operators like IN, ANY, ALL

If you use IN, ANY, or ALL, the subquery may return several rows, but only one column.
If you use single row operators, the subquery must return a single value.

Subquery using IN, ANY, ALL

A condition in the where clause can have one of the following forms:

SYNTAX < expression > [ not ] in ( < subquery > )


< expression > < comparison operator > [ ANY | ALL ] ( < subquery > )

An <expression> can either be a column or a computed value.

Example of IN operator - to select all the employees whose salary is same as the salary of
WARD or FORD.
SELECT * FROM EMP
WHERE SAL IN (SELECT SAL FROM EMP WHERE ENAME IN (‘WARD’,’FORD’) );
The sub query retrieves two values (the salary of WARD and FORD).

Note: As long as the result of a subquery is not known in advance, i.e., whether it is a single
value or a multiple value, it is advisable to use the IN operator.

ANY / ALL

Conditions of the form <expression> <comparison operator> [any | all] <subquery> are
used to compare a given <expression> with each value selected by <subquery>.

Clause ANY and ALL are used with any relational operator except =.

• ANY means any one of the value in the set.


The ANY operator returns true if any of the subquery rows meet the condition. If the

subquery produces an empty result set, the condition is not satisfied.

• ALL means all the value in the set.

The ALL operator returns true if all of the subquery rows meet the condition.

In this case the condition evaluates to true if the subquery does not produce any row or
value.

Example of ANY operator Retrieve all employees whose salary greater than or equal to at
least one employee working in department 10:

SELECT * FROM EMP WHERE SAL >= ANY (SELECT


SAL FROM EMP WHERE DEPTNO = 10);
Suppose department 10 has 3 employees with salary 2450, 5000 and 1300. So the query will
be

SELECT * FROM EMP WHERE SAL >= ANY (2450, 3000, 1300);
Equivalent Query: SELECT * FROM EMP
WHERE SAL >= 2450 OR SAL >= 3000 OR SAL >= 1300;
Note:
1. ANY and SOME operators are equivalent.
2. ANY and SOME are equivalent to OR operator and the IN operator.
Example of ALL operator Retrieve all employees who earn more than all employees working
in department 10:

SELECT * FROM EMP WHERE SAL > ALL(SELECT SAL FROM EMP WHERE DEPTNO =
10);
Suppose department 10 has 3 employees with salary 2450, 5000 and 1300. So the query will
be
SELECT * FROM EMP WHERE SAL >= ALL (2450, 3000, 1300);
Equivalent Query: SELECT * FROM EMP
WHERE SAL >= 2450 AND SAL >= 3000 AND SAL >= 1300;

Limitation Oracle allows up to 255 levels of sub queries in the WHERE clause.
** JOIN **

The process of forming rows from two or more tables by comparing the contents of related
columns is called “Joining” tables.
Join: A join is a query that combines rows from two or more tables or views.

Joining column name may not be same but type and width must be same for all tables.

The purpose is to bind data together, across tables, without repeating all of the data in every
table. Generally joining includes primary key of one table and foreign key of another table.

Connection between the tables is established using WHERE clause.

Guidelines for creating join:

1. When writing a select statement that joins tables, precede the column name with the table
name for clarity.
2. If the same column name appears in more than one table, the column name must be
prefixed with the table name.
3. The where clause is the most critical clause in join select statement. Always make sure to
include where clause.
There are 5 different types of SQL joins:

1. Inner / Equi Join


2. Outer (Left / Right/ Full) Join
3. Cross / Cartesian Join
4. Natural Join
5. Self Join

1. INNER JOIN

INNER JOIN is also known as EQUI JOIN or SIMPLE JOIN. This is the most commonly used
join.

It is known as EQUI JOIN because the where condition generally compares two columns from
two tables with equality operator ( = ) operator.

INNER JOIN returns all rows from both tables where there is an exact match between
two columns.

SyntaxSELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
OR
SELECT <ColumnName1>, <ColumnName2>, ….. <ColumnNameN>
FROM <TableName1>, <TableName2>
WHERE <TableName1.ColumnName1> = <TableName2.ColumnName2>;

Example: SELECT EMPNO, ENAME, SAL, E.DEPTNO, DNAME


FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO;

ColumnName in one table will be usually table’s primary key and ColumnName in another
table will be foreign key.

Example: SELECT EMPNO, ENAME, SAL, E.DEPTNO, DNAME FROM


EMP E, DEPT D WHERE E.DEPTNO = D.DEPTNO;

NON-EQUI JOIN

When a joining condition contains any operator other than equality operator like >, <, >=, <=,
then the join is known as NON-EQUI JOIN.

Non equi join is used to return result from two or more tables where exact join is not possible.

For example we have EMP table and SALGRADE table. The SALGRADE table contains
grade and their low salary and high salary.

Suppose we want to find the grade of employees based on their salaries then you can use
NON EQUI join because there are no matching columns in the two tables.
SELECT E.EMPNO, E.ENAME, E.SAL, S.GRADE
FROM EMP E, SALGRADE S
WHERE E.SAL >= S.LOWSAL AND E.SAL <= S.HISAL;

2. OUTER JOIN

If some values in one table do not have corresponding values then EQUI JOIN will not
display those rows.

Such rows can be displayed using OUTER JOIN. Corresponding columns for such rows will
be displayed with NULL values.

So, OUTER JOIN can be used when it is required to select all rows from the table on the left /
right / both regardless of whether the other table has values in common and enter NULL
where data is missing.
103 ACER
Table: SUPPLIERS

SUP_ID SUP_NAME
100 IBM
101 HP
102 MICROSOFT
1 100 21
Table: ORDERS
2 101 22
ORDER_ID SUP_ID CUST_ID
3 104 23

1) LEFT JOIN (LEFT OUTER JOIN)

LEFT JOIN keyword returns all rows from the left table (TableName1), even if there are no
matches in the right table (TableName2).
Left Join Syntax
SELECT <ColumnName1>, <ColumnName2>, ….. <ColumnNameN>
FROM <TableName1> LEFT [ OUTER ] JOIN <TableName2>
ON <TableName1.ColumnName1> = <TableName2.ColumnName2>;
EXAMPLE

SELECT S.SUP_ID, SUP_NAME, CUST_ID SUP_ID SUP_NAME CUST_ID


FROM SUPPLIERS S LEFT JOIN ORDERS
O ON S.SUP_ID = O.SUP_ID; 100 IBM 21

OR 101 HP 22

SELECT S.SUP_ID, SUP_NAME, 102 MICROSOFT <null>


CUST_ID FROM SUPPLIERS S, ORDERS
O WHERE S.SUP_ID = O.SUP_ID(+); 103 ACER <null>
2) RIGHT JOIN

RIGHT JOIN keyword returns all rows from the right table (TableName2), even if there are
no matches in the left table (TableName1).

SYNTAX:
SELECT column_name(s)

FROM table1

RIGHT JOIN table2

ON table1.column_name = table2.column_name;

EXAMPLE
O
SELECT ORDER_ID, CUST_ID, SUP_NAME FROM SUPPLIERS S RIGHT JOIN ORDERS R
O ON S.SUP_ID = O.SUP_ID;
SELECT ORDER_ID, CUST_ID, SUP_NAME FROM SUPPLIERS S, ORDERS O WHERE
S.SUP_ID(+) = O.SUP_ID;

3) FULL JOIN
FULL JOIN keyword return rows when there is a match in one of
the tables. The Oracle FULL OUTER JOIN would return the
all records from both Table1 and Table2.

SYNTAX (Ansi style)

SELECT <ColumnName1>, <ColumnName2>, ….. <ColumnNameN>


FROM <TableName1> FULL [ OUTER ] JOIN <TableName2>
ON <TableName1.ColumnName1> = <TableName2.ColumnName2>;

Note: FULL OUTER JOIN cannot be written in the theta style syntax without using a
UNION query.

EXAMPLE
SELECT S.SUP_ID, SUP_NAME, CUST_ID FROM SUPPLIERS S FULL JOIN ORDERS
O ON S.SUP_ID = O.SUP_ID;

This FULL OUTER JOIN example would


• return all rows from the suppliers table and all rows from the orders table and
• whenever the join condition is not met, <nulls> will be displayed in the result
set.

3. CROSS / CARTESIAN JOIN

If a join condition is not specified, Oracle performs a Cartesian product. Oracle


combines each row of one table with each row of the other table.
It combines each row from left table with every row from the right table.
4
For example, if EMP table contains 10 records and DEPT table contains 4 records, .
the number of rows selected by the query without a join condition produces 40
records. N
A
SYNTAX: T
U
EXAMPLE
R
SELECT * FROM EMP, DEPT; A
L
SYNTAX:
J
select * from table1 CROSS JOIN table2;
O
OR I
Select * from table1,table2; N

N
A
T
U
R
A
L

J
O
I
N

i
s

t
y
p
e

o
f

E
Q
U
I

J
O
IN and is structured in such a way that, columns with same name of associate tables
will appear once only.

Guidelines:
a) The associated tables have one or more pairs of identically named columns.
b) The columns must be the same data type.
c) Don’t use ON clause in a natural join.

Syntax: SELECT * FROM table1 NATURAL JOIN table2;

Example: SELECT * FROM emp NATURAL JOIN dept;

5. SELF JOIN

SELF JOIN is a type of SQL join which is used to join a table to itself. It is a join of two
copies of same table.

It is generally used when the table has a FOREIGN KEY that references its own
PRIMARY KEY.

It is necessary to ensure that the join statement defines an alias for both copies of the
table to avoid column ambiguity.

Syntax of self join is same as other joins but the FROM clause is different. It contains
same tables twice or more times. It is compulsory to prefix the column name with alias.

EXAMPLE

Display name of employees and names of their respective managers.

SELECT EMP_MASTER.ENAME, MANAGER.ENAME


FROM EMP EMP_MASTER, EMP MANAGER
WHERE EMP_MASTER.MGR=MANAGER.EMPNO;

You might also like