0% found this document useful (0 votes)
29 views82 pages

DDM 2

Uploaded by

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

DDM 2

Uploaded by

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

UNIT-2

RELATIONAL MODEL & SQL

2.1 Relational Model concepts


2.2 Integrity Constraints
2.3 SQL Data Manipulation
2.4 SQL Data Definition
2.5 Views
2.6 SQL Programming
2.1 RELATIONAL MODEL CONCEPTS:
2.1.1 INTRODUCTION TO RELATIONAL MODEL:

✔ 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.

2.1.2 HISTORY OF RELATIONAL MODEL:

✔ 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).

The relational model’s objectives were specified as follows:

✔ To allow a high degree of data independence.


✔ Application programs must not be affected by modifications to the internal data
representation, particularly by changes to file organizations, record orderings, or access
paths.
✔ To provide substantial grounds for dealing with data semantics, consistency, and
redundancy problems. In particular, Codd’s paper introduced the concept of normalized
relations, that is, relations that have no repeating groups.
✔ To enable the expansion of set-oriented data manipulation languages.

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.

2.1.3 TERMINOLOGIES IN RELATIONAL MODEL:


The relational model is based on the mathematical concept of a relation, which is
physically represented as a table.
RELATIONAL DATA STRUCTURES:
Relation -A relation is a table with columns and rows.
● In the relational model, relations are used to hold information about the objects to be
represented in the database.
● A relation is represented as a two-dimensional table in which the rows of the table
correspond to individual records and the table columns correspond to attributes.
Attribute - An attribute is a named column of a relation.
● Attributes can appear in any order and the relation will still be the same relation, and
therefore will convey the same meaning.
Domain - A domain is the set of allowable values for one or more attributes.
● Domains are an extremely powerful feature of the relational model. Every attribute in a
relation is defined on a domain.
● Domains may be distinct for each attribute, or two or more attributes may be defined on
the same domain.
Example:
The information on branch offices is represented by the Branch relation, with columns for
attributes branch No (the branch number), street, city, and postcode.
Similarly, the information on staff is represented by the Staff relation, with columns for attributes
staff No (the staff number), fName, IName, position, sex, DOB (date of birth), salary, and
branchNo (the number of the branch the staff member works at).
Figure1, shows instances of the Branch and Staff relations.

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:

✔ Name of the relation is distinct from all other relations.


✔ Each relation cell contains exactly one atomic (single) value.
✔ Each attribute contains a distinct name.
✔ Attribute domain has no significance.
✔ Tuple has no duplicate value.
✔ Order of tuples can have a different sequence.

ADVANTAGES OF RELATIONAL MODEL:

✔ 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:

✔ Data is represented in rows and columns called relations.


✔ Data is stored in tables having relationships between them called the Relational model.
✔ The relational model supports the operations like Data definition, Data manipulation, and
Transaction management.
✔ Each column has a distinct name and they are representing attributes.
✔ Each row represents a single entity.

2.1.7 RELATIONAL KEYS:


KEYS:

✔ Keys play an important role in the relational database.


✔ It is used to uniquely identify any record or row of data from the table.
✔ It is also used to establish and identify relationships between tables.
For example: ID is used as a key in the student table because it is unique for each student. In the
PERSON table, passport_number, license_number, SSN are keys since they are unique for each
person.

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;

REFERENTIAL INTEGRITY CONSTRAINTS:


✔ The second integrity rule applies to foreign keys.
✔ A referential integrity constraint is specified between two tables.
✔ In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary
Key of Table 2, then every value of the Foreign Key in Table 1 must be null or be
available in Table 2.
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

2.3 SQL DATA MANIPULATION:


2.3.1 INTRODUCTION TO SQL:
✔ SQL stands for Structured Query Language. It is used for storing and managing data in
relational database management systems (RDMS).
✔ It is a standard language for Relational Database Systems. It enables a user to create,
read, update and delete relational databases and tables.
✔ All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use SQL as
their standard database language.
✔ SQL allows users to query the database in a number of ways, using English-like
statements.
✔ Structure query language is not case sensitive.
✔ Statements of SQL are dependent on text lines. We can use a single SQL statement on
one or multiple text lines.
2.3.2 OBJECTIVES OF SQL:
Ideally, a database language should allow a user to:
✔ Create the database and relational structures;
✔ Perform basic data management tasks, such as the insertion, modification, and deletion of
data from the relations;
✔ Perform both simple and complex queries.

✔ SQL is an example of a transform-oriented language, or a language designed to use


relations to transform inputs into required outputs.
✔ As a language, the ISO SQL standard has two major components
o Data Definition Language (DDL) for defining the database structure and
controlling access to the data;
o Data Manipulation Language (DML) for retrieving and updating data.
✔ The command structure consists of standard English words such as CREATE TABLE,
INSERT, SELECT.
For example: – CREATE TABLE Staff (staffNo VARCHAR(5), IName
VARCHAR(15), salary DECIMAL(7,2));
– INSERT INTO Staff VALUES (‘SG16’, ‘Brown’, 8300);
– SELECT staffNo, IName, salary FROM Staff WHERE salary > 10000;Statements,
Functions, and Clauses:

2.3.3 HISTORY OF SQL:


✔ 1970 - Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational databases. He
described a relational model for databases.
✔ 1974 - Structured Query Language (SQL) appeared.
✔ 1977 - Relational Software Inc,The company that eventually became Oracle, begins
building a commercial RDBMS.
✔ 1978 - IBM worked to develop Codd's ideas and released a product named System/R.
✔ 1979 - Oracle ships first commercially available RDBMS for Digital Equipment Corp.'s
minicomputer systems.
✔ 1982 - IBM ships SQL/Data System, a SQL RDBMS for IBM mainframes.
✔ 1985 - IBM ships Database 2, a SQL RDBMS for IBM's Multiple Virtual Storage
mainframe operating system.
✔ 1986 - IBM developed the first prototype of relational database and standardized it by
ANSI. The first relational database was released by Relational Software which later came
to be known as Oracle.
✔ 1987 - SQL became part of the International Organization for Standardization (ISO).
✔ 1989 - First revision of the ISO SQL standard, SQL-89, published.
✔ 1992 - First major revision of ISQ SQL standard, SQL-92, published.
✔ 1999 - First version to be named in accordance with ISO naming standards, ISO/IEC
SQL:1999, adds programming functionality and support for Java.
✔ 2003 - ISO/IEC SQL:2003 adds support for a predefined data type for Extensible Markup
Language (XML) objects.
✔ 2006 - ISO/IEC SQL:2006 expands XML-related functionality.
✔ 2008 - ISO/IEC SQL:2008 adds support for partitioned JOINs, a method for linking two
or more tables that treats the joined tables as a single table.
✔ 2011 - ISO/IEC SQL:2011 improves support for relational databases containing time-
related data.
✔ 2016 - ISO/IEC SQL:2016 adds optional new features, including JavaScript Object
Notation-related changes, support for polymorphic table functions and row pattern
matching.

2.3.4 IMPORTANCE OF SQL:


✔ SQL is the first and, so far, only standard database language to gain wide acceptance.
✔ The only other standard database language, the Network Database Language (NDL).
based on the CODASYL network model, has few followers.
✔ Nearly every major current vendor provides database products based on SQL or with an
SQL interface, and most are represented on at least one of the standard-making bodies.
✔ There is a huge investment in the SQL language both by vendors and by users.
✔ It has become part of application architectures such as IBM’s Systems Application
Architecture (SAA) and is the strategic choice of many large and influential
organizations.
✔ For example, the Open Group consortium for UNIX standards. SQL has also become a
Federal Information Processing Standard (FIPS) to which conformity is required for
all sales of DBMSs to the U.S. government.
✔ The SQL Access Group, a consortium of vendors, defined a set of enhancements to SQL
that would support interoperability across disparate systems.
✔ SQL is used in other standards and even influences the development of other standards as
a definitional tool.
✔ Examples include ISO’s Information Resource Dictionary System (IRDS) standard
and Remote Data Access (RDA) standard.
✔ The development of the language is supported by considerable academic interest,
providing both a theoretical basis for the language and the techniques needed to
implement it successfully.
✔ SQL is especially true in query optimization, distribution of data, and security.
✔ There are now specialized implementations of SQL that are directed at new markets, such
as Online Analytical Processing (OLAP).
2.3.5 TERMINOLOGY:
✔ The ISO SQL standard does not use the formal terms of relations, attributes, and tuples,
instead using the terms tables, columns, and rows.

2.3.7 WRITING SQL COMMENTS:

✔ An SQL statement consists of reserved words and user-defined words.

✔ 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.

Types of SQL Commands:


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1. Data Definition Language (DDL):


✔ DDL changes the structure of the table like creating a table, deleting a table, altering a
table, etc.
✔ All the commands of DDL are auto-committed, which means it permanently saves all the
changes in the database.

2. Data Manipulation Language (DML):


✔ DML commands are used to modify the database. It is responsible for all forms of
changes in the database.
✔ The command of DML is not auto-committed, which means it can't permanently save all
the changes in the database. They can be rolled back.

3. Data Control Language (DCL):


✔ DCL commands are used to grant and take back authority from any database user.
✔ DCL includes commands such as GRANT and REVOKE which mainly deal with the
rights, permissions, and other controls of the database system.

4. Transaction Control Language (TCL):


✔ Transaction Control Language commands are used to manage transactions in the
database.
✔ These are used to manage the changes made by DML-statements.
✔ It also allows statements to be grouped together into logical transactions
.
5. Data Query Language (DQL):
✔ It is used for retrieving data.
✔ A user can retrieve data according to his/her requirements using the select command.

2.3.8 DATA MANIPULATION:


Here are some commands that come under DML:
List of DML commands:
✔ SELECT : to query data in the database
✔ 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 data from a database table.
DML (Data Manipulation Language) is a subset of SQL (Structured Query Language) that
deals with the manipulation of data stored in a database. Here are some simple queries in DML:
INSERT - INSERT command is used to insert new rows or records in a table.
Syntax:
INSERT INTO <table_name> ('column_name1' <datatype>, 'column_name2' <datatype>)
VALUES ('value1', 'value2');
Example:
INSERT INTO students ('stu_id' int, 'stu_name' varchar (20), 'city' varchar (20))
VALUES ('1', 'Nirmit', 'Gorakhpur');
UPDATE - This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE <table_name> SET <column_name = value> WHERE condition;
Example:
UPDATE students SET due_fees = 20000 WHERE stu_name = 'Mini';
DELETE - DELETE is used for removing one or more rows from the table.
Syntax:
DELETE FROM <table_name> WHERE <condition>;
Example:
DELETE FROM students WHERE stu_id = '001';
SELECT - This command is used to get data out of the database.
Syntax:
SELECT * FROM <table_name>;
Example:
SELECT * FROM students;
DISTINCT
The SELECT DISTINCT statement is used to return only distinct (different) values.
SELECT DISTINCT Course FROM Student;
ROW SELECTION (WHERE CLAUSE)

✔ 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

Select all customers that starts with the letter "a":

SELECT * FROM Customers WHERE CustomerName LIKE 'a%';


