Dbms (Unit 3,4,5)
Dbms (Unit 3,4,5)
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:
2. Types Of Constraints?
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.
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
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?
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.
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;
considered to be met, if the subquery returns at least one row. It can be used
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);
ALL means that the condition will be true only if the operation is true for all
values in the range.
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
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
DBMS data types include integer, float, characters, strings, and arrays.
They're also very distinct types, such as dates, date timestamps, boolean,
other languages.
categories:
• Conditional Control
• Iterative Control
• Sequential Control
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
1. Implicit Cursors: Implicit Cursors are also known as Default Cursors of SQL
SERVER. These Cursors are allocated by SQL SERVER when the user
requires them. Explicit Cursors are used for Fetching data from Table in Row-
By-Row Manner.
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.
10.parameter modes
The following table lists out the parameter modes in PL/SQL subprograms −
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.
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.
Creating a trigger:
Syntax for creating trigger:
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.
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
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.
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.
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:
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
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.
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.
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.
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
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.
Failure Classification
To find that where the problem has occurred, we generalize a failure into the following
categories:
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 -
2. System Crash
o System failure can occur due to power failure or other hardware or software
failure. Example: Operating system error.
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.
Primary Storage
Secondary Storage
Tertiary Storage
<Tn, Start>
<Tn, commit>
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.
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.