RDBMS Notes.
RDBMS Notes.
Features of PL/SQL:
1. PL/SQL is basically a procedural language, which provides the functionality of decision
making, iteration and many more features of procedural programming languages.
2. PL/SQL can execute a number of queries in one block using single command.
3. One can create a PL/SQL unit such as procedures, functions, packages, triggers, and
types, which are stored in the database for reuse by applications.
4. PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known
as exception handling block.
5. Applications written in PL/SQL are portable to computer hardware or operating system
where Oracle is operational.
6. PL/SQL Offers extensive error checking.
SQL PL/SQL
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;
Declare section starts with DECLARE keyword in which variables, constants, records
as cursors can be declared which stores data temporarily. It basically consists definition
of PL/SQL identifiers. This part of the code is optional.
Execution section starts with BEGIN and ends with END keyword.This is a mandatory
section and here the program logic is written to perform any task like loops and
conditional statements. It supports all DML commands, DDL commands and SQL*PLUS
built-in functions as well.
Exception section starts with EXCEPTION keyword.This section is optional which
contains statements that are executed when a run-time error occurs. Any exceptions can
be handled in this section.
Syntax:
if condition then
-- do something
end if;
if – then- else: The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we want to do
something else if the condition is false. Here comes the else statement. We can use the
else statement with if statement to execute a block of code when the condition is false.
Syntax:-
if (condition) then
-- Executes this block if
-- condition is true
else
-- Executes this block if
-- condition is false
Syntax:-
if (condition1) then
-- Executes when condition1 is true
if (condition2) then
-- Executes when condition2 is true
end if;
end if;
if-then-elsif-then-else ladder Here, a user can decide among multiple options. The if
then statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of
the ladder is bypassed. If none of the conditions is true, then the final else statement will
be executed.
Syntax:-
if (condition) then
--statement
elsif (condition) then
--statement
.
.
else
--statement
Endif
PL/SQL - Loops
A loop statement allows us to execute a statement or group of statements multiple times .
PL/SQL provides the following types of loop to handle the looping requirements.
1. PL/SQL - Basic Loop Statement
Basic loop structure encloses sequence of statements in between the LOOP and END
LOOP statements. With each iteration, the sequence of statements is executed and
then control resumes at the top of the loop.
Syntax
LOOP
Sequence of statements;
END LOOP;
Syntax
WHILE condition LOOP
sequence_of_statements
END LOOP;
Syntax
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
Parameter Modes in PL/SQL Subprograms
The following table lists out the parameter modes in PL/SQL subprograms −
IN
An IN parameter lets you pass a value to the subprogram. It is a read-only parameter. Inside the
1 subprogram, an IN parameter acts like a constant. It cannot be assigned a value. You can pass a
constant, literal, initialized variable, or expression as an IN parameter. You can also initialize it to a
default value; however, in that case, it is omitted from the subprogram call. It is the default mode of
parameter passing. Parameters are passed by reference.
OUT
2 An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT parameter
acts like a variable. You can change its value and reference the value after assigning it. 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 value to the
3 caller. It can be assigned a value and the value can be read.
The actual parameter corresponding to an IN OUT formal parameter must be a variable, not a constant
or an expression. Formal parameter must be assigned a value. Actual parameter is passed by value.
Syntax:
Creating a Procedure
CREATE PROCEDURE procedure_name
(parameter1 data_type, parameter2 data_type, …)
AS
BEGIN
— SQL statements to be executed
END
Creating a Function
Example:
This function returns the total number of CUSTOMERS in the customers table.
RETURN total;
END;
'language plpgsql;
PL/SQL – Cursors
A cursor is a pointer that points to a result of a query. A cursor is used to
referred to a program to fetch and process the rows returned by the SQL
statement, one at a time.
types of cursors −
Implicit cursors
Explicit cursors
Explicit Cursors
Declaring the cursor defines the cursor with a name and the associated SELECT statement.
For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;
Opening the Cursor
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the
rows returned by the SQL statement into it. For example, we will open the above defined
cursor as follows −
OPEN c_customers;
Fetching the Cursor
Fetching the cursor involves accessing one row at a time. For example, we will fetch rows
from the above-opened cursor as follows −
Closing the cursor means releasing the allocated memory. For example, we will close the
above-opened cursor as follows −
CLOSE c_customers;
PL/SQL - Triggers
Triggers are stored programs, which are automatically executed or fired when some events
occur. Triggers are, in fact, written to be executed in response to any of the following events
−
PL/SQL - Transactions
Collection of operations that forms a single logical unit of work is called transaction.
Consistency:
This means that integrity constraints must be maintained so that the database is consistent
before and after the transaction. It refers to the correctness of a database. Referring to the
example above,
The total amount before and after the transaction must be maintained.
Total before T occurs = 500 + 200 = 700.
Total after T occurs = 400 + 300 = 700.
Therefore, the database is consistent. Inconsistency occurs in case T1 completes
but T2 fails. As a result, T is incomplete.
Isolation:
This property ensures that multiple transactions can occur concurrently without leading to
the inconsistency of the database state.
This property ensures that the execution of transactions concurrently will result in a state
that is equivalent to a state achieved these were executed serially in some order.
Durability:
This property ensures that once the transaction has completed execution, the updates and
modifications to the database are stored in and written to disk and they persist even if a
system failure occurs. These updates now become permanent and are stored in non-volatile
memory. The effects of the transaction, thus, are never lost.
Following are the functions to access the database:
1.read :It belongs to transaction that executed the read operation.
2.write :This transaction that executed the write operation.
States of Transaction
1. Active State –
When the instructions of the transaction are running then the transaction is in active
state. If all the ‘read and write’ operations are performed without any error then it goes
to the “partially committed state”; if any instruction fails, it goes to the “failed state”.
2. Partially Committed –
After completion of all the read and write operation the changes are made in main
memory or local buffer. If the changes are made permanent on the DataBase then the
state will change to “committed state” and in case of failure it will go to the “failed
state”.
3. Failed State –
When any instruction of the transaction fails, it goes to the “failed state” or if failure
occurs in making a permanent change of data on Data Base.
4. Aborted State –
After having any type of failure the transaction goes from “failed state” to “aborted
state” and since in previous states, the changes are only made to local buffer or main
memory and hence these changes are deleted or rolled-back.
5. Committed State –
It is the state when the changes are made permanent on the Data Base and the
transaction is complete and therefore terminated in the “terminated state”.
Schedules
When multiple transaction requests are made at the same time, we need to decide their order
of execution.
Serial Schedule
when multiple transactions are to be executed, they are executed serially, i.e. at one time
only one transaction is executed while others wait for the execution of the current transaction
to be completed. This ensures consistency in the database as transactions do not execute
simultaneously.
Example: Consider the following schedule involving two transactions T 1 and T2.
T1 T2
R(A)
W(A)
R(B)
W(B)
R(A)
R(B)
where R(A) denotes that a read operation is performed on some data item ‘A’ This is a serial
schedule since the transactions perform serially in the order T 1 —> T2
Concurrent (Non-Serial) Schedule
To reduce the waiting time of transactions in the waiting queue and improve the system
efficiency, we use non serial schedules which allow multiple transactions to start before a
transaction is completely executed. This may sometimes result in inconsistency and errors in
database operation.
Serializability:
Serialization referes to the transactions running serially,one after the other rather than
concurrently .
These are of two types:
1. Conflict Serializable: A schedule is called conflict serializable if it can be transformed
into a serial schedule by swapping non-conflicting operations. Two operations are said
to be conflicting if all conditions satisfy:
They belong to different transactions
They operate on the same data item
At Least one of them is a write operation
2. View Serializable: A Schedule is called view serializable if it is view equal to a serial
schedule (no overlapping transactions). A conflict schedule is a view serializable but if
the serializability contains blind writes, then the view serializable does not conflict
serializable.
Precedance Graph :
It is set of vertices and edges.
Locks/Locking:
Locking data item is one of the main techniques for controlling the concurrent execution of
transactions which controls the access of the data item.
TYPES OF LOCKS
1. Shared lock:
o It is also known as a Read-only lock. In a shared lock, the data item can only read by
the transaction.
o 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:
o In the exclusive lock, the data item can be both reads as well as written by the
transaction.
o This lock is exclusive, and in this lock, multiple transactions do not modify the same
data simultaneously.
COMMIT-
COMMIT in SQL is a transaction control language that is used to permanently
save the changes done in the transaction in tables/databases. The database cannot
regain its previous state after its execution of commit.
When the transaction is successful, COMMIT is applied.
Syntax of COMMIT statement are:
COMMIT;
REVOKE -
The Revoke statement is used to revoke some or all of the privileges which have been
granted to a user in the past.
Syntax:
REVOKE privileges ON object FROM user;
Parameters Used:
object: It is the name of the database object from which permissions are being
revoked. In the case of revoking privileges from a table, this would be the table
name.
user: It is the name of the user from whom the privileges are being revoked.
Here is an example:
REVOKE INSERT ON mydb FROM 'user1'@'localhost';
This command revokes the INSERT permission on the database 'mydb' from
'user1'.
GRANT-
This DCL command grants permissions to the user on the database objects. It
assigns access rights to users.
DOCUMENT DATABASE-
The document-based database is a nonrelational database. Instead of storing the data
in rows and columns (tables), it uses the documents to store the data in the database.
Collections are the group of documents that store documents that have similar
contents.
Documents in the database has a flexible schema. It means the documents in the
database need not be the same schema.
Key-Value Stores:
Failure Classification
To find that where the problem has occurred, we generalize a failure into the following
categories:
1. Transaction failure
2. System crash
3. 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.
1. Logical errors: If a transaction cannot complete due to some code error or an internal
error condition, then the logical error occurs.
2. 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.
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.
ROLLBACK-
o The rollback command is used to get back to the previous permanent status of the table,
which is saved by the commit command.
ENCRYPTION-
DEADLOCK-
A deadlock is a condition where two or more transactions are waiting indefinitely for one another
to give up locks.
DATABASE RECOVERY
Database recovery techniques are used in database management systems (DBMS)
to restore a database to a consistent state after a failure or error has occurred.
PARALLEL DATABASE-
A parallel database is one which involves multiple processors and working in parallel on the
database used to provide the services.
A parallel server can allow access to a single database by users on multiple
machines.
DISTRIBUTED DATABASE
a distributed database is a database that stores data in multiple locations instead of one
location. This means that rather than putting all data on one server or on one computer,
data is placed on multiple servers or in a cluster of computers consisting of individual
nodes.
1. Discretionary Access Control (DAC)
DAC is identity-based access control. DAC mechanisms will be controlled by
user identification such as username and password. DAC is discretionary
because the owners can transfer objects or any authenticated information to
other users. In simple words, the owner can determine the access privileges.
2. Mandatory Access Control (MAC)
The operating system in MAC will provide access to the user based on their
identities and data. For gaining access, the user has to submit their personal
information. It is very secure because the rules and restrictions are imposed
by the admin and will be strictly followed. MAC settings and policy
management will be established in a secure network and are limited to system
administrators.