Null
The IS NULL operator is used to test for empty values (NULL values).
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
SELECT CustomerName, ContactName, Address FROM Customers
WHERE Address IS NULL;
Sorting Results (ORDER BY Clause)
Single-column ordering
The ORDER BY keyword is used to sort the result-set in ascending or descending order.

Example
Sort the products by price:

SELECT * FROM Products ORDER BY Price;


To sort the records in descending order, use the DESC keyword.
Example
Sort the products from highest to lowest price:
SELECT * FROM Products ORDER BY Price DESC;
Multiple column ordering
For Multiple column order, add the name of the column by which you’d like to sort records first.
The column that is entered at first place will get sorted first and likewise.
Using the SQL Aggregate Functions

✔ 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(*)

SELECT COUNT(*) FROM STUDENT;

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;

GROUPING RESULTS (GROUP BY CLAUSE)

The GROUP BY statement groups rows that have the same values into summary rows, like "find
the number of customers in each country".

The GROUP BY statement is often used with aggregate functions

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 |

The HAVING clause in SQL is used in conjunction with the GROUP BY


Example
To find departments with a total salary greater than 120,000.
SELECT department, SUM(salary) AS total_salary FROM employee
GROUP BY department
HAVING SUM(salary) > 120000;
| department | total_salary |
|------------|--------------|
| IT | 122000 |
| Finance | 145000 |
An SQL subquery is nothing but a query inside another query
Example
to find employees whose salaries are above the average salary for their respective departments
SELECT employee_id, employee_name, department, salary
FROM employee e
WHERE salary > (
SELECT AVG(salary)
FROM employee
WHERE department = e.department
);
| employee_id | employee_name | department | salary |
|-------------|---------------|------------|--------|
|2 | Mary | IT | 60000 |
|4 | Alice | IT | 62000 |
|5 | James | Finance | 70000 |
|6 | Emily | Finance | 75000 |

Nested subqueries: use of IN


find employees whose salaries are greater than the average salary for their departments, but you
want to use the IN operator with a subquery.
SELECT employee_id, employee_name, department, salary FROM employee
WHERE (department, salary) IN (
SELECT department, MAX(salary)
FROM employee
GROUP BY department
);
In this query:
1. The subquery calculates the maximum salary for each department using the MAX
function.
2. The main query then selects employees whose (department, salary) pairs are in the result
obtained from the subquery.
| employee_id | employee_name | department | salary |
|-------------|---------------|------------|--------|
|2 | Mary | IT | 60000 |
|4 | Alice | IT | 62000 |
|6 | Emily | Finance | 75000 |
In this result set, only employees whose (department, salary) pairs match the maximum salary for
their respective departments are included. The IN operator with a subquery is used to achieve
this condition.
ANY and ALL
The ANY and ALL operators in SQL are used to compare a value to a set of values returned by a
subquery.
Using ANY:
Suppose you want to find employees whose salary is greater than the highest salary in the
Finance department

SELECT employee_id, employee_name, department, salary


FROM employee
WHERE salary > ANY (
SELECT salary
FROM employee
WHERE department = 'Finance'
);
In this query:
1. The subquery returns all salaries in the Finance department.
2. The main query selects employees whose salary is greater than any of the salaries in the
Finance department.
| employee_id | employee_name | department | salary |
|-------------|---------------|------------|--------|
|2 | Mary | IT | 60000 |
|4 | Alice | IT | 62000 |
|5 | James | Finance | 70000 |
|6 | Emily | Finance | 75000 |
Using ALL:
Now, let's say you want to find employees whose salary is greater than all salaries in the Finance
department
-- Sample SQL query with ALL
SELECT employee_id, employee_name, department, salary
FROM employee
WHERE salary > ALL (
SELECT salary
FROM employee
WHERE department = 'Finance'
);
In this query:
1. The subquery returns all salaries in the Finance department.
2. The main query selects employees whose salary is greater than all of the salaries in the
Finance department.
| employee_id | employee_name | department | salary |
|-------------|---------------|------------|--------|
|6 | Emily | Finance | 75000 |
When you run the above SQL queries:
✔ For the ANY query, you might get employees with salaries greater than any salary in the
Finance department.
✔ For the ALL query, you might get employees with salaries greater than all salaries in the
Finance department.
MULTI-TABLE QUERIES
SQL Join statement is used to combine data or rows from two or more tables based on a common
field between them.

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

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 e.employee_id, e.employee_name, e.salary, d.department_name


FROM employee e
JOIN department d ON e.department_id = d.department_id;
| employee_id | employee_name | salary | department_name |
|-------------|---------------|--------|------------------|
|1 | John | 50000 | HR |
|2 | Mary | 60000 | IT |
|3 | Bob | 55000 | HR |
|4 | Alice | 62000 | IT |
|5 | James | 70000 | Finance |
|6 | Emily | 75000 | Finance |
LEFT (OUTER) JOIN:
-- Example SQL query with LEFT OUTER JOIN
SELECT e.employee_id, e.employee_name, e.salary, d.department_name
FROM employee e
LEFT OUTER JOIN department d ON e.department_id = d.department_id;
| employee_id | employee_name | salary | department_name |
|-------------|---------------|--------|------------------|
|1 | John | 50000 | HR |
|2 | Mary | 60000 | IT |
|3 | Bob | 55000 | HR |
|4 | Alice | 62000 | IT |
|5 | James | 70000 | Finance |
|6 | Emily | 75000 | Finance |

RIGHT (OUTER) JOIN


