0% found this document useful (0 votes)
36 views

Dbms (Unit 3,4,5)

The document discusses SQL commands categorized into DDL, DQL, DML, DCL and TCL. It provides examples and descriptions of commands for each category. Constraints like NOT NULL, UNIQUE, PRIMARY KEY and FOREIGN KEY are explained. The differences between TRUNCATE, DROP and DELETE are outlined. Examples are provided to demonstrate the IN operator, UNIQUE, NOT NULL, CHECK constraints and aggregate functions like COUNT, SUM, AVG, MIN and MAX. Common string functions such as ASCII, CHR, CONCAT, CONVERT and DUMP are listed along with examples.

Uploaded by

ada
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Dbms (Unit 3,4,5)

The document discusses SQL commands categorized into DDL, DQL, DML, DCL and TCL. It provides examples and descriptions of commands for each category. Constraints like NOT NULL, UNIQUE, PRIMARY KEY and FOREIGN KEY are explained. The differences between TRUNCATE, DROP and DELETE are outlined. Examples are provided to demonstrate the IN operator, UNIQUE, NOT NULL, CHECK constraints and aggregate functions like COUNT, SUM, AVG, MIN and MAX. Common string functions such as ASCII, CHR, CONCAT, CONVERT and DUMP are listed along with examples.

Uploaded by

ada
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Unit-3

1.Explain Basics Of Sql,Dml,Ddl,Dcl,Dql?

ANS:
Structured Query Language(SQL) as we all know is the database language
by the use of which we can perform certain operations on the existing
database and also we can use this language to create a database. SQL uses
certain commands like Create, Drop, Insert, etc. to carry out the required
tasks.
These SQL commands are mainly categorized into four categories as:
1. DDL – Data Definition Language
2. DQl – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
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. We can define DQL as follows it is a
component of SQL statement that allows getting data from the database and
imposing order upon it. It includes the SELECT statement. This command
allows getting the data out of the database to perform operations with it.
When a SELECT is fired against a table or tables the result is compiled into
a further temporary table, which is displayed or perhaps received by the
program i.e. a front-end.
List of DQL:
 SELECT: It is used to retrieve data from the database.
DML(Data Manipulation Language):
The SQL commands that deals with the manipulation of data present in the
database belong to DML or Data Manipulation Language and this includes
most of the SQL statements. It is the component of the SQL statement that
controls access to data and to the database. Basically, DCL statements are
grouped with DML statements.
List of DML commands:
 INSERT : It is used to insert data into a table.
 UPDATE: It is used to update existing data within a table.
 DELETE : It is used to delete records from a database table.
 LOCK: Table control concurrency.
 CALL: Call a PL/SQL or JAVA subprogram.
 EXPLAIN PLAN: It describes the access path to data.
DCL (Data Control Language):
DCL includes commands such as GRANT and REVOKE which mainly deal
with the rights, permissions, and other controls of the database system.
List of DCL commands:
 GRANT: This command gives users access privileges to the database.
 REVOKE: This command withdraws the user’s access privileges given
by using the GRANT command.
Though many resources claim there to be another category of SQL clauses
TCL – Transaction Control Language. So we will see in detail about TCL as
well. TCL commands deal with the transaction within the database.
List of TCL commands:

 COMMIT: Commits a Transaction.


 ROLLBACK: Rollbacks a transaction in case of any error occurs.
 SAVEPOINT:Sets a savepoint within a transaction.
 SET TRANSACTION: Specify characteristics for the transaction.

2. Types Of Constraints?

ANS: The following constraints are commonly used in SQL:


 NOT NULL - Ensures that a column cannot have a NULL value
 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between
tables
 CHECK - Ensures that the values in a column satisfies a specific
condition
 DEFAULT - Sets a default value for a column if no value is specified
 CREATE INDEX - Used to create and retrieve data from the
database very quickly

3. Differerence Between Truncate,Drop,Delete?

TRUNCATE
It is also a Data Definition Language Command (DDL). It is used to delete
all the rows of a relation (table) in one go. With the help of the
“TRUNCATE” command, we can’t delete the single row as here WHERE
clause is not used. By using this command the existence of all the rows of
the table is lost. It is comparatively faster than the delete command as it
deletes all the rows fastly.
DELETE
Basically, it is a Data Manipulation Language Command (DML). It is used
to delete one or more tuples of a table. With the help of the “DELETE”
command, we can either delete all the rows in one go or can delete rows
one by one. i.e., we can use it as per the requirement or the condition using
the Where clause. It is comparatively slower than the TRUNCATE
command. The TRUNCATE command does not remove the structure of the
table.

