DDM 2
DDM 2
✔ The Relational Database Management System (RDBMS) has become the dominant data
processing software in use today, with an estimated total software revenue worldwide of
US$24 billion in 2011 and estimated to grow to about US$37 billion by 2016.
✔ This software represents the second generation of DBMSs and is based on the relational
data model proposed by E. F. Codd (1970).
✔ In the relational model, all data is logically structured within relations (tables).
✔ Each relation has a name and is made up of named attributes (columns) of data.
✔ Each tuple (row) contains one value per attribute.
✔ The relational model was first proposed by E. F. Codd in his seminal paper “A
relational model of data for large shared data banks” (Codd, 1970).
✔ This paper is now generally accepted as a landmark in database systems, although a set-
oriented Model had been proposed previously (Childs, 1968).
Although interest in the relational model came from several directions, the most
significant research may be attributed to three projects with rather different perspectives.
✔ The first of these, at IBM’s San José Research Laboratory in California, was the
prototype relational DBMS System R, which was developed during the late 1970s
(Astrahan et al., 1976).
✔ This project was designed to implementation concerns such as transaction management,
concurrency control, recovery techniques, query optimization, data security and integrity,
human factors, and user interfaces,
✔ In particular, the System R project led to two major developments:
● the development of a structured query language called SQL, which has since
become the formal International Organization for Standardization (ISO) and de
facto standard language for relational DBMSs;
● the production of various commercial relational DBMS products during the late
1970s and the 1980s: for example, DB2 and SQL/DS from IBM and Oracle from
Oracle Corporation.
✔ The second project to have been significant in the development of the relational model
was the INGRES (Interactive Graphics Retrieval System) project at the University of
California at Berkeley, which was active at about the same time as the System R
project.
✔ The INGRES project involved the development of a prototype RDBMS, with the
research concentrating on the same overall objectives as the System R project.
✔ The third project was the Peterlee Relational Test Vehicle at the IBM UK Scientific
Centre in Peterlee (Todd, 1976).
✔ This project had a more theoretical orientation than the System R and INGRES projects
and was significant, principally for research into such issues as query processing and
optimization as well as functional extension.
Commercial systems based on the relational model started to appear in the late 1970s and
early 1980s.
Figure2, shows the domains for some of the attributes of the Branch and Staff relations.
Tuple - A Tuple is a row of a relation.
● The elements of a relation are the rows or tuples in the table. In the Branch relation, each
row contains four values, one for each attribute.
Degree -The Degree of a relation is the number of attributes it contains.
● The Branch relation in Figure 1 has four degrees. This means that each row of the table is
a four-tuple, containing four values. A relation with only one attribute would have degree
one and be called a unary relation or one-tuple.
● A relation with two attributes is called binary.
● A Relation one with three attributes is called ternary.
Cardinality - The Cardinality of a relation is the number of tuples it contains.
● By contrast, the number of tuples is called the cardinality of the relation and this changes
as tuples are added or deleted.
Relational database - A collection of normalized relations with distinct relation names.
Alternative terminology
A relation may be referred to as a file, the tuples as records, and the attributes as fields.
MATHEMATICAL RELATIONS:
To understand the true meaning of the term relation, we have to review some concepts from
mathematics.
Suppose that we have two sets, D1 and D2.where D1 {2, 4} and D2 {1, 3, 5}.The
Cartesian product of these two sets, written D1 x D2, is the set of all ordered pairs such that
the first element is a member of D1 and the second element is a member of D2.
In our case, we have:
D1 x D2 = {(2, 1), (2, 3), (2, 5), (4, 1), (4, 3), (4, 5)}
Any subset of this Cartesian product is a relation.
For example, we could produce a relation R such that:R = {(2, 1), (4, 1)}
R = {(x, y) | x ∈ D1, y ∈ D2, and y = 1}
Database Relations :
Relation schema - A named relation defined by a set of attribute and domain name pairs.
● Let A1, A2, . . ., An be attributed with domains D1, D2, . . ., Dn. Then the set {A1:D1,
A2:D2, . . ., An:Dn} is a relation schema.
● A relation R defined by a relation schema Is a set of mappings from the attribute names
to their corresponding domains.
● Thus, relation R is a set of n-tuples:(A1: d1, A2: d2, . . ., An:dn) such that d1 ∈ D1, d2 ∈
D2, . . . , dn ∈ Dn.
Relational database schema - A set of relation schemas, each with a distinct name.
● If R1, R2, . . . Rn are a set of relation schemas, then we can write the relational database
schema, or simply relational schema, R, as:R = {R1, R2, . . . , Rn}
PROPERTIES OF RELATIONS:
A relation has the following properties:
✔ Simple model: Relational Model is simple and easy to use in comparison to other
languages.
✔ Flexible: Relational Model is more flexible than any other relational model present.
✔ Secure: Relational Model is more secure than any other relational model.
✔ Data Accuracy: Data is more accurate in the relational data model.
✔ Data Integrity: The integrity of the data is maintained in the relational model.
✔ Operations can be Applied Easily: It is better to perform operations in the relational
model.
CHARACTERISTICS OF RELATIONAL MODEL:
TYPES OF KEYS:
Super Key - The set of attributes that can uniquely identify a tuple is known as Super Key. A
super key is a group of single or multiple keys that identifies rows in a table. It supports NULL
values.
Example: In the example EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME), the
name of two employees can be the same, but their EMPLYEE_ID can't be the same. Hence, this
combination can also be a key.
Candidate Key - The minimal set of attributes that can uniquely identify a tuple is known as a
candidate key.
Example: In the EMPLOYEE table, id is best suited for the primary key. The rest of the
attributes, like SSN, Passport_Number, License_Number, etc., are considered a candidate key.
Primary Key - A primary key is a constraint in a table which uniquely identifies each row
record in a database table by enabling one or more columns in the table as primary key.
Foreign Key - An attribute, or set of attributes, within one relation that matches the
candidate key of some (possibly the same) relation.
The foreign key constraint is a column or list of columns which points to the primary key column
of another table.They act as a cross-reference between the tables.
2.2 INTEGRITY CONSTRAINTS:
✔ Integrity constraints are a set of rules. It is used to maintain the quality of information.
✔ Integrity constraints ensure that the data insertion, updating, and other processes have to
be performed in such a way that data integrity is not affected.Thus, integrity constraint is
used to guard against accidental damage to the database.
NULLS:
✔ Represents a value for an attribute that is currently unknown or is not applicable for this
tuple.
✔ A null can be taken to mean the logical value “unknown.”.
✔ Nulls are a way to deal with incomplete or exceptional data.
✔ However, a null is not the same as a zero numeric value or a text string filled with spaces;
zeros and spaces are values, but a null represents the absence of a value.
ENTITY INTEGRITY CONSTRAINTS:
✔ The entity integrity constraint states that primary key value can't be null.
✔ This is because the primary key value is used to identify individual rows in relation and if
the primary key has a null value, then we can't identify those rows.
✔ A table can contain a null value other than the primary key field.
Example;
GENERAL CONSTRAINTS:
Additional rules specified by the users or database administrators of a database that defines or
constrains some aspect of the enterprise.
For example, if an upper limit of 20 has been placed upon the number of staff that may work at
a branch office, then the user must be able to specify this general constraint and expect the
DBMS to enforce it. In this case, it should not be possible to add a new member of staff at a
given branch
✔ Reserved words are a fixed part of the SQL language and have a fixed meaning.
✔ User-defined words are made up by the user (according to certain syntax rules) and
represent the names of various database objects such as tables, columns, views, indexes,
and so on.
✔ SQL requires the use of a statement terminator to mark the end of each SQL statement
(usually the semicolon “;” is used).
✔ Most components of an SQL statement are case-insensitive, which means that letters can
be typed in either upper- or lowercase.
✔ keyword WHERE followed by a search condition that specifies the rows to be retrieved.
✔ The five basic search conditions (or predicates, using the ISO terminology) are as follows:
• Comparison Compare the value of one expression to the value of another expression.
• Range Test whether the value of an expression falls within a specified range of values.
• Set membership Test whether the value of an expression equals one of a set of values.
• Pattern match Test whether a string matches a specified pattern.
• Null Test whether a column has a null (unknown) value.
Comparison search condition
SELECT * FROM students where due_fees <=20000;
Compound comparison search condition
SELECT * FROM Branch WHERE city = ‘London’ OR city = ‘Glasgow’;
Range search condition (BETWEEN/NOT BETWEEN)
SELECT staffNo, fName, IName, position, salary FROM Staff WHERE salary BETWEEN
20000 AND 30000;
Set membership search condition (IN/NOT IN)
SELECT staffNo, fName, IName, position FROM Staff WHERE position IN (‘Manager’,
‘Supervisor’);
Pattern match search condition (LIKE/NOT LIKE)
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
● The percent sign % represents zero, one, or multiple characters
● The underscore sign _ represents one, single character
Example
Sort the products by price:
✔ SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table. It returns a single value.
✔ The ISO standard defines five aggregate functions:
• COUNT – returns the number of values in a specified column
• SUM – returns the sum of the values in a specified column
• AVG – returns the average of the values in a specified column
• MIN – returns the smallest value in a specified column
• MAX – returns the largest value in a specified column
The COUNT function is used to Count the number of rows in a database table.
Use of COUNT(*)
Use of COUNT(DISTINCT)
SELECT COUNT(DISTINCT COURSE) FROM PRODUCT_MAST;
Sum function is used to calculate the sum of all selected columns. It works on numeric fields only
SELECT SUM(SALARY) FROM EMPLOYEE;
The AVG function is used to calculate the average value of the numeric type.
SELECT AVG(SALARY) FROM EMPLOYEE;
MAX function is used to find the maximum value of a certain column.
SELECT MAX (SALARY) FROM EMPLOYEE;
MIN function is used to find the minimum value of a certain column.
SELECT MAX (SALARY) FROM EMPLOYEE;
The GROUP BY statement groups rows that have the same values into summary rows, like "find
the number of customers in each country".
Example
Now, let's say you want to find the total salary for each department
SELECT department, SUM(salary) AS total_salary FROM employee GROUP BY Department;
| employee_id | employee_name | department | salary |
|-------------|---------------|------------|--------|
|1 | John | HR | 50000 |
|2 | Mary | IT | 60000 |
|3 | Bob | HR | 55000 |
|4 | Alice | IT | 62000 |
|5 | James | Finance | 70000 |
|6 | Emily | Finance | 75000 |
| department | total_salary |
|------------|--------------|
| HR | 105000 |
| IT | 122000 |
| Finance | 145000 |
● (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
An INNER JOIN retrieves rows from both tables where there is a match based on the specified
condition
Let's consider two tables 1. Employee Table
| employee_id | employee_name | department_id | salary |
|-------------|---------------|---------------|--------|
|1 | John |1 | 50000 |
|2 | Mary |2 | 60000 |
|3 | Bob |1 | 55000 |
|4 | Alice |2 | 62000 |
|5 | James |3 | 70000 |
|6 | Emily |3 | 75000 |
2.Department Table
| department_id | department_name |
|---------------|------------------|
|1 | HR |
|2 | IT |
|3 | Finance |
SELECT *
FROM employee e
WHERE NOT EXISTS (
SELECT 1
FROM employee
WHERE department_id IS NULL
AND employee.employee_id = e.employee_id
);
Union of the sets A and B, denoted by A ∪ B, is the set of distinct elements that belong to set A
or set B, or both.
Intersection
The intersection of the sets A and B, denoted by A ∩ B, is the set of
elements that belong to both A and B i.e. set of the common elements
in A and B.
The difference between sets is denoted by ‘A – B’, which is the set containing elements that are
in A but not in B. i.e., all elements of A except the element of B.
Let's consider a scenario with two tables, students and courses, and demonstrate set operations
like UNION, INTERSECT, and EXCEPT
1.Student Table
| student_id | student_name | major |
|------------|--------------|------------|
|1 | Alice | Computer Science |
|2 | Bob | Biology |
|3 | Charlie | Physics |
|4 | David | Chemistry |
|5 | Emily | Computer Science |
2.Course Table
| student_id | course |
|------------|--------------|
|1 | Math |
|1 | Computer Science |
|2 | Biology |
|3 | Physics |
|4 | Chemistry |
|4 | Math |
|5 | Computer Science |
|5 | Physics |
STUDENT1
| stu_id | student_name |
|--------|--------------|
|1 | Alice |
|2 | Bob |
|3 | Charlie |
|4 | David |
|5 | Eve |
STUDENT 2
| stu_id | student_name |
|--------|--------------|
|1 | Alice |
|2 | Tamil |
|3 | Sumi |
|4 | Ani |
OUTPUT
| stu_id | student_name |
|--------|--------------|
|1 | Alice |
|2 | Bob |
|3 | Charlie |
|4 | David |
|5 | Eve |
|2 | Tamil |
|3 | Sumi |
|4 | Ani |
INTERSECT operation returns the common rows between the "students" and "students_2" tables
-- Perform INTERSECT operation on the students tables
SELECT stu_id, student_name FROM students
INTERSECT
SELECT stu_id, student_name FROM students_2;
OUTPUT
| stu_id | student_name |
|--------|--------------|
|1 | Alice
EXCEPT
It displays the rows which are present in the first query but absent in the second query with no
duplicates.
Example Tables:
Students Table:
stu_id student_name
1 Alice
2 Bob
3 Charlie
4 David
5 Eve
Students_2 Table:
stu_id student_name
3 Charlie
4 David
5 Eve
6 Frank
✔ SQL identifiers are used to identify objects in the database, such as table names, view
names, and columns.
✔ The characters that can be used in a user-defined SQL identifier must appear in a
character set.
✔ The ISO standard provides a default character set, which consists of the uppercase letters
A . . . Z, the lowercase letters a . . . z, the digits 0 . . . 9, and the underscore (_)
✔ It is also possible to specify an alternative character set.
✔ The following restrictions are imposed on an identifier:
Large objects-
✔ A large object is a data type that holds a large amount of data, such as a long text file
or a graphics file.
✔ Three different types of large object data types are defined in SQL:
✔ Binary Large Object (BLOB), a binary string that does not have a character set or
collation association;
✔ Character Large Object (CLOB) and National Character Large Object
(NCLOB), both character strings.
Scalar operators-
✔ SQL provides a number of built-in scalar operators and functions that can be used to
construct a scalar expression, that is, an expression that evaluates to a scalar value.
(a) CHECK
sex CHAR NOT NULL
CHECK (sex IN (‘M’, ‘F’))
For example:
CREATE DOMAIN SexType AS CHAR
CHECK (VALUE IN (‘M’, ‘F’));
sex SexType NOT NULL
● The PRIMARY KEY clause can be specified only once per table.
● It is still possible to ensure uniqueness for any alternate keys in the table using the
keyword UNIQUE.
● Every column that appears in a UNIQUE clause must also be declared as NOT NULL.
● There may be as many UNIQUE clauses per table as required.
client No VARCHAR (5) NOT NULL,
property No VARCHAR (5) NOT NULL,
UNIQUE (client No, property No)
Referential Integrity-
✔ Referential integrity means that, if the foreign key contains a value, that value must refer to an
existing, valid row in the table.
✔ A foreign key is a column, or set of columns, that links each row in the child table containing
the foreign key to the row of the parent table containing the matching candidate key value.
✔ The ISO standard supports the definition of foreign keys with the FOREIGN KEY clause in the
CREATE and ALTER TABLE statements.
For example, to define the foreign key branchNo of the PropertyForRent table, we include the
clause:
FOREIGN KEY(branchNo) REFERENCES Branch
General Constraints-
✔ The ISO standard allows general constraints to be specified using the CHECK and UNIQUE
clauses of the CREATE and ALTER TABLE statements and the CREATE ASSERTION
statement.
✔ The CREATE ASSERTION statement is an integrity constraint that is not directly linked with
a table definition.
The format of the statement is:
CREATE ASSERTION Assertion Name
CHECK (search Condition)
Example:
CREATE ASSERTION StaffNotHandlingTooMuch
CHECK (NOT EXISTS (SELECT staff No
FROM PropertyForRent
GROUP BY staff No
HAVING COUNT (*) > 100))
2.4.4 DATA DEFINITION:
✔ 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.
1. Creating a Database
2. Creating a Table (CREATE TABLE)
3. Changing a Table Definition (ALTER TABLE)
4. Removing a Table (DROP TABLE)
5. Creating an Index (CREATE INDEX)
6. Removing an Index (DROP INDEX)
CREATE A DATABASE:
CREATE: This command is used to create tables in the relational database, triggers
and other database objects.
This can be done by specifying the names and datatypes of various columns.
CREATE A TABLE:
The CREATE TABLE statement creates a table called Table Name consisting of one or more
columns of the specified datatype.
Syntax:
CREATE TABLE TABLE_NAME
(
column_name1 datatype1,
column_name2 datatype2,
column_name3 datatype3,
column_name4 datatype4
);
for example:
CREATE TABLE
Employee
(Student_id INT,
Name VARCHAR (100),
Marks INT);
Example:
ALTER TABLE Student
ADD
(Address VARCHAR (200));
Example:
ALTER TABLE
Employee
RENAME
Marks TO Age;
The command above will change the column_name from Marks to Age;
For example:
ALTER TABLE Employee
DROP
(Age);
For example:
ALTER TABLE
student
MODIFY
(name varchar (300));
The above command will modify the column_name “Name” by changing the size of that
column.
Syntax –
DROP TABLE table_name
This will delete all the records as well as the structure of the table.
This is the main difference between TRUNCATE AND DROP. -
TRUNCATE only removes the records whereas DROP completely destroys the table.
Example:
DROP TABLE Student;
This command will remove the table records as well as destroy the schema too.
CREATE INDEX:
✔ The CREATE INDEX statement will create indexes in tables.
✔ Indexes are used for data procurement from the databases faster.
✔ The users cannot see the indexes, they are running in the background of queries, used to
speed up searches/queries.
Query:
CREATE INDEX City
ON Customer (Country);
Note that = This code does not produce any output directly visible to the user. When an index is
created in a database, the database management system updates its internal data structures to
include the new index, but this process does not produce any output that is visible to the user.
Query:
SELECT * FROM sqlite_master WHERE
type = 'index' AND tbl_name = 'Customer';
Output:
DROP INDEX:
The DROP INDEX statement could be used to remove an index from any table.
Syntax:
DROP INDEX tablename.indexname; (or)
DROP INDEX index_name ON table_name;
Query:
DROP INDEX City;
Output:
2.5 VIEWS:
b) Student Marks
CREATING VIEWS:
We can create a View using the CREATE VIEW statement. A View can be created from a single
table or multiple tables.
Syntax:
Output:
Example:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
Output:
EXAMPLE-1: Create a horizontal view
A horizontal view restricts a user’s access to selected rows of one or more tables.
DELETING VIEWS:
A view can be deleted using the Drop View statement.
Syntax:
DROP VIEW view_name;
Example:
DROP VIEW MarksView;
(b) Grouped views may never be joined with a base table or a view.
For example, StaffProp Can't view is a grouped view, so any attempt to join this view with
another table or view fails.
ADVANTAGES:
✔ Data Independence - A view can present a consistent, unchanging picture of the structure of the
database, even if the underlying source tables are changed.
✔ Currency - Changes to any of the base tables in the defining query are immediately reflected in
the view.
✔ Improved security - Each user can be given the privilege to access the database only through a
small set of views that contain the data appropriate for that user, thus restricting and controlling
each user’s access to the database.
✔ Reduced complexity - A view can simplify queries, by drawing data from several tables into a
single table, thereby transforming multi-table queries into single-table queries.
✔ Convenience - Views can provide greater convenience to users as users are presented with only
that part of the database that they need to see. This also reduces the complexity from the user’s
point of view.
✔ Customization - Views provide a method to customize the appearance of the database, so that
the same underlying base tables can be seen by different users in different ways.
✔ Data integrity - If the WITH CHECK OPTION clause of the CREATE VIEW statement is
used, then SQL ensures that no row that fails to satisfy the WHERE clause of the defining query
is ever added to any of the underlying base table(s) through. the view, thereby ensuring the
integrity of the view.
DISADVANTAGES:
✔ Update restriction - In some cases, a view cannot be updated.
✔ Structure restriction - The structure of a view is determined at the time of its creation. If the
defining query was of the form SELECT * FROM . . ., then the * refers to the columns of the
base table present when the view is created. If columns are subsequently added to the base table,
then these columns will not appear in the view, unless the view is dropped and recreated.
✔ Performance - There is a performance penalty to be paid when using a view. In some cases,
this will be negligible; in other cases, it may be more problematic.
Example:
CREATE VIEW StaffPropRent (staffNo)
AS SELECT DISTINCT staffNo
FROM PropertyForRent
WHERE branchNo = ‘B003’ AND rent > 400;
2.5.4 TRANSACTIONS:
✔ The ISO standard defines a transaction model based on two SQL statements: COMMIT
and ROLLBACK.
✔ A transaction is a logical unit of work consisting of one or more SQL statements that is
guaranteed to be atomic with respect to recovery.
✔ The standard specifies that an SQL transaction automatically begins with a transaction-
initiating SQL statement executed by a user or program (for example, SELECT,
INSERT, UPDATE).
✔ Changes made by a transaction are not visible to other concurrently executing
transactions until the transaction completes.
The READ ONLY and READ WRITE qualifiers indicate whether the transaction is read-only or
involves both read and write operations. READ ONLY allows a transaction to issue INSERT,
UPDATE, and DELETE statements against temporary tables.
The isolation level indicates the degree of interaction that is allowed from other transactions
during the execution of the transaction.
•Dirty read - A transaction reads data that has been written by another as yet uncommitted
transaction.
•Non repeatable read - A transaction rereads data that it has previously read, but another
committed transaction has modified or deleted the data in the intervening period.
•Phantom read - A transaction executes a query that retrieves a set of rows satisfying a certain
search condition.
✔ Mandatory access control - Each database object is assigned a certain classification level and
each subject is given a designated clearance level. The classification levels form a strict ordering
(Top Secret > Secret > Confidential > Unclassified) and a subject requires the necessary clearance
to read or write a database object. The most commonly used mandatory access control model is
known as Bell–LaPadula (Bell and La Padula, 1974).
SQL supports only discretionary access control through the GRANT and REVOKE statements.
The mechanism is based on the concepts of authorization identifiers, ownership, and privileges.
✔ Ownership - Each object that is created in SQL has an owner. The owner is identified by the
authorization identifier defined in the AUTHORIZATION clause of the schema to which the
object belongs.
The owner is initially the only person who may know of the existence of the object and,
consequently, perform any operations on the object.
Privileges:
Privileges are the actions that a user is permitted to carry out on a given base table
or view. The privileges defined by the ISO standard are:
• SELECT—the privilege to retrieve data from a table;
• INSERT—the privilege to insert new rows into a table;
• UPDATE—the privilege to modify rows of data in a table;
• DELETE—the privilege to delete rows of data from a table;
• REFERENCES—the privilege to reference columns of a named table in integrity constraints;
• USAGE—the privilege to use domains, collations, character sets, and translations.
✔ The GRANT statement allows the keyword ALL PRIVILEGES to be used to grant all
privileges to a user instead of having to specify the six privileges individually.
✔ It also provides the keyword PUBLIC to allow access to be granted to all present and
future authorized users, not just to the users currently known to the DBMS.
✔ Object Name can be the name of a base table, view, domain, character set, collation, or
translation.
✔ The WITH GRANT OPTION clause allows the user(s) in the Authorization List to pass
the privileges they have been given for the named object on to other users.
✔ If these users pass a privilege on specifying WITH GRANT OPTION, the users receiving
the privilege may in turn grant it to still other users.
The keyword ALL PRIVILEGES refers to all the privileges granted to a user by the user
revoking the privileges. The optional GRANT OPTION FOR clause allows privileges passed on
via the WITH GRANT OPTION of the GRANT statement to be revoked separately from the
privileges themselves.
2.6.2 DECLARATIONS:
Variables and constant variables must be declared before they can be referenced in
other statements, including other declarative statements.
✔ The Declare section starts with the DECLARE keyword in which variables, constants,
records as cursors can be declared which stores data temporarily. It basically consists of
definitions of PL/SQL identifiers. This part of the code is optional.
✔ The Execution section starts with BEGIN and ends with the 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.
✔ The Exception section starts with the 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.
2.6.3 ASSIGNMENTS:
In the executable part of a PL/SQL block, variables can be assigned in two ways:
● Using the normal assignment statement (: =) or
● The SQL SELECT or FETCH statement.
Example:
vStaffNo :5 ‘SG14’;
vRent :5 500;
SELECT COUNT (*) INTO x FROM PropertyForRent WHERE staffNo 5 vStaffNo;
In the third case, the variable x is set to the result of the SELECT statement (in this case, equal to
the number of properties managed by staff member SG14).Note that in the SQL standard, an
assignment uses the SET keyword at the start of the line with the “5” symbol, instead of the “:5”.
For example:
SET vStaffNo 5 ‘SG14’
Decision making statements are those statements which are in charge of executing a statement
out of multiple given statements based on some condition. The condition will return either true or
false. Based on what the condition returns, the associated statement is executed.
For example - if someone says, If I get 40 marks, I will pass the exam, else I will fail. In this
case the condition is getting 40 marks, if it's true then the person will pass else he/she will fail.
IF…THEN STATEMENT:
1. The if statement, or the if...then statement can be used when there is only a single
condition to be tested.
2. If the result of the condition is TRUE then a certain specified action will be performed,
otherwise if it is FALSE then no action is taken and the control of the program will just
move out of the if code block.
Syntax:
if <test_condition> then
body of action
end if;
Flowchart:
Example:
set serveroutput on;
DECLARE
x int: =10;
y int: =80;
BEGIN
if(y>x) then
dbms_output.put_line('Result: ' ||y|| ' is greater than ' ||x);
end if;
END;
Output:
Result: 80 is greater than 10
PL/SQL procedure successfully completed.
Syntax:
if <test_condition> then
statement 1/set of statements 1
else
statement 2/set of statements 2
end if;
Flowchart:
Example:
set serveroutput on;
DECLARE
x int;
BEGIN
x: = &x;
if mod(x,2) = 0 then
dbms_output.put_line('Even Number');
else
dbms_output.put_line('Odd Number');
end if;
END;
Output:
Enter value for x:6
Even Number
PL/SQL procedure successfully completed.
IF…THEN…ELSEIF…ELSE STATEMENT:
1. It is used to check multiple conditions.
2. If...then...elseif...else statement is suitable in which all the conditions are tested one by
one and whichever condition is found to be TRUE, that block of code is executed. And if
all the conditions result in FALSE then the else part is executed.
Syntax:
if <test_condition1> then
body of action
elseif <test_condition2>then
body of action
elseif<test_condition3>then
body of action
...
...
...
else
body of action
end if;
Flowchart:
Example:
set serveroutput on;
DECLARE
a int;
b int;
BEGIN
a: = &a;
b: = &b;
if(a>b) then
dbms_output.put_line(‘a is greater than b’);
elsif(b>a) then
dbms_output.put_line(‘b is greater than a’);
else
dbms_output.put_line(‘Both a and b are equal’);
end if;
END;
Output:
Enter value for a: 8
Enter value for b: 5
a is greater than b
PL/SQL procedure successfully completed.
CASE STATEMENT:
1. If we try to describe the case statement in one line then, then we can say it means "one
out of many".
2. It is a decision-making statement that selects only one option out of the multiple available
options.
3. It uses a selector.
4. This selector can be a variable, function or procedure that returns some value and on the
basis of the result one of the case statements is executed. If all the cases fail then the else
case is executed.
Syntax:
CASE selector
when value1 then Statement1;
when value2 then Statement2;
...
...
else statement;
end CASE;
Example:
set serveroutput on;
DECLARE
a int;
b int;
BEGIN
a: = &a;
b: = mod(a,2);
CASE b
when 0 then dbms_output.put_line('Even Number');
when 1 then dbms_output.put_line('Odd Number');
else dbms_output.put_line('User has not given any input value to check');
END CASE;
END;
Output:
Enter the value for a:7
Odd number
PL/SQL procedure successfully completed.
SEARCH CASE STATEMENT:
1. In this type of case statement, no selector is used but a test condition is checked by using
the WHEN clause itself.
2. When the condition is TRUE the statements following it are executed otherwise other test
conditions are checked using the WHEN clause sequentially. And if all the test conditions
fail then the else case is executed.
Syntax:
CASE
when <test_condition1> then statement1;
when <test_condition2> then statement2;
...
...
else default statement;
end case;
Example:
set serveroutput on;
DECLARE
dt Date;
str varchar2(10);
BEGIN
dt: = '&date';
str: = to_char(dt,'DY');
CASE
when str in ('SAT','SUN') then dbms_output.put_line('It’s the Weekend');
else dbms_output.put_line('Not a Weekend');
END CASE;
END;
Output:
Enter the value for dt:28-APR-2019
Weekend date
PL/SQL procedure successfully completed.
Syntax:
LOOP
Loop statements
Conditional exit using EXIT|EXIT
WHEN
END LOOP;
Flowchart:
Example:
DECLARE
i NUMBER: = 1;
BEGIN
LOOP
EXIT WHEN i>5;
dbms_output.put_line(i);
i := i+1;
END LOOP;
END;
Output:
1
2
3
4
5
WHILE LOOP:
It is used when a set of statements should be executed as long as the condition is true.
The condition is decided at the beginning of each iteration and continues until the condition
becomes false.
Syntax:
WHILE <test_condition> LOOP
<action>
END LOOP;
Flowchart:
Example:
set serveroutput on;
DECLARE
num int: =1;
BEGIN
while (num <= 10) LOOP
dbms_output.put_line(''|| no);
num: = num+2;
END LOOP;
END;
Output:
1
3
5
7
9
PL/SQL procedure successfully completed.
Syntax:
Syntax:
FOR counter_variable IN start_value.end_value LOOP
statement to be executed
END LOOP;
Flowchart:
Example:
set serveroutput on;
DECLARE
i number (2);
BEGIN
FOR i IN 1...5 LOOP
dbms_output.put_line(i);
END LOOP;
END;
Output:
1
2
3
4
5
PL/SQL procedure successfully completed.
Syntax:
Example:
myLoop1:
FOR iStaff AS SELECT COUNT (*) FROM PropertyForRent
WHERE staffNo 5 ‘SG14’ DO
.....
END FOR myLoop1;
Syntax:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
Exception1-handling-statements
WHEN exception2 THEN
Exception2-handling-statements
WHEN exception3 THEN
Exception3-handling-statements
……..
WHEN others THEN
Exception3
Example:
DECLARE
C_id customers.id%type := 8;
C_name customerS.Name%type;
C_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE (‘Name: ‘|| c_name);
DBMS_OUTPUT.PUT_LINE (‘Address: ‘ || c_addr);
EXCEPTION
WHEN no_data_found THEN
Dbms_output.put_line(‘No such customer!’);
WHEN others THEN
Dbms_output.put_line(‘Error!’);
END;
/
Output:
No such customer!
RAISING EXCEPTIONS:
✔ In the case of any internal database error, exceptions are raised by the database server
automatically.
✔ But it can also be raised explicitly by programmers by using command RAISE.
Syntax:
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
USER-DEFINED EXCEPTIONS:
✔ An exception can be defined by the programmer while writing the code; such types of
exceptions are called User-defined exceptions.
✔ User defined exceptions are in general defined to handle special cases where our code can
generate exceptions due to our code logic.
Syntax:
DECLARE
<exception name> EXCEPTION
BEGIN
<sql sentence>
If <test_condition> THEN
RAISE <exception_name>;
END IF;
EXCEPTION
WHEN <exception_name> THEN
-- some action
END;
Example:
Query:
set serveroutput on;
DECLARE
sno student.rollno%type;
snm student.sname%type;
crno student.total_course%type;
invalid_total EXCEPTION;
BEGIN
sno := &rollno;
snm := '&sname';
crno:=total_courses;
IF (crno > 3) THEN
RAISE invalid_total;
END IF;
INSERT into student values(sno, snm, crno);
EXCEPTION
WHEN invalid_total THEN
dbms_output.put_line('Total number of courses cannot be more than 3');
END;
Output:
Enter the value for sno:15
Enter the value for snm:Akash
Enter the value for crno:5
Total number of courses cannot be more than 3
PL/SQL procedure successfully completed.
✔ PL/SQL provides many pre-defined exceptions, which are executed when any database
rule is violated by a program.
✔ Oracle has predefined some common exceptions.
✔ These exceptions have a unique exception name and error number.
✔ These exceptions are already defined in the ‘STANDARD’ package in Oracle.
In code, we can directly use these predefined exception names to handle them.
Example:
set serveroutput on;
DECLARE
a int;
b int;
c int;
BEGIN
a := &a;
b := &b;
c := a/b;
dbms_output.put_line('RESULT=' || c);
EXCEPTION
when ZERO_DIVIDE then
dbms_output.put_line('Division by 0 is not possible');
END;
Output:
Enter the value for a:10
Enter the value for b:0
Division by 0 is not possible
PL/SQL procedure successfully completed.
✔ PL/SQL uses cursors to allow the rows of a query result to be accessed one at a time.
✔ In effect, the cursor acts as a pointer to a particular row of the query result. The cursor
can be advanced by 1 to access the next row.
✔ A cursor must be declared and opened before it can be used, and it must be closed to
deactivate it after it is no longer required.
✔ Once the cursor has been opened, the rows of the query. A SELECT statement can be
used if the query returns one and only one row.
✔ To handle a query that can return an arbitrary number of rows (that is, zero, one, or more
rows).
Passing parameters to cursors- PL/SQL allows cursors to be parameterized, so that the same
cursor definition can be reused with different criteria.
For example:
CURSOR propertyCursor (vStaffNo VARCHAR2) IS
SELECT propertyNo, street, city, postcode
FROM PropertyForRent
WHERE staffNo 5 vStaffNo
ORDER BY propertyNo;
and we could open the cursor using the following example statements:
vStaffNo1 PropertyForRent.staffNo%TYPE :5 ‘SG14’;
OPEN propertyCursor(‘SG14’);
OPEN propertyCursor(‘SA9’);
OPEN propertyCursor(vStaffNo1);
✔ It is possible to update and delete a row after it has been fetched through a cursor.
✔ In this case, to ensure that rows are not changed between declaring the cursor, opening it,
and fetching the rows in the active set, the FOR-UPDATE clause is added to the cursor
declaration.
✔ This has the effect of locking the rows of the active set to prevent any update conflict
when the cursor is opened.
CURSOR propertyCursor IS
SELECT propertyNo, street, city, postcode
FROM PropertyForRent
WHERE staffNo 5 ‘SG14’
ORDER BY propertyNo
FOR UPDATE NOWAIT;
UPDATE PropertyForRent
SET staffNo 5 ‘SG37’
WHERE CURRENT OF propertyCursor;
...
COMMIT;
2.6.7 SUBPROGRAMS, STORED PROCEDURES, FUNCTIONS, AND PACKAGES:
✔ Subprograms are named PL/SQL blocks that can take parameters and be invoked.
✔ PL/SQL has two types of subprograms called (stored) procedures and functions.
✔ Procedures and functions can take a set of parameters given to them by the calling
program and perform a set of actions.
✔ Both can modify and return data passed to them as a parameter.
✔ The difference between a procedure and a function is that a function will always return a
single value to the caller, whereas a procedure does not.
✔ Usually, procedures are used unless only one return value is needed.
✔ Procedures and functions are very similar to those found in most high-level programming
languages, and have the same advantages: they provide modularity and extensibility, they
promote reusability and maintainability, and they aid abstraction.
A parameter has a specified name and data type but can also be designated as:
• IN – parameter is used as an input value only.
• OUT – parameter is used as an output value only.
• IN OUT – parameter is used as both an input and an output value.
Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [, parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Example:
CREATE OR REPLACE PROCEDURE
welcome_msg (p_name IN VARCHAR2)
IS
BEGIN
dbms_output.put_line (‘Welcome '|| p_name);
END;
/
EXEC welcome_msg (‘Charles’);
Output: Welcome Charles.
Example:
set serveroutput on;
CREATE OR REPLACE FUNCTION Sum
(a IN number, b IN number)
RETURN Number IS
c number;
BEGIN
c := a+b;
RETURN c;
END;
Control RETURN will simply exit the RETURN will exit the control
control from the subprogram. from the subprogram and also
returns the value.
Data Type Return data type will not be Return data type is mandatory
specified at the time of at the time of creation
creation
PACKAGES:
✔ A package is a collection of procedures, functions, variables, and SQL statements that are
grouped together and stored as a single program unit.
✔ A package has two parts: a specification and a body.
✔ A package’s specification declares all public constructs of the package, and the body
defines all constructs (public and private) of the package, and so implements the
specification.
✔ In this way, packages provide a form of encapsulation.
Oracle performs the following steps when a procedure or package is created:
•It compiles the procedure or package.
•It stores the compiled code in memory.
•It stores the procedure or package in the database.
Example:
CREATE PACKAGE cust_sal AS
PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
Output: Package Created
Package Specification:
✔ The specification is the interface to the package.
✔ It just DECLARES the types, variables, constants, exceptions, cursors, and subprograms that
can be referenced from outside the package.
✔ In other words, it contains all information about the content of the package, but excludes the
code for the subprograms.
✔ All objects placed in the specification are called public objects.
✔ Any subprogram not in the package specification but coded in the package body is called a
private object.
Example:
CREATE OR REPLACE PACKAGE pkg_student IS
PROCEDURE updateRecord(sno student.rollno%type);
FUNCTION deleteRecord(snm student.sname%type)
RETURN boolean;
END pkg_student;
Package Body:
✔ Package body has the codes for various methods declared in the package specification and
other private declarations, which are hidden from the code outside the package.
✔ The CREATE PACKAGE BODY Statement is used for creating the package body.
Example:
CREATE OR REPLACE PACKAGE BODY cust_sal AS
PROCEDURE find_sal(c_id customers.id%TYPE) IS
c_sal customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/
Output: Package Body Created.
✔ Triggers are automatically and repeatedly called upon by the oracle engine on satisfying certain
conditions.
✔ Triggers can be activated or deactivated depending on the requirements.
✔ If triggers are activated then they are executed implicitly by oracle engine and if triggers are
deactivated then they are executed explicitly by oracle engine.
✔ A trigger defines an action that the database should take when some event occurs in the
application.
✔ A trigger may be used to enforce some referential integrity constraints, to enforce complex
constraints, or to audit changes to data.
✔ The code within a trigger, called the trigger body or trigger action, is made up of an SQL
block.
✔ Triggers are based on the Event–Condition–Action (ECA) model.
✔ The event (or events) that trigger the rule, which can be an INSERT, UPDATE, or DELETE
statement on a specified table (or possibly view).
In Oracle, it can also be:
– a CREATE, ALTER, or DROP statement on any schema object;
– a database startup or instance shutdown, or a user logon or logoff;
– a specific error message or any error message.
It is also possible to specify whether the trigger should fire before the event or after the event.
• The condition that determines whether the action should be executed. The condition is optional
but, if specified, the action will be executed only if the condition is true.
• The action to be taken. This block contains the SQL statements and code to be executed when a
triggering statement is issued and the trigger condition evaluates to true.
✔ Row-level triggers (FOR EACH ROW) that execute for each row of the table that is
affected by the triggering event.
✔ Statement-level triggers (FOR EACH STATEMENT) that execute only once even if
multiple rows are affected by the triggering event.
✔ SQL also supports INSTEAD OF triggers, which provide a transparent way of modifying
views that cannot be modified directly through SQL DML statements (INSERT,
UPDATE, and DELETE).
✔ These triggers are called INSTEAD OF triggers because, unlike other types of trigger, the
trigger is fired instead of executing the original SQL statement.
✔ Triggers can also activate themselves one after the other.
✔ This can happen when the trigger action makes a change to the database that has the
effect of causing another event that has a trigger associated with it to fire.
✔ The BEFORE keyword indicates that the trigger should be executed before an insert is
applied to the PropertyForRent table.
✔ The FOR EACH ROW keyword indicates that this is a row-level trigger, which executes
for each row of the PropertyForRent table that is updated in the statement.
Example:
CREATE OR REPLACE TRIGGER CheckAge
BEFORE
INSERT OR UPDATE ON student
FOR EACH ROW
BEGIN
IF :new.Age>30 THEN
raise_application_error(-20001, 'Age should not be greater than 30');
END IF;
END;
BENEFITS OF TRIGGERS:
Following are the benefits of triggers.
ADVANTAGES OF TRIGGERS:
✔ Elimination of redundant code- Instead of placing a copy of the functionality of the trigger in
every client application that requires it, the trigger is stored only once in the database.
✔ Simplifying modifications- Changing a trigger requires changing it in one place only; all the
applications automatically use the updated trigger.
Thus, they are only coded once, tested once, and then centrally enforced for all the applications
accessing the database.
✔ Increased security- Storing the triggers in the database gives them all the benefits of
security provided automatically by the DBMS.
✔ Improved integrity- Triggers can be extremely useful for implementing some types of
integrity constraints Storing triggers in the database means that integrity constraints can be
enforced consistently by the DBMS across all applications.
✔ Improved processing power- Triggers add processing power to the DBMS and to the database
as a whole
.
✔ Good fit with the client-server architecture- The central activation and processing of triggers
fits the client-server architecture well.
DISADVANTAGES OF TRIGGERS:
✔ Performance overhead- The management and execution of triggers have a performance
overhead that has to be balanced against the advantages cited previously.
✔ Cascading effects- The action of one trigger can cause another trigger to be fired, and so on, in
a cascading manner.
✔ Cannot be scheduled- Triggers cannot be scheduled; they occur when the event that they are
based on happens.
✔ Less portable- Most DBMSs implement their own dialect for triggers, which affects portability.
2.6.9 RECURSION:
✔Atomicity of data means that repeating groups are not allowed in the relational model.
✔As a result, it is extremely difficult to handle recursive queries, that is, queries about
relationships that a relation has with itself (directly or indirectly).
Example:
WITH RECURSIVE
AllManagers (staffNo, managerStaffNo) AS
(SELECT staffNo, managerStaffNo
FROM Staff
UNION
SELECT in.staffNo, out.managerStaffNo
FROM AllManagers in, Staff out
WHERE in.managerStaffNo 5 out.staffNo);
SELECT * FROM AllManagers
ORDER BY staffNo, managerStaffNo;
For example,
SEARCH BREADTH FIRST BY staffNo, managerStaffNo
SET orderColumn
The SET clause identifies a new column name (orderColumn), which is used by SQL to order
the result into the required breadth-first traversal.
The recursive statement has a CYCLE clause that instructs SQL to record a specified value to
indicate that a new row has already been added to the result table.
Whenever a new row is found, SQL checks that the row has not been added previously by
determining whether the row has been marked with the specified value.
If it has, then SQL assumes a cycle has been encountered and stops searching for further
result rows.
********************