-- Example SQL query with RIGHT OUTER JOIN
SELECT e.employee_id, e.employee_name, e.salary, d.department_name
FROM employee e
RIGHT OUTER JOIN department d ON e.department_id = d.department_id;
| employee_id | employee_name | salary | department_name |
|-------------|---------------|--------|------------------|
|1 | John | 50000 | HR |
|2 | Mary | 60000 | IT |
|3 | Bob | 55000 | HR |
|4 | Alice | 62000 | IT |
|5 | James | 70000 | Finance |
|6 | Emily | 75000 | Finance |
| NULL | NULL | NULL | Marketing |
The EXISTS and NOT EXISTS operators are useful for checking the existence or non-
existence of rows based on a specified condition.
Example with EXISTS:
Let's find employees in the HR department (department_id = 1):
sql
SELECT *
FROM employee e
WHERE EXISTS (
SELECT 1
FROM employee
WHERE department_id = 1
AND employee.employee_id = e.employee_id
);
Expected result:
| employee_id | employee_name | department_id | salary |
|-------------|---------------|---------------|--------|
|1 | John |1 | 50000 |
|3 | Bob |1 | 55000 |

Example with NOT EXISTS:


Let's find employees who do not belong to any department (department_id is NULL):

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 |

-- Perform UNION operation on the students tables


SELECT stu_id, student_name FROM students
UNION
SELECT stu_id, student_name FROM students_2;

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

-- Perform MINUS operation on the students tables


SELECT stu_id, student_name FROM students
MINUS
SELECT stu_id, student_name FROM students_2;
OUTPUT
| stu_id | student_name |
|--------|--------------|
|1 | Alice |
|2 | Bob |

2.4 SQL DATA DEFINITION:


2.4.1 SQL IDENTIFIERS:

✔ 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:

● An identifier can be no longer than 128 characters.


● An identifier must start with a letter;
● An identifier cannot contain spaces.

ISO SQL data types table:


2.4.2 SQL SCALAR DATA TYPES:
Boolean data-
✔ Boolean data consists of the distinct truth values TRUE and FALSE. Unless prohibited
by a NOT NULL constraint, Boolean data also supports the UNKNOWN truth value as
the NULL value.
Character data-
✔ Character data consists of a sequence of characters from an implementation defined
character set, that is, it is defined by the vendor of the particular SQL dialect.
✔ Thus, the exact characters that can appear as data values in a character type column will
vary. ASCII and EBCDIC are two sets in common use today.
✔ The format for specifying a character data type is:
CHARACTER [VARYING] [length]
CHARACTER can be abbreviated to CHAR and
CHARACTER VARYING to VARCHAR.
Bit data-
✔ The bit data type is used to define bit strings, that is, a sequence of binary digits (bits),
each having either the value 0 or 1.
✔ The format for specifying the bit data type is similar to that of the character data type:
BIT [VARYING] [length]
Exact Numeric Data-
✔ The exact numeric data type is used to define numbers with an exact representation.
✔ The number consists of digits, an optional decimal point, and an optional sign.
✔ An exact numeric data type consists of a precision and a scale.
A special case of exact numeric occurs with integers.
There are several ways of specifying an exact numeric data type:
NUMERIC [ precision [, scale] ]
DECIMAL [ precision [, scale] ]
INTEGER
SMALLINT
BIGINT

✔ INTEGER can be abbreviated to INT and DECIMAL to DEC.


✔ NUMERIC and DECIMAL store numbers in decimal notation.
✔ The default scale is always 0; the default precision is implementation-defined.
✔ INTEGER is used for large positive or negative whole numbers.
✔ SMALLINT is used for small positive or negative whole numbers.
✔ BIGINT for very large whole numbers. By specifying
✔ This data type, less storage space can be reserved for the data.

Approximate numeric data-


✔ The approximate numeric data type is used for defining numbers that do not have an
exact representation, such as real numbers.
✔ There are several ways of specifying an approximate numeric data type:
FLOAT [precision]
REAL
DOUBLE PRECISION
✔ The precision controls the precision of the mantissa. The precision of REAL and
DOUBLE PRECISION is implementation-defined.
Date time data-
✔ The date time data type is used to define points in time to a certain degree of accuracy.
Examples are dates, times, and times of day.
✔ The ISO standard subdivides the date time data type into YEAR, MONTH, DAY,
HOUR, MINUTE, SECOND, TIMEZONE_HOUR, and TIMEZONE_MINUTE.
✔ The latter two fields specify the hour and minute part of the time zone offset from
Universal Coordinated Time (which used to be called Greenwich Mean Time).
Three types of datetime data type are supported:
DATE
TIME [time Precision] [WITH TIME ZONE]
TIMESTAMP [time Precision] [WITH TIME ZONE]
1. DATE is used to store calendar dates using the YEAR, MONTH, and DAY fields.
2. TIME is used to store time using the HOUR, MINUTE, and SECOND fields.
3. TIMESTAMP is used to store dates and times.
4. The time Precision is the number of decimal places of accuracy to which the SECOND
field is kept. If not specified, TIME defaults to a precision of 0 (that is, whole seconds),
and TIMESTAMP defaults to 6 (that is, microseconds).
5. The WITH TIME ZONE keyword controls the presence of the TIMEZONE_HOUR and
TIMEZONE_MINUTE fields.
Interval data-
✔ The interval data type is used to represent periods of time.
✔ Every interval data type consists of a contiguous subset of the fields: YEAR, MONTH,
DAY, HOUR, MINUTE, SECOND.
✔ There are two classes of interval data type: year–month intervals and day–time intervals.
✔ The year–month class may contain only the YEAR and/or the MONTH fields; the day–
time class may contain only a contiguous selection from DAY, HOUR, MINUTE,
SECOND.

The format for specifying the interval data type is:


INTERVAL {{start Field TO Endfield} singleDatetimeField}
start Field = YEAR | MONTH | DAY | HOUR | MINUTE
[(intervalLeadingFieldPrecision)]
endField = YEAR | MONTH | DAY | HOUR | MINUTE |
SECOND[(fractionalSecondsPrecision)]
singleDatetimeField = startField | SECOND
[(intervalLeadingFieldPrecision [, fractionalSecondsPrecision])]

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.

2.4.3 INTEGRITY ENHANCEMENT FEATURE:


Integrity control consists of constraints that we wish to impose in order to protect the database
from becoming inconsistent. We consider five types of integrity constraints.
1. Required data;
2. Domain constraints;
3. Entity integrity;
4. Referential integrity;
5. General constraints.
These constraints can be defined in the CREATE and ALTER TABLE statements, as we will
explain shortly.
Required Data
✔ A null is distinct from blank or zero, and is used to represent data that is either not
available, missing, or not applicable.
✔ The ISO standard provides the NOT NULL column specified in the CREATE and
ALTER TABLE statements to provide this type of constraint.
✔ When NOT NULL is specified, the system rejects any attempt to insert a null in the
column.
✔ If NULL is specified, the system accepts nulls. The ISO default is NULL.
✔ For example, to specify that the column position of the Staff table cannot be null, we
define the column as: position VARCHAR(10) NOT NULL
Domain Constraints-
✔ Every column has a domain; in other words, a set of legal values.
✔ The ISO standard provides two mechanisms for specifying domains in the CREATE and
ALTER TABLE statements.
✔ The first is the CHECK clause, which allows a constraint to be defined on a column or
the entire table.
✔ The format of the CHECK clause is: CHECK (search Condition)

(a) CHECK
sex CHAR NOT NULL
CHECK (sex IN (‘M’, ‘F’))

(b) CREATE DOMAIN


CREATE DOMAIN Domain Name [AS] datatype
[DEFAULT default Option]
[CHECK (search Condition)]

For example:
CREATE DOMAIN SexType AS CHAR
CHECK (VALUE IN (‘M’, ‘F’));
sex SexType NOT NULL

Search Condition can involve a table lookup:


CREATE DOMAIN Branch No AS CHAR (4)
CHECK (VALUE IN (SELECT branchNoFROM Branch));
Domains can be removed using DROP DOMAIN:
DROP DOMAIN Domain Name
[RESTRICT | CASCADE]
Entity Integrity-
✔ The primary key of a table must contain a unique, nonnull value for each row.
✔ The ISO standard supports entity integrity with the PRIMARY KEY clause in the CREATE
and ALTER TABLE statements:
PRIMARY KEY (staff No)
PRIMARY KEY (client No, property No)

● 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.

Syntax to Create a Database:


CREATE Database Database_Name;

Example to Create a Database:


Create Database Books;

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);

ALTER TABLE (CHANGING THE TABLE DEFINITION):


✔ ALTER is a DDL command which changes or modifies the existing structure of the database,
and it also changes the schema of database objects.
✔ We can also add and drop constraints of the table using the ALTER command.
✔ Alter command is used for altering the table in many forms like:
● Add a column
● Rename existing column
● Drop a column
● Modify the size of the column or change datatype of the column

ADD using ALTER –

Syntax to add column:


ALTER TABLE table_name ADD (column_name datatype);

Example:
ALTER TABLE Student
ADD
(Address VARCHAR (200));

RENAME using ALTER –


Syntax to rename column:
ALTER TABLE
table_name
RENAME
old_column_name TO new_column_name;
The above command will rename the existing column to a new column.

Example:
ALTER TABLE
Employee
RENAME
Marks TO Age;

The command above will change the column_name from Marks to Age;

DROP using ALTER –

Syntax to Drop a column:


ALTER TABLE
table_name
DROp
(column_name);

The above command will delete the existing column.

For example:
ALTER TABLE Employee
DROP
(Age);

Here the column_name =” Age”, has been deleted by this command;

MODIFY using ALTER –

Syntax to Modify a column:


ALTER TABLE
Employee MODIFY
(column_name datatype);

The above command will modify the existing column.

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.

DROP TABLE (REMOVING A TABLE):


This command completely removes the table from the database along with the destruction of the
table structure.

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.

Create an index on a table:


Syntax:
CREATE INDEX index_name ON table_name (column_name 1, column_name2, …);
Create a unique index on a table:
Syntax:
CREATE UNIQUE INDEX index_name ON table_name (column_name 1, column_name2, …);
Let’s take an example of a Customer Table where we will insert the ‘City” column on “Country:
in the SQL statement.
Example:
CREATE TABLE Customer (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR (50),
LastName VARCHAR (50),
Country VARCHAR (50),
Age int (2),
Phone int (10)
);
-- Insert some sample data into the Customers table
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');
Output:

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:

✔ Views in SQL are considered as a virtual table.


✔ A view also contains rows and columns.
✔ To create the view, we can select the fields from one or more tables present in the
database.
✔ A view can either have specific rows based on certain conditions or all the rows of a table
Basic Operation in Views:
1. Creating a View (CREATE VIEW)
2. Removing a View (DROP VIEW)
Implementation on Views:
1. View Resolution
2. Restrictions on Views
3. View Updatability
4. With CHECK Option
5. Advantages and Disadvantages of Views
6. View Materialization

Sample Tables: a) Student Details

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:

CREATE VIEW view_name AS SELECT column1, column2.... FROM table_name


WHERE condition;
(view_name: Name for the View
table_name: Name of the table
condition: Condition to select rows)
Examples:
1)Creating View from a single table:
In this example we will create a View named Details View from the table Student Details.

CREATE VIEW DetailsView AS


SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;

To see the data in the View,


SELECT * FROM DetailsView;

Output:

2)Creating View from multiple tables:


In this example we will create a View named Marks View from two tables Student Details and
Student Marks. To create a View from multiple tables we can simply include multiple tables in
the SELECT statement.

Example:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;

To display data of View MarksView:


SELECT * FROM MarksView;

Output:
EXAMPLE-1: Create a horizontal view
A horizontal view restricts a user’s access to selected rows of one or more tables.

CREATE VIEW Manager3Staff


AS SELECT *
FROM Staff
WHERE branch No = ‘B003’;

SELECT * FROM Manager3Staff;

Example -2: Create a vertical view


A vertical view restricts a user’s access to selected columns of one or more tables.

CREATE VIEW Staff3


AS SELECT staff No, fName, IName, position, sex
FROM Staff
WHERE branch No = ‘B003’;

CREATE VIEW Staff3


AS SELECT staffNo, fName, IName, position, sex
FROM Manager3Staff;
Example -3: Grouped and joined views

CREATE VIEW StaffPropCnt (branchNo, staffNo, cnt)


AS SELECT s.branchNo, s.staffNo, COUNT(*)
FROM Staff s, PropertyForRent p
WHERE s.staffNo = p.staffNo
GROUP BY s.branchNo, s.staffNo;

DELETING VIEWS:
A view can be deleted using the Drop View statement.

Syntax:
DROP VIEW view_name;

Example:
DROP VIEW MarksView;

2.5.1 RESTRICTIONS ON VIEWS:


The ISO standard imposes several important restrictions on the creation and use of
views, although there is considerable variation among dialects.
(a) If column in view is based on an aggregate function:
– Column may appear only in SELECT and ORDER BY clauses of queries that access the view.
– Column may not be used in WHERE nor be an argument to an aggregate function in any query
based on view.

For example, following query would fail:


SELECT COUNT (cnt)
FROM StaffPropCnt;

Similarly, following query would also fail:


SELECT *
FROM StaffPropCnt
WHERE cnt > 2;

(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.

2.5.2 ADVANTAGES AND DISADVANTAGES OF VIEWS:

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.

2.5.3 VIEW MATERIALIZATION:


✔ An alternative approach, called view materialization, is to store the view as a temporary
table in the database when the view is first queried.
✔ Thereafter, queries based on the materialized view can be much faster than recomputing
the view each time.
✔ The speed difference may be critical in applications where the query rate is high and the
views are complex, so it is not practical to recompute the view for every query.
✔ Materialized views are useful in new applications such as data warehousing, replication
servers, data visualization, and mobile systems.
✔ Integrity constraint checking and query optimization can also benefit from materialized
views. The difficulty with this approach is maintaining the currency of the view while the
base table(s) are being updated.
✔ The process of updating a materialized view in response to changes to the underlying data
is called view maintenance.
✔ The basic aim of view maintenance is to apply only those changes necessary to the view
to keep it current. As an indication of the issues involved, consider the following view:

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.

A transaction can complete in one of four ways:


● A COMMIT statement ends the transaction successfully, making the database changes
permanent. A new transaction starts after COMMIT with the next transaction-initiating
statement.
● A ROLLBACK statement aborts the transaction, backing out any changes made by the
transaction. A new transaction starts after ROLLBACK with the next transaction-
initiating statement.
● For programmatic SQL (see Appendix I), successful program termination ends the final
transaction successfully, even if a COMMIT statement has not been executed.
● For programmatic SQL, abnormal program termination aborts the transaction.
The SET TRANSACTION statement allows the user to configure certain aspects of the
transaction. The basic format of the statement is:
SET TRANSACTION
[READ ONLY | READ WRITE] |
[ISOLATION LEVEL READ UNCOMMITTED | READ COMMITTED |
REPEATABLE READ | SERIALIZABLE]

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.

2.5.5 IMMEDIATE AND DEFERRED INTEGRITY CONSTRAINTS:


✔ A constraint may be defined as INITIALLY IMMEDIATE or INITIALLY DEFERRED,
indicating which mode the constraint assumes at the start of each transaction.
✔ In the former case, it is also possible to specify whether the mode can be changed
subsequently using the qualifier [NOT] DEFERRABLE. The default mode is
INITIALLY IMMEDIATE.
✔ The SET CONSTRAINTS statement is used to set the mode for specified constraints for
the current transaction.
✔ The format of this statement is:
SET CONSTRAINTS
{ALL | constraint Name [, . . .]} {DEFERRED | IMMEDIATE}

2.5.6 DISCRETIONARY ACCESS CONTROL:


✔ Discretionary access control - Each user is given appropriate access rights (or privileges) on
specific database objects. Typically, users obtain certain privileges when they create an object and
can pass some or all of these privileges to other users at their discretion.

✔ 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.

Authorization identifiers and ownership:


✔ Authorization Identifiers - An authorization identifier is a normal SQL identifier that is used
to establish the identity of a user. Each database user is assigned an authorization identifier by the
DBA.
Usually, the identifier has an associated password, for obvious security reasons.
The authorization identifier is used to determine which database objects the user may reference
and what operations may be performed on those objects.

✔ 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.

GRANTING PRIVILEGE TO OTHER USERS (GRANT):


✔ The GRANT statement is used to grant privileges on database objects to specific users.
✔ Normally the GRANT statement is used by the owner of a table to give other users access to
the data.

The format of the GRANT statement is:


GRANT {PrivilegeList | ALL PRIVILEGES}
ON ObjectName
TO {AuthorizationldList | PUBLIC}
[WITH GRANT OPTION]
PrivilegeList consists of one or more of the following privileges, separated by commas:
SELECT
DELETE
INSERT [(columnName [, . . .])]
UPDATE [(columnName [, . . .])]
REFERENCES [(columnName [, . . .])]
USAGE

✔ 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.

Example - 1 GRANT all privileges:


Give the user with authorization identifier Manager all privileges on the Staff table.
GRANT ALL PRIVILEGES
ON Staff
TO Manager WITH GRANT OPTION;

Example - 2 GRANT specific privileges:


Give users Personnel and Director the privileges SELECT and UPDATE on column salary of the
Staff table.
GRANT SELECT, UPDATE (salary)
ON Staff
TO Personnel, Director;

Example - 3 GRANT specific privileges to PUBLIC:


Give all users the privilege SELECT on the Branch table.
GRANT SELECT
ON Branch
TO PUBLIC;

REVOKING PRIVILEGES FROM USERS (REVOKE):


✔ The REVOKE statement is used to take away privileges that were granted with the
GRANT statement.
✔ A REVOKE statement can take away all or some of the privileges that were previously
granted to a user.

The format of the statement is:


REVOKE [GRANT OPTION FOR] {PrivilegeList | ALL PRIVILEGES}
ON ObjectName
FROM {Authorization List | PUBLIC} [RESTRICT | CASCADE]

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.

For example, in Figure 7.1


User A grants User B INSERT privilege on the Stafftable WITH GRANT OPTION
(step 1). User B passes this privilege on to User C
(step 2). Subsequently, User C gets the same privilege from User E
(step 3). User C then passes the privilege on to User D (step 4). When User A revokes the
INSERT privilege from User B
(step 5), the privilege cannot be revoked from User C, because User C has also received the
privilege from User E. If User E had not given User C this privilege, the revoke would have
cascaded to User C and User D.

Example - 1 REVOKE specific privileges from PUBLIC


Revoke the privilege SELECT on the Branch table from all users.
REVOKE SELECT
ON Branch
FROM PUBLIC;

Example - 2 REVOKE specific privileges from named user


Revoke all privileges you have given to the Director on the Staff table.
REVOKE ALL PRIVILEGES
ON Staff
FROM Director;

2.6 SQL PROGRAMMING:


2.6.1 SQL Introduction:
✔ Structured Query Language is a standard Database language that is used to create,
maintain, and retrieve the relational database.
✔ Structured Query Language (SQL) refers to a standard programming language utilized to
extract, organize, manage, and manipulate data stored in relational databases. SQL is
thereby referred to as a database language that can execute activities on databases that
consist of tables made up of rows and columns.
✔ SQL is an American National Standards Institute (ANSI) standard that operates via
multiple versions and frameworks to handle backend data across various web
applications supported by relational databases such as MySQL, SQL Server, Oracle
PostgreSQL, and others.
PL/SQL Introduction:
✔ PL/SQL is a block structured language that enables developers to combine the power of
SQL with procedural statements.
✔ All the statements of a block are passed to the oracle engine all at once which increases
processing speed and decreases the traffic.
✔ PL/SQL is a combination of SQL along with the procedural features of programming
languages.
✔ Oracle uses a PL/SQL engine to process the PL/SQL statements.
✔ PL/SQL includes procedural language elements like conditions and loops. It allows
declaration of constants and variables, procedures and functions, types and variables of
those types and triggers.
✔ PL/SQL is basically a procedural language, which provides the functionality of decision
making, iteration and many more features of procedural programming languages.
✔ PL/SQL can execute a number of queries in one block using a single command.
✔ 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.
✔ PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known
as exception handling block.
✔ Applications written in PL/SQL are portable to computer hardware or operating systems
where Oracle is operational.
✔ PL/SQL Offers extensive error checking.

A PL/SQL block has up to three parts:


• an optional declaration part, in which variables, constants, cursors, and exceptions are defined
and possibly initialized;
• a mandatory executable part, in which the variables are manipulated;
• an optional exception part, to handle any exceptions raised during execution.

2.6.2 DECLARATIONS:
Variables and constant variables must be declared before they can be referenced in
other statements, including other declarative statements.

PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a


structural language that is more powerful than SQL. The basic unit in PL/SQL is a block.
All PL/SQL programs are made up of blocks, which can be nested within each other.

✔ 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’

2.6.4 CONTROL STATEMENTS:


 PL/SQL supports the usual conditional, iterative, and sequential flow-of-control mechanisms.

 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.

The Conditional statements in PL/SQL are:


✔ IF…Then Statement
✔ IF…Then…Else Statement
✔ IF…Then…Elseif…Else Statement
✔ Case Statement
✔ Searched Case Statement

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.

IF…THEN…. ELSE STATEMENT:


Using this statement group, we can specify two statements or two sets of statements, depending
on a condition such that when the condition is true then one set of statements is executed and if
the condition is false then the other set of statements is executed.

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.

The Iterative statements in PL/SQL are:


✔ Simple Loop
✔ While loop and While Repeat
✔ For loop - IN and AS
SIMPLE LOOP:
The simple loop is infinite. The loop keeps on executing the enclosed statements infinitely.
Simple loop needs an exit condition and exit statement to terminate.

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.

WHILE LOOP - REPEAT:


The WHILE and REPEAT statements have the following form (note that PL/SQL has no
equivalent to the REPEAT loop specified in the SQL standard).

Syntax:

FOR LOOP IN PL/SQL - (IN):


PL/SQL for loop is used when you want to execute a set of Statements for a predetermined
number of times. The loop is iterated between the Start and End Integer values. The counter is
always Incremented by 1 and once the Counter reaches the value of the end integer, the loop
ends.

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.

FOR LOOP IN STANDARD SQL (AS):


This loop is used when some statements in SQL code blocks are to be repeated for a fixed
number of times.

Syntax:
Example:
myLoop1:
FOR iStaff AS SELECT COUNT (*) FROM PropertyForRent
WHERE staffNo 5 ‘SG14’ DO
.....
END FOR myLoop1;

2.6.5 EXCEPTIONS IN PL/SQL:


✔ An exception is an error which disrupts the normal flow of program instructions.
✔ PL/SQL provides us the exception block which raises the exception thus helping the
programmer to find out the fault and resolve it.
✔ Any abnormal condition or event that interrupts the normal flow of our program
instructions at run time or in simple words an exception is an error.

There are two types of exceptions defined in PL/SQL:


1. User defined exceptions.
2. System defined exceptions.

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!

PL/SQL procedure successfully completed.

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.

SYSTEM (PRE-DEFINED) EXCEPTIONS:

✔ 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.

1. LOGIN_DENIED- Occurs when invalid username or invalid password is given while


connecting to Oracle.
2. TOO_MANY_ROWS - Occurs when a select statement returns more than one
row.
3. VALUE_ERROR- Occurs when invalid datatype or size is given by the user.
4. NO_DATA_FOUND- Occurs when no records are found.
5. DUP_VAL_ON_INDEX- Occurs when a unique constraint is applied on some column
and execution of Insert or Update leads to creation of duplicate records for that column.
6. PROGRAM_ERROR- Occurs when internal errors arise in the program.
7. ZERO_DIVIDE- Occurs when the division of any variable value is done by zero.

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.

Example 1: In this example, we are going to see

1. How to declare the exception


2. How to raise the declared exception and
3. How to propagate it to the main block
2.6.6 CURSORS IN PL/SQL:

✔ 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);

Updating rows through a cursor-

✔ 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.

Syntax for Creating Function:


CREATE OR REPLACE FUNCTION <function_name>
(<variable_name> IN <datatype>,
<variable_name> IN <datatype>,...)
RETURN <datatype> IS/AS
variable/constant declaration;
BEGIN
-- PL/SQL subprogram body;
END <function_name>;

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;

Output: Function Created

Advantages of a Stored Procedure or Function:

✔ Improves Database Performance


✔ Provides Reusability and avoids redundancy
✔ Maintains Integrity
✔ Maintains Security
✔ Saves Memory

Similarities between Procedure and Function:

✔ Both can be called from other PL/SQL blocks.


✔ If the exception raised in the subprogram is not handled in the subprogram exception
handling section, then it will propagate to the calling block.
✔ Both can have as many parameters as required.
✔ Both are treated as database objects in PL/SQL.

Difference between Procedure & Function:

CASE PROCEDURE FUNCTION

Process Used mainly to execute a Used mainly to perform some


certain process. calculation.

Select Statement Cannot call in the SELECT A Function that contains no


statement. DML statements can be called
in a SELECT statement.

Parameter Use OUT parameter to return Use RETURN Parameter to


the value. return the value.

Mandatory It is not mandatory to return It is mandatory to return the


the value. value.

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;

Output: Package created.

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 general format of a trigger in SQL is:


CREATE TRIGGER TriggerName
BEFORE | AFTER | INSTEAD OF
INSERT | DELETE | UPDATE [OF TriggerColumnList]
ON TableName
[REFERENCING {OLD | NEW} AS {OldName | NewName}
[FOR EACH {ROW | STATEMENT}]
[WHEN Condition]
<trigger action>

✔ 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.

✔ NEW and: OLD Clause:


NEW – It holds a new value for the columns of the base table/view during the trigger execution.
OLD – It holds the old value of the columns of the base table/view during the trigger execution.

There are two types of triggers:


1.ROW-Level Trigger
2.STATEMENT-Level Trigger

✔ 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.

AFTER Row-level trigger:


CREATE TRIGGER StaffAfterInsert
AFTER INSERT ON Staff
REFERENCING NEW AS new
FOR EACH ROW
BEGIN
INSERT INTO StaffAudit
VALUES (:new.staffNo, :new.fName, :new.lName, :new.position,
:new.sex, :new.DOB, :new.salary, :new.branchNo);
END;
Using a BEFORE trigger:

✔ 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.

Syntax for creating Triggers:


CREATE OR REPLACE TRIGGER <trigger_name>
BEFORE/AFTER/INSTEAD OF
INSERT/DELETE/UPDATE ON <table_name>
REFERENCING (OLD AS O, NEW AS N)
FOR EACH ROW WHEN (test_condition)
DECLARE
-- Variable declaration;
BEGIN
-- Executable statements;
EXCEPTION
-- Error handling statements;
END <trigger_name>;
END;

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;

Output: Trigger created.


USES OF TRIGGERS:
✔ Maintaining complex constraints which is either impossible or very difficult via normal
constraints (like primary, foreign, unique etc.) applying technique.
✔ Recording the changes made on the table.
✔ Automatically generating primary key values.
✔ Prevent invalid transactions to occur.
✔ Granting authorization and providing security to the database.
✔ Enforcing referential integrity.

BENEFITS OF TRIGGERS:
Following are the benefits of triggers.

✔ Generating some derived column values automatically.


✔ Enforcing referential integrity.
✔ Event logging and storing information on table access.
✔ Auditing
✔ Synchronous replication of tables.
✔ Imposing security authorizations.
✔ Preventing invalid transactions.

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;

The recursion statement allows the specification of two orderings:


•Depth-first, where each ‘parent’ or ‘containing’ item appears in the result before the items that it
contains, as well as before its ‘siblings’ (items with the same parent or container);
•Breadth-first, where items follow their ‘siblings’ without following the siblings’ children.

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.

An example of the CYCLE clause is:


CYCLE staffNo, managerStaffNo
SET cycleMark TO ‘Y’ DEFAULT ‘N’
USING cyclePath.

********************

You might also like