DROP
It is a Data Definition Language Command (DDL). It is used to drop the
whole table. With the help of the “DROP” command we can drop (delete)
the whole structure in one go i.e. it removes the named elements of the
schema. By using this command the existence of the whole table is finished
or say lost.

4. Important Of In Operator, Unique,Not Null,Checks With Example?

ANS:
IN -> The IN operator is used to compare a value to a list of literal values
that have been specified.
UNIQUE -> The UNIQUE operator searches every row of a specified table
for uniqueness (no duplicates).
NOTNULL -> The IS NOT NULL condition is used in SQL to test for a non-
NULL value. It returns TRUE if a non-NULL value is found, otherwise it
returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE
statement.
SQL CHECK Constraint:
The CHECK constraint is used to limit the value range that can be placed in
a column.If you define a CHECK constraint on a column it will allow only
certain values for this column.If you define a CHECK constraint on a table it
can limit the values in certain columns based on values in other columns in
the row.
5. Explain Aggregate Function With Examples?

1. COUNT()
• This function is used to calculate number of rows in a table selected by
query.
• COUNT returns the number of rows in the table when the column value is
not NULL.
Example: Find total number of students
SELECT COUNT(Sid) as COUNT
FROM Exam_Marks
Count
6
2. SUM()
•This function is used to calculate sum of column values in a table selected
by query.
Example:
Find total of marks scored by all students
SELECT SUM(Marks) as SUM
FROM Exam_Marks
Sum
446
3. AVG()
• This function is used to calculate the average of column values in a table
selected by query.
• This function first calculates sum of columns and then divide by total
number of rows.
Example:
Find average marks of students
SELECT AVG(Marks) as AVG
FROM Exam_Marks
AVG
89.33
4. MIN()
•This function is used to find maximum value out of column values in a
table selected by query.
Example:
Find total of marks scored by all students
SELECT MIN(Marks) as MIN
FROM Exam_Marks
MIN
80
5. MAX()
•This function is used to find maximum value out of column values in a
table selected by query.
Example:
Find total of marks scored by all students
SELECT MAX(Marks) as MAX
FROM Exam_Marks
MAX
99

6. List Any 10 Strings Functions With Examples?

Function Example Result Purpose


ASCII ASCII(‘A’) 65 Returns an
ASCII code
value of a
character.
CHR CHR(’65’) ‘A’ Converts a
numeric value to
its
corresponding
ASCII character.
CONCAT CONCAT(‘A’,’BC ‘ABC’ Concatenate two
’) strings and
return the
combined string.
CONVERT CONVERT( ‘Ä Ê ‘A E I’ Convert a
Í’, ‘US7ASCII’, character string
‘WE8ISO8859P1 from one
’) character set to
another.
DUMP DUMP(‘A’) Typ=96 Len=1: Return a string
65 value
(VARCHAR2)
that includes the
datatype code,
length measured
in bytes, and
internal
representation of
a specified
expression.
INITCAP INITCAP(‘hi ‘Hi There’ Converts the first
there’) character in
each word in a
specified string
to uppercase
and the rest to
lowercase.
INSTR INSTR( ‘This is a 3 Search for a
playlist’, ‘is’) substring and
return the
location of the
substring in a
string
LENGTH LENGTH(‘ABC’) 3 Return the
number of
characters (or
length) of a
specified string
LOWER LOWER(‘Abc’) ‘abc’ Return a string
with all
characters
converted to
lowercase.
LPAD LPAD(‘ABC’,5,’*’ ‘**ABC’ Return a string
) that is left-
padded with the
specified
characters to a
certain length.
LTRIM LTRIM(‘ ABC ‘) ‘ABC ‘ Remove spaces
or other
specified
characters in a
set from the left
end of a string.
REGEXP_COU REGEXP_COU 3 Return the
NT NT(‘1 2 3 number of times
abc’,’¥d’) a pattern occurs
in a string.
REGEXP_INST REGEXP_INST 2 Return the
R R( ‘Y2K position of a
problem’,’¥d+’) pattern in a
string.
REGEXP_LIKE REGEXP_LIKE( true Match a string
‘Year of based on a
2017′,’¥d+’ ) regular
expression
pattern.
REGEXP_REPL REGEXP_REPL ‘Year of Replace
ACE ACE( ‘Year of Dragon’ substring in a
2017′,’¥d+’, string by a new
‘Dragon’ ) substring using a
regular
expression.
REGEXP_SUBS REGEXP_SUBS 10 Extract
TR TR( ‘Number substrings from
10’, ‘¥d+’ ) a string using a
pattern of a
regular
expression.
REPLACE REPLACE(‘JAC ‘BLACK AND Replace all
K AND BLOND’ occurrences of a
JOND’,’J’,’BL’); substring by
another
substring in a
string.
RPAD ‘ABC**’ Return a string
RPAD(‘ABC’,5,’*’ that is right-
) padded with the
specified
characters to a
certain length.
RTRIM RTRIM(‘ ABC ‘) ‘ ABC’ Remove all
spaces or
specified
character in a
set from the right
end of a string.
SOUNDEX SOUNDEX(‘sea’ ‘S000’ Return a
) phonetic
representation of
a specified
string.
SUBSTR SUBSTR(‘Oracle ‘Oracle’ Extract a
Substring’, 1, 6 ) substring from a
string.
TRANSLATE ‘b2x5’ Replace all
TRANSLATE(‘12 occurrences of
345’, ‘143’, ‘bx’) characters by
other characters
in a string.
TRIM TRIM(‘ ABC ‘) ‘ABC’ Remove the
space character
or other
specified
characters either
from the start or
end of a string.
UPPER UPPER(‘Abc’) ‘ABC’ Convert all
characters in a
specified string
to uppercase.

7. Explain How Date Function Is Used?

Date functions in Oracle can be defined as a set of functions which operate


on date and allows the developer or users to retrieve the current date and
time in a particular time zone or extract only the date/ month/year or more
complex actions like extracting the last day of the month/ next day/ session
time zone and it also consist of functions which can be used to convert a
Date value to a character string or convert a date which is in character
string to a Date value.

8. Set Operations?
1. Union
 The SQL Union operation is used to combine the result of two or more
SQL SELECT queries.
 In the union operation, all the number of datatype and columns must
be same in both the tables on which UNION operation is being applied.
 The union operation eliminates the duplicate rows from its resultset.
Syntax
SELECT column_name FROM table1
UNION
SELECT column_name FROM table2;
2. Union All
Union All operation is equal to the Union operation. It returns the set without
removing duplication and sorting the data.
Syntax:
SELECT column_name FROM table1
UNION ALL
SELECT column_name FROM table2;
3. Intersect
 It is used to combine two SELECT statements. The Intersect operation
returns the common rows from both the SELECT statements.
 In the Intersect operation, the number of datatype and columns must
be the same.
 It has no duplicates and it arranges the data in ascending order by
default.
Syntax
SELECT column_name FROM table1
INTERSECT
SELECT column_name FROM table2;
4. Minus
 It combines the result of two SELECT statements. Minus operator is
used to display the rows which are present in the first query but absent
in the second query.
 It has no duplicates and data arranged in ascending order by default.
Syntax:
SELECT column_name FROM table1
MINUS
SELECT column_name FROM table2;
9.What Are Sub-Queries & Correlated Sub-Queries

Subquery:
A Subquery or Inner query or a Nested query is a query within another SQL
query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a
condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
Correlated Subqueries :
SQL Correlated Subqueries are used to select data from a table referenced
in the outer query. The subquery is known as a correlated because the
subquery is related to the outer query. In this type of queries, a table alias
(also called a correlation name) must be used to specify which table
reference is to be used.
The alias is the pet name of a table which is brought about by putting directly
after the table name in the FROM clause. This is suitable when anybody
wants to obtain information from two separate tables.

Unit-4
1.Explain Group By Having Order By?

ORDER BY returns sorted items in ascending and descending order while

GROUP BY returns unique items with the aggregate resultant column.

Group By :
Group by statement is used to group the rows that have the same value. It
is often used with aggregate functions for example:AVG(), MAX(),
COUNT(), MIN() etc. One thing to remember about the group by clause is
that the tuples are grouped based on the similarity between the attribute
values of tuples.
Group By Syntax –
SELECT function_Name(column_1), column_2
FROM Table_Name
WHERE condition
GROUP BY column_1, column_2
ORDER BY column_1, column_2;
The SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could
not 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);

Order By :
Order by keyword sort the result-set either in ascending or in descending
order. This clause sorts the result-set in ascending order by default. In order
to sort the result-set in descending order DESC keyword is used.
Order By Syntax –
SELECT column_1, column_2, column_3...........
FROM Table_Name
ORDER BY column_1, column_2, column_3....... ASC|DESC;
ASC: keyword for ascending order DESC: keyword for descending order
2.Explain Join And Its Types?

JOINS in SQL are commands which are used to combine rows from two or
more tables, based on a related column between those tables. There are
predominantly used when a user is trying to extract data from tables which
have one-to-many or many-to-many relationships between them.

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both


tables
 LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
 RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
 FULL (OUTER) JOIN: Returns all records when there is a match in
either left or right table

Inner Join
syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
LEFT JOIN
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

RIGHT JOIN
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

FULL JOIN:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

3.Use Of Exists Any All Clauses?

The SQL EXISTS condition is used in combination with a subquery and is

considered to be met, if the subquery returns at least one row. It can be used

in a SELECT, INSERT, UPDATE, or DELETE statement. The syntax for the

EXISTS condition in SQL is: WHERE EXISTS ( subquery );

The SQL ANY Operator

The ANY operator:

 returns a boolean value as a result


 returns TRUE if ANY of the subquery 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 Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);

The SQL ALL Operator

The ALL operator:

 returns a boolean value as a result


 returns TRUE if ALL of the subquery values meet the condition
 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 Syntax With SELECT


SELECT ALL column_name(s)
FROM table_name
WHERE condition;

4.Explain Tcl Commands?

These are used to manage the changes made by DML-statements. It also

allows statements to be grouped together into logical transactions.

COMMIT: Commit command is used to permanently save any transaction into

the database.Examples of TCL commands

ROLLBACK: This command restores the database to last committed state. It

is also used with savepoint command to jump to a savepoint in a transaction.

SAVEPOINT: Savepoint command is used to temporarily save a transaction

so that you can rollback to that point whenever necessary.


5. Block Structure Of Pl/Sql?

Parts of a PL/SQL Subprogram


It have the following three parts −

S.No Parts & Description

Declarative Part
1
It is an optional part. However, the declarative part for a subprogram
does not start with the DECLARE keyword.

Executable Part
2 This is a mandatory part and contains statements that perform the
designated action.

Exception-handling
3 This is again an optional part. It contains the code that handles run-
time errors.
Creating a Procedure

A procedure is created with the CREATE OR REPLACE


PROCEDURE statement.
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;

6. List Variables,Operators,Data Types?

A list variable holds a list of values (for example, logins or passwords) to be

used in scenarios. Each list variable specifies the order, in which virtual users

access list values. For example, each virtual user can use only one specific

value from the list or take the next value every time the user simulates a

request to the server.

DBMS data types include integer, float, characters, strings, and arrays.

They're also very distinct types, such as dates, date timestamps, boolean,

and varchar formats.


7.Control Structures?

PL/SQL Control Structures are used to control flow of execution. PL/SQL

provides different kinds of statements to provide such type of procedural

capabilities.These statements are almost same as that of provided by

other languages.

The flow of control statements can be classified into the following

categories:

• Conditional Control

• Iterative Control

• Sequential Control

8.Use Of Cursors With Syntax & Their Types?

Cursor is a Temporary Memory or Temporary Work Station. It is Allocated by

Database Server at the Time of Performing DML(Data Manipulation Language)

operations on Table by User. Cursors are used to store Database Tables. There

are 2 types of Cursors: Implicit Cursors, and Explicit Cursors. These are

explained as following below.

1. Implicit Cursors: Implicit Cursors are also known as Default Cursors of SQL

SERVER. These Cursors are allocated by SQL SERVER when the user

performs DML operations.


2. Explicit Cursors : Explicit Cursors are Created by Users whenever the user

requires them. Explicit Cursors are used for Fetching data from Table in Row-

By-Row Manner.

How to use Explicit Cursor? T

here are four steps in using an Explicit Cursor.

1. DECLARE the cursor in the Declaration section.

2. OPEN the cursor in the Execution Section.

3. FETCH the data from the cursor into PL/SQL variables or records in the

Execution Section.

4. CLOSE the cursor in the Execution Section before you end the PL/SQL

Block.

9.Attributes In Stored Procedure?

10.parameter modes

The following table lists out the parameter modes in PL/SQL subprograms −

S.No Parameter Mode & Description


IN
1 An IN parameter lets you pass a value to the subprogram. It is a read-only
parameter.. You can pass a constant, literal, initialized variable, or expression as an
IN parameter.

OUT
An OUT parameter returns a value to the calling program. Inside the subprogram, an
2 OUT parameter acts like a variable. The actual parameter must be variable and it
is passed by value.

IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated
3 value to the caller. The actual parameter corresponding to an IN OUT formal
parameter must be a variable, Actual parameter is passed by value.

IN & OUT Mode Example 1


This program finds the minimum of two values. Here, the procedure takes two numbers
using the IN mode and returns their minimum using the OUT parameters.

DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Minimum of (23, 45) : 23
10.Triggers?

PL/SQL Trigger
Trigger is invoked by Oracle engine automatically whenever a specified event occurs.Trigger
is stored into database and invoked repeatedly, when specific condition match.
Triggers are stored programs, which are automatically executed or fired when some event
occurs.
Triggers are written to be executed in response to any of the following events.

 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).


 A database definition (DDL) statement (CREATE, ALTER, or DROP).

Creating a trigger:
Syntax for creating trigger:

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
BEFORE and AFTER of Trigger:
BEFORE triggers run the trigger action before the triggering statement is run.
AFTER triggers run the trigger action after the triggering statement is run.

EXAMPLE
Create or replace trigger t2 before update on emp
Begin
Update employee1 set salary=salary*1.2 where salary>2000
Dbms_output.put_line(‘record updated’);
End;

OUTPUT
RECORD UPDATED
9.Attributes In Stored Procedure?

A stored procedure is a prepared SQL code that you can save, so the code
can be reused over and over again.

Used to mark a method definition in an assembly as a stored procedure. The


properties on the attribute reflect the physical characteristics used when the
type is registered with SQL Server. This class cannot be inherited.

C#Copy

[System.AttributeUsage(System.AttributeTargets.Method,
AllowMultiple=false, Inherited=false)]
[System.Serializable]
public sealed class SqlProcedureAttribute : Attribute
Inheritance
Object
Attribute SqlProcedureAttribute Attributes AttributeUsageAttribute
SerializableAttribute

Unit-5

1. Transactions & Its States?

Transaction:
Transaction is a logical unit of work that represents real-world events of any
organisation or an enterprise whereas concurrency control is the
management of concurrent transaction execution. Transaction processing
systems execute database transactions with large databases and hundreds
of concurrent users, for example, railway and air reservations systems,
banking system, credit card processing, stock market monitoring, super
market inventory and checkouts and so on.
A transaction can be in one of the following states:

State Description
Active A transaction goes into an active state immediately after it starts execution, where it can
state issue READ and WRITE operations.
A transaction may be aborted when the transaction itself detects an error during execution
which it cannot recover from, for example, a transaction trying to debit loan amount of an
employee from his insufficient gross salary. A transaction may also be aborted before it has
been committed due to system failure or any other circumstances beyond its control.
Partiall When the transaction ends, it moves to the partially committed state.When the last state is
y reached.
commit To this point, some recovery protocols need to ensure that a system failure will not result in
ted an inability to record the changes of the transaction permanently. Once this check is
successful, the transaction is said to have reached its commit point and enters the committed
state.
Aborte When the normal execution can no longer be performed.
d Failed or aborted transactions may be restarted later, either automatically or after being
resubmitted by the user as new transactions.
Commi After successful completion of transaction.
tted A transaction is said to be in a committed state if it has partially committed and it can be
ensured that it will never be aborted.

2.Properties Of Transactions?

Transaction Properties:
A transaction must have the following four properties, called ACID properties
(also called ACIDITY of a transaction), to ensure that a database remains
stable state after the transaction is executed:
5. Atomicity.
6. Consistency.
7. Isolation.
8. Durability.
Atomicity:
The atomicity property of a transaction requires that all operations of a
transaction be completed, if not, the transaction is aborted. In other words,
a transaction is treated as single, individual logical unit of work.
Therefore, a transaction must execute and complete each operation in its
logic before it commits its changes.As stated earlier, the transaction is
considered as one operation even though there are multiple read and
writes. Thus, transaction completes or fails as one unit.
The atomicity property of transaction is ensured by the transaction
recovery subsystem of a DBMS.
In the event of a system crash in the midst of transaction execution, the
recovery techniques undo any effects of the transaction on the database.

Consistency:
Database consistency is the property that every transaction sees a
consistent database instance.In other words, execution of a transaction
must leave a database in either its prior stable state or a new stable state
that reflects the new modifications (updates) made by the transaction.
If the transaction fails, the database must be returned to the state it was in
prior to the execution of the failed transaction.
If the transaction commits, the database must reflect the new
changes.Thus, all resources are always in a consistent state.
The preservation of consistency is generally the responsibility of the
programmers who write the database programs or of the DBMS module
that enforces integrity constraints.
A database program should be written in a way that guarantees that, if the
database is in a consistent state before executing the transaction, it will be
in a consistent state after the complete execution of the transaction,
assuming that no interference with other transactions occur.
In other words, a transaction must transform the database from one
consistent state to another consistent state.

Isolation:
Isolation property of a transaction means that the data used during the
execution of a transaction cannot be used by a second transaction until the
first one is completed. This property isolates transactions from one
another.In other words, if a transaction T1 is being executed and is using
the data item X, that data item cannot be accessed by any other
transaction (T2… ......... Tn) until T1 ends.
The isolation property is enforced by the concurrency control subsystem of
the DBMS.

Durability:
The durability property of transaction indicates the performance of the
database's consistent state. It states that the changes made by a
transaction are permanent.
They cannot be lost by either a system failure or by the erroneous
operation of a faulty transaction. When a transaction is completed, the
database reaches a consistent state and that state cannot be lost, even in
the event of system's failure.
Durability property is the responsibility of the recovery subsystem of the
DBMS.

3.Difference Between Serial & Non Serial Schedule?


Serial Schedule Non-Serial Schedule
A serial schedule is a sequence of A non-serial schedule is a schedule
operation by a set of concurrent where the operations of a group of
transaction that preserves the order of concurrent transactions are interleaved.
operations in each of the individual
transactions.
Transactions are performed in serial Transactions are performed in non-serial
order. order, but result should be same as
serial.
No interference between transactions Concurrency problem can arise here.
It does not matter which transaction is The problem we have seen earlier lost
executed first, as long as every update, uncommitted data, inconsistent
transaction is executed in its entirely from analysis is arise if scheduling is not
the beginning to end. proper.
A serial schedule gives the benefits of In this schedule there is no any benefit of
concurrent execution without any problem concurrent execution.

Serial schedule that does interleaved the Where non-serial schedule has no only fix
actions of different transactions. actions of any transaction.
4.Define Concurrent Executions?

In a multi-user system, multiple users can access and use the same
database at one time, which is known as the concurrent execution of the
database. It means that the same database is executed simultaneously on
a multi-user system by different users.

5.Types Of Serialiazabiity?
Types of serializability
There are two types of serializability −

View serializability
A schedule is view-serializability if it is viewed equivalent to a serial schedule.
The rules it follows are as follows −
 T1 is reading the initial value of A, then T2 also reads the initial value of A.
 T1 is the reading value written by T2, then T2 also reads the value written by T1.
 T1 is writing the final value, and then T2 also has the write operation as the final
value.

Conflict serializability
It orders any conflicting operations in the same way as some serial execution. A pair of
operations is said to conflict if they operate on the same data item and one of them is a
write operation.
That means
 Readi(x) readj(x) - non conflict read-read operation
 Readi(x) writej(x) - conflict read-write operation.
 Writei(x) readj(x) - conflict write-read operation.
 Writei(x) writej(x) - conflict write-write operation.

6.Rules For Testing Serialiazabiity?

Testing of Serializability
Serialization Graph is used to test the Serializability of a schedule.
Assume a schedule S. For S, we construct a graph known as precedence graph. This
graph has a pair G = (V, E), where V consists a set of vertices, and E consists a set of
edges. The set of vertices is used to contain all the transactions participating in the
schedule. The set of edges is used to contain all edges Ti ->Tj for which one of the three
conditions holds:

9. Create a node Ti → Tj if Ti executes write (Q) before Tj executes read (Q).


10. Create a node Ti → Tj if Ti executes read (Q) before Tj executes write (Q).
11. Create a node Ti → Tj if Ti executes write (Q) before Tj executes write (Q).
 If a precedence graph contains a single edge Ti → Tj, then all the instructions of
Ti are executed before the first instruction of Tj is executed.
 If a precedence graph for schedule S contains a cycle, then S is non-serializable.
If the precedence graph has no cycle, then S is known as serializable.
For example:

Explanation:
Read(A): In T1, no subsequent writes to A, so no new edges
Read(B): In T2, no subsequent writes to B, so no new edges
Read(C): In T3, no subsequent writes to C, so no new edges
Write(B): B is subsequently read by T3, so add edge T2 → T3
Write(C): C is subsequently read by T1, so add edge T3 → T1
Write(A): A is subsequently read by T2, so add edge T1 → T2
Write(A): In T2, no subsequent reads to A, so no new edges
Write(C): In T1, no subsequent reads to C, so no new edges
Write(B): In T3, no subsequent reads to B, so no new edges

Precedence graph for schedule S1:

The precedence graph for schedule S1 contains a cycle that's why Schedule S1 is non-
serializable.
Explanation:
Read(A): In T4,no subsequent writes to A, so no new edges
Read(C): In T4, no subsequent writes to C, so no new edges
Write(A): A is subsequently read by T5, so add edge T4 → T5
Read(B): In T5,no subsequent writes to B, so no new edges
Write(C): C is subsequently read by T6, so add edge T4 → T6
Write(B): A is subsequently read by T6, so add edge T5 → T6
Write(C): In T6, no subsequent reads to C, so no new edges
Write(A): In T5, no subsequent reads to A, so no new edges
Write(B): In T6, no subsequent reads to B, so no new edges
Precedence graph for schedule S2:

The precedence graph for schedule S2 contains no cycle that's why ScheduleS2 is
serializable.

8. Define Concurrency Control And Explain The Concurrency Control


Protocols

(Different Types Of Locks, Phases In 2pl,Phases In Validation Protocol,


Define Timestamp)

Concurrency Control
Concurrency Control is the working concept that is required for controlling and managing the concurrent execution of
database operations and thus avoiding the inconsistencies in the database. Thus, for maintaining the concurrency of
the database, we have the concurrency control protocols.

Concurrency Control Protocols


The concurrency control protocols ensure the atomicity, consistency, isolation, durability and serializability of the
concurrent execution of the database transactions. Therefore, these protocols are categorized as:

 Lock Based Concurrency Control Protocol


 Time Stamp Concurrency Control Protocol
 Validation Based Concurrency Control Protocol

We will understand and discuss each protocol one by one in our next sections.

Lock-Based Protocol
In this type of protocol, any transaction cannot read or write data until it acquires an appropriate lock on it. There are
two types of lock:

1. Shared lock:

 It is also known as a Read-only lock. In a shared lock, the data item can only read by the transaction.
 It can be shared between the transactions because when the transaction holds a lock, then it can't update the data on the
data item.

2. Exclusive lock:

 In the exclusive lock, the data item can be both reads as well as written by the transaction.
 This lock is exclusive, and in this lock, multiple transactions do not modify the same data simultaneously.

There are four types of lock protocols available:


1. Simplistic lock protocol
It is the simplest way of locking the data while transaction. Simplistic lock-based protocols allow
all the transactions to get the lock on the data before insert or delete or update on it. It will unlock
the data item after completing the transaction.
Prime Ministers of India | List of Prime Minister of India (1947-2020)

2. Pre-claiming Lock Protocol


 Pre-claiming Lock Protocols evaluate the transaction to list all the data items on which they need
locks.
 Before initiating an execution of the transaction, it requests DBMS for all the lock on all those data
items.
 If all the locks are granted then this protocol allows the transaction to begin. When the transaction
is completed then it releases all the lock.
 If all the locks are not granted then this protocol allows the transaction to rolls back and waits until
all the locks are granted.

3. Two-phase locking (2PL)


 The two-phase locking protocol divides the execution phase of the transaction into three parts.
 In the first part, when the execution of the transaction starts, it seeks permission for the lock it
requires.
 In the second part, the transaction acquires all the locks. The third phase is started as soon as the
transaction releases its first lock.
 In the third phase, the transaction cannot demand any new locks. It only releases the acquired
locks.

There are two phases of 2PL:


Growing phase: In the growing phase, a new lock on the data item may be acquired by the
transaction, but none can be released.
Shrinking phase: In the shrinking phase, existing lock held by the transaction may be released,
but no new locks can be acquired.
In the below example, if lock conversion is allowed then the following phase can happen:
12. Upgrading of lock (from S(a) to X (a)) is allowed in growing phase.
13. Downgrading of lock (from X(a) to S(a)) must be done in shrinking phase.

Example:

The following way shows how unlocking and locking work with 2-PL.
Transaction T1:
 Growing phase: from step 1-3
 Shrinking phase: from step 5-7
 Lock point: at 3

Transaction T2:
 Growing phase: from step 2-6
 Shrinking phase: from step 8-9
 Lock point: at 6

4. Strict Two-phase locking (Strict-2PL)


 The first phase of Strict-2PL is similar to 2PL. In the first phase, after acquiring all the locks, the
transaction continues to execute normally.
 The only difference between 2PL and strict 2PL is that Strict-2PL does not release a lock after
using it.
 Strict-2PL waits until the whole transaction to commit, and then it releases all the locks at a time.
 Strict-2PL protocol does not have shrinking phase of lock release.

It does not have cascading abort as 2PL does.

Timestamp Ordering Protocol


 The Timestamp Ordering Protocol is used to order the transactions based on their Timestamps.
The order of transaction is nothing but the ascending order of the transaction creation.
 The priority of the older transaction is higher that's why it executes first. To determine the timestamp
of the transaction, this protocol uses system time or logical counter.
 The lock-based protocol is used to manage the order between conflicting pairs among transactions
at the execution time. But Timestamp based protocols start working as soon as a transaction is
created.
 Let's assume there are two transactions T1 and T2. Suppose the transaction T1 has entered the
system at 007 times and transaction T2 has entered the system at 009 times. T1 has the higher
priority, so it executes first as it is entered the system first.
 The timestamp ordering protocol also maintains the timestamp of last 'read' and 'write' operation
on a data.

Basic Timestamp ordering protocol works as follows:


1. Check the following condition whenever a transaction Ti issues a Read (X) operation:
 If W_TS(X) >TS(Ti) then the operation is rejected.
 If W_TS(X) <= TS(Ti) then the operation is executed.
 Timestamps of all the data items are updated.

2. Check the following condition whenever a transaction Ti issues a Write(X) operation:


 If TS(Ti) < R_TS(X) then the operation is rejected.
 If TS(Ti) < W_TS(X) then the operation is rejected and Ti is rolled back otherwise the operation is
executed.

Where,
TS(TI) denotes the timestamp of the transaction Ti.
R_TS(X) denotes the Read time-stamp of data-item X.
W_TS(X) denotes the Write time-stamp of data-item X.

Validation Based Protocol


Validation phase is also known as optimistic concurrency control technique.
In the validation based protocol, the transaction is executed in the following
three phases:
14. Read phase: In this phase, the transaction T is read and
executed. It is used to read the value of various data items and stores
them in temporary local variables. It can perform all the write
operations on temporary variables without an update to the actual
database.
15. Validation phase: In this phase, the temporary variable value
will be validated against the actual data to see if it violates the
serializability.
16. Write phase: If the validation of the transaction is validated, then
the temporary results are written to the database or system otherwise
the transaction is rolled back.
Here each phase has the following different timestamps:
Start(Ti): It contains the time when Ti started its execution.
Validation (Ti): It contains the time when Ti finishes its read phase and starts
its validation phase.
C++ vs Java

Finish(Ti): It contains the time when Ti finishes its write phase.


 This protocol is used to determine the time stamp for the transaction
for serialization using the time stamp of the validation phase, as it is
the actual phase which determines if the transaction will commit or
rollback.
 Hence TS(T) = validation(T).
 The serializability is determined during the validation process. It can't
be decided in advance.
 While executing the transaction, it ensures a greater degree of
concurrency and also less number of conflicts.
 Thus it contains transactions which have less number of rollbacks.

9. Define Failure Classification And Reasons For Failure

Failure Classification
To find that where the problem has occurred, we generalize a failure into the following
categories:

17. Transaction failure


18. System crash
19. Disk failure

1. Transaction failure
The transaction failure occurs when it fails to execute or when it reaches a point from
where it can't go any further. If a few transaction or process is hurt, then this is called as
transaction failure.
Reasons for a transaction failure could be -

a. Logical errors: If a transaction cannot complete due to some code error or


an internal error condition, then the logical error occurs.
b. Syntax error: It occurs where the DBMS itself terminates an active
transaction because the database system is not able to execute it. For
example, The system aborts an active transaction, in case of deadlock or
resource unavailability.

2. System Crash
o System failure can occur due to power failure or other hardware or software
failure. Example: Operating system error.

o Fail-stop assumption: In the system crash, non-volatile storage is


assumed not to be corrupted.

3. Disk Failure
o It occurs where hard-disk drives or storage drives used to fail frequently. It
was a common problem in the early days of technology evolution.
o Disk failure occurs due to the formation of bad sectors, disk head crash, and
unreachability to the disk or any other failure, which destroy all or part of
disk storage.

10. Types Of Storages


There are the following types of storage devices used for storing the data:

 Primary Storage
 Secondary Storage
 Tertiary Storage

11. Explain Log Based Recovery System


Log-based Recovery
Log is a sequence of records, which maintains the records of actions performed by a transaction. It is important that
the logs are written prior to the actual modification and stored on a stable storage media, which is failsafe.

Log-based recovery works as follows −

 The log file is kept on a stable storage media.


 When a transaction enters the system and starts execution, it writes a log about it.

<Tn, Start>

 When the transaction modifies an item X, it write logs as follows −

<Tn, X, V1, V2>

It reads Tn has changed the value of X, from V1 to V2.

 When the transaction finishes, it logs −

<Tn, commit>

The database can be modified using two approaches −

 Deferred database modification − All logs are written on to the stable storage and the database is updated
when a transaction commits.
 Immediate database modification − Each log follows an actual database modification. That is, the database
is modified immediately after every operation.

12. Explain Remote Backup System

Remote Backup
Remote backup provides a sense of security in case the primary location where the
database is located gets destroyed. Remote backup can be offline or real-time or online.
In case it is offline, it is maintained manually.
Online backup systems are more real-time and lifesavers for database administrators and
investors. An online backup system is a mechanism where every bit of the real-time data
is backed up simultaneously at two distant places. One of them is directly connected to
the system and the other one is kept at a remote place as backup.
As soon as the primary database storage fails, the backup system senses the failure and
switches the user system to the remote storage. Sometimes this is so instant that the
users can’t even realize a failure.

You might also like