UNIT 2 DBMS

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 72

UNIT-2

Database Management Systems(KCA 204)

RDBMS(Relational Database Management System)

A RDBMS is a database management system that is based on the relational


model as introduced by Dr. EF Codd.

It should satisfies Codds’s 12 rules but in practice there is no DBMS that


satisfies all these rules.

RDBMS stores data in the form of related tables.

RDBMS are powerful because they require few assumptions about how data is
related or how it will be extracted from the database. As, a result the same
database can be viewed in many different ways.

Main feature of relational systems is that single database can be spread across
several tables.

Popular commercial for large databases include Oracle , Microsoft SQL


SERVER, Sybase , IBM Db2. PostgreSQL etc

E. F CODDS Rules: Dr Edgar F. Codd, after his extensive research on the


Relational Model of database systems, came up with twelve rules of his own,
which according to him, a database must obey in order to be regarded as a true
relational database.
These rules can be applied on any database system that manages stored data
using only its relational capabilities. This is a foundation rule, which acts as a
base for all the other rules.
Rule 1: Information Rule
The data stored in a database, may it be user data or metadata, must be a value
of some table cell. Everything in a database must be stored in a table format.
Rule 2: Guaranteed Access Rule
Every single data element (value) is guaranteed to be accessible logically with
a combination of table-name, primary-key (row value), and attribute-name
(column value). No other means, such as pointers, can be used to access data.
Rule 3: Systematic Treatment of NULL Values
The NULL values in a database must be given a systematic and uniform
treatment. This is a very important rule because a NULL can be interpreted as
one the following − data is missing, data is not known, or data is not
applicable.
Rule 4: Active Online Catalog
The structure description of the entire database must be stored in an online
catalog, known as data dictionary, which can be accessed by authorized users.
Users can use the same query language to access the catalog which they use to
access the database itself.
Rule 5: Comprehensive Data Sub-Language Rule
A database can only be accessed using a language having linear syntax that
supports data definition, data manipulation, and transaction management
operations. This language can be used directly or by means of some
application. If the database allows access to data without any help of this
language, then it is considered as a violation.
Rule 6: View Updating Rule
All the views of a database, which can theoretically be updated, must also be
updatable by the system.
Rule 7: High-Level Insert, Update, and Delete Rule
A database must support high-level insertion, updation, and deletion. This must
not be limited to a single row, that is, it must also support union, intersection
and minus operations to yield sets of data records.
Rule 8: Physical Data Independence
The data stored in a database must be independent of the applications that
access the database. Any change in the physical structure of a database must
not have any impact on how the data is being accessed by external applications.
Rule 9: Logical Data Independence
The logical data in a database must be independent of its user’s view
(application). Any change in logical data must not affect the applications using
it. For example, if two tables are merged or one is split into two different
tables, there should be no impact or change on the user application. This is one
of the most difficult rule to apply.
Rule 10: Integrity Independence
A database must be independent of the application that uses it. All its integrity
constraints can be independently modified without the need of any change in
the application. This rule makes a database independent of the front-end
application and its interface.
Rule 11: Distribution Independence
The end-user must not be able to see that the data is distributed over various
locations. Users should always get the impression that the data is located at one
site only. This rule has been regarded as the foundation of distributed database
systems.
Rule 12: Non-Subversion Rule
If a system has an interface that provides access to low-level records, then the
interface must not be able to subvert the system and bypass security and
integrity constraints.
Properties of relational table
• Values Are Atomic
This property implies that columns in a relational table are not repeating
group or arrays.
• Column Values Are of the Same Kind
In relational terms this means that all values in a column come from the
same domain. For example, a empName column contains only specific name of
employee. It never contains other information such as address and DOB etc
• Each Row is Unique
This property ensures that no two rows in a relational table are identical
• The Sequence of Columns is Insignificant
This property states that the ordering of the columns in the relational table
has no meaning. Columns can be retrieved in any order and in various
sequences
• The Sequence of Rows is Insignificant
This property is analogous the one above but applies to rows instead of
columns..
• Each Column Has a Unique Name
Because the sequence of columns is insignificant, columns must be
referenced by name and not by position. In general, a column name need not be
unique within an entire database but only within the table to which it belongs.
Difference between DBMS and RDBMS
DBMS RDBMS
In DBMS data are store as a file In RDBMS data are stored in a tabular
form.
In DBMS relationship between two In RDBMS relationship between two
tables are maintained programmatically tables can be specified at the time of table
creation
DBMS does not support Client Server RDBMS support Client Server
Architecture Architecture
DBMS does not support Distributed DBMS support Distributed Architecture
Architecture
In DBMS there are no security of data In RDBMS there are multilevel of security
at logging level, at command level , at
object level
DBMS may satisfy less than 7 rules of RDBMS may satisfy more than 7 to 8
Dr. EF codd rules of Dr. EF codd
Normalization is not available in DBMS Normalization is available in RDBMS
Example of DBMS are file system, XML Example of RDBMS are MySQL, Postgre,
SQL Server, Oracle.
RDBMS Concepts
• Tables − In relational data model, relations are saved in the format of
Tables. This format stores the relation among entities. A table has rows
and columns, where rows represents records and columns represent the
attributes.
• Tuple − A single row of a table, which contains a single record for that
relation is called a tuple.
• Relation instance − A finite set of tuples in the relational database
system represents relation instance. Relation instances do not have
duplicate tuples.
• Relation schema − A relation schema describes the relation name (table
name), attributes, and their names.
• Relation key − Each row has one or more attributes, known as relation
key, which can identify the row in the relation (table) uniquely.
• Attribute domain − Every attribute has some pre-defined value scope,
known as attribute domain.

Constraints
• Constraints are the rules enforced on the data columns of a table. These
are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the database.
• Constraints could be either on a column level or a table level. The column
level constraints are applied only to one column, whereas the table level
constraints are applied to the whole table.
Following are some of the most commonly used constraints
available in SQL are -
• NOT NULL Constraint − Ensures that a column cannot have NULL
value.
• DEFAULT Constraint − Provides a default value for a column when
none is specified.
• UNIQUE Constraint − Ensures that all values in a column are different.
• PRIMARY Key − Uniquely identifies each row/record in a database
table.
• FOREIGN Key − Uniquely identifies a row/record in any of the given
database table.
CHECK Constraint − The CHECK constraint ensures that all the values
in a column satisfies certain conditions.

CONSTRAINTS

1) NOT NULL CONSTRAINT:- The NOT NULL column constraint


ensures that a table column cannot be left empty. When a column is defined
as not null, then that column becomes a mandatory column. It implies that a
value must be entered into the column if the record is to be accepted for
storage in the table.

Syntax:-<Column Name><data type>(<size>) NOT NULL ;


Example:-create table student(stid number(8) not null,name varchar(22),
city char(12));

2) PRIMARY KEY CONSTRAINT: - A primary is one or more column in


a table
used to identify each row in a table. None of the fields that are part of
the primary key can contain a null value. A table can have only one
primary
Syntax:-<Column name><data type>(<size>) PRIMARY KEY

SQL Command primary key for one column:

CREATE TABLE students


(
S_Id int NOT NULL PRIMARY KEY,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
Address varchar (255),
City varchar (255)
) ;

SQL Command primary key for multiple columns:


CREATE TABLE students
(
S_Id int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
Address varchar (255),
City varchar (255),
PRIMARY KEY (S_Id, LastName)
);

3) FOREIGN KEY CONSTRAINT:-Foreign key represent


relationships between tables. A foreign key is a column (or a group of
columns) whose values are derived from the primary key or unique key of
some other table. The table in which the foreign key is defined is called a
FOREIGN TABLE or DETAIL TABLE.The table that defines the
primary or unique key and is referenced by the foreign key is called the
PRIMARY KEY or MASTER KEY.

Syntax: - Foreign key (<column name>) REFERENCES <table


name>(column name);

Example:-

primary key table(studs)

SQL>CREATE TABLE studs(stid INT PRIMARY KEY,name


CHAR(22),address VARCHAR2(22));

foreign key table(course)

SQL>CREATE TABLE course(courseid INT PRIMARY


KEY ,cname CHAR(22),stid INT, FOREIGN KEY(stid)
REFERENCES student111(stid));

4) UNIQUE KEY CONSTRAINT:-The unique key constraint


permits multiple entries of NULL into the column. These NULL
values are clubbed at the top of the column in the order in which they
were entered into the table. This is the essential difference between the
primary key and the unique constraints when applied to table
column(s).Key point about UNIQUE constraint:
 Unique key will not allow duplicate values.
 Unique index is created automatically.
 A table can have more than one unique key which is not possible in
primary key.

Syntax:-CREATE TABLE Table name


(<columnName1><datatype>(<size>) Unique,
<columnName2><data type>(<size>));

Example:-
SQL> create table student1(roll_no number(12) primary key,
,name varchar2(20),class varchar2(2), e_mail varchar2(20)
unique);

Table created.

5) Check Constraints:-

The CHECK constraint is used to limit the value range that can be
placed in a column. If you define a CHECK constraint on a single
column it allows only certain values for this column.
For Example:-

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);

SQL DEFAULT Constraint

The DEFAULT constraint is used to set a default value for a column.

The default value will be added to all new records, if no other value is specified.

SQL DEFAULT on CREATE TABLE


The following SQL sets a DEFAULT value for the "City" column when the
"Persons" table is created:

Oracle:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

SQL DEFAULT on ALTER TABLE

To create a DEFAULT constraint on the "City" column when the table is


already created, use the following SQL:

Oracle:

ALTER TABLE Persons


MODIFY City DEFAULT 'Sandnes';

Integrity Constraints:
• Integrity constraints are used to ensure accuracy and consistency of data
in a relational database. Data integrity is handled in a relational database
through the concept of referential integrity.
• There are many types of integrity constraints that play a role in referential
integrity (RI). These constraints include Primary Key, Foreign Key,
Unique Constraints and other constraints
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.
• Key constraints
• Domain constraints
• Referential integrity constraints
• Entity Integrity Constraints

Key Constraints
• There must be at least one minimal subset of attributes in the relation,
which can identify a tuple uniquely. This minimal subset of attributes is
called key for that relation. If there are more than one such minimal
subsets, these are called candidate keys.
• Key constraints force that −
• in a relation with a key attribute, no two tuples can have identical values
for key attributes.
• a key attribute can not have NULL values.
• Key constraints are also referred to as Entity Constraints.

Entity Integrity Constraint


 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.
The entity integrity constraint states that primary keys can't be null. There
must be a proper value in the primary key field. This is because the
primary key value is used to identify individual rows in a table. If there
were null values for primary keys, it would mean that we could not
identify those rows.
On the other hand, there can be null values other than primary key fields.
Null value means that one doesn't know the value for that field. Null
value is different from zero value or space.

Domain Constraints
• Attributes have specific values in real-world scenario. For example, age
can only be a positive integer. The same constraints have been tried to
employ on the attributes of a relation. Every attribute is bound to have a
specific range of values. For example, age cannot be less than zero and
telephone numbers cannot contain a digit outside 0-9. Domain
constraints can be defined as the definition of a valid set of values for an
attribute.
• The data type of domain includes string, character, integer, time, date,
currency, etc. The value of the attribute must be available in the
corresponding domain.
• Example:

Referential integrity Constraints


• Referential integrity constraints work on the concept of Foreign Keys. A
foreign key is a key attribute of a relation that can be referred in other
relation. Referential integrity constraint states that if a relation refers to a
key attribute of a different or same relation, then that key element must
exist.
• A referential integrity constraint requires that for each row of the table the
value in the foreign key matches a value in a parent key.
• 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

Relational Algebra:-

 The relational algebra is a procedural query language. It consists of a set


of operations that take one or two relations as input and produce a new
relation as their result.
 The fundamental operations in the relational algebra are select, project,
union, set difference, Cartesian product, and rename.
 In addition to the fundamental operations, there are several other
operations—namely, set intersection, natural join, and assignment.
 Relational algebra is the mathematical basis for relational databases
developed by E.F Codd.
 It is a notation for representing various operations can be performed on
relational databases.

Fundamental Relational Algebra Operations:-


 Unary Operations:-The select, project, and rename operations are called
unary operations, because they operate on one relation or table.

 Binary Operations:-The other three operations operate on pairs of


relations and are, therefore, called binary operations. For Example:- union
,set difference, Cartesian product etc.
Types of Relational algebra
Unary Operations
1. Select Operation (σ) 2. Project Operation (∏) 3.
Rename Operation (ρ)
Binary Operations
1. Union Operation (∪) 2.Set Difference Operation (−)
3.Cartesian Product operation (Χ)
4. Join Operation (⋈) 5. Division Operation(÷ )
6. Set Intersection(∩)

1. Select Operation:
o The select operation selects tuples that satisfy a given predicate.
o It is denoted by sigma (σ).
o It yields a horizontal subset of a given relation.
1. Notation: σ p(r)
Where:
σ is used for selection prediction
r is used for relation
p is used as a propositional logic formula which may use connectors like: AND
OR and NOT. These relational can use as relational operators like =, ≠, ≥, <, >,
≤. Furthermore, we can combine several predicates into a larger predicate by
using the connectives and (∧), or (∨), and not (¬).
For example: LOAN Relation
BRANCH_NAME LOAN_NO AMOUNT

Downtown L-17 1000

Redwood L-23 2000

Perryride L-15 1500

Downtown L-14 1500

Mianus L-13 500

Roundhill L-11 900

Perryride L-16 1300


Find those tuples of Loan relation where branch is perryride.
Input:
1. σ BRANCH_NAME="perryride" (LOAN)
Output:
BRANCH_NAME LOAN_NO AMOUNT

Perryride L-15 1500

Perryride L-16 1300

Find those tuples whose loans of more than Rs 1200 and branch is perryride.
2. σ BRANCH_NAME="perryride" ∧ amount>1200(LOAN)

Find the tuples from books where subject is 'database'.


σsubject = "database"(Books)

find tuples from books where subject is 'database' and 'price' is 450.
σsubject = "database" ∧ price = "450"(Books)

Selects tuples from books where subject is 'database' and 'price' is 450 or
those books published after 2010.
σsubject = "database" ∧ price = "450" ∨ year > "2010"(Books)

2. Project Operation:
o This operation shows the list of those attributes that we wish to appear in
the result. Rest of the attributes are eliminated from the table.
o It is denoted by ∏.
o It yields a vertical subset of a given relation.
1. Notation: ∏ A1, A2, An (r)
Where
A1, A2, A3 is used as an attribute name of relation r.
Example: CUSTOMER RELATION
NAME STREET CITY

Jones Main Harrison

Smith North Rye

Hays Main Harrison

Curry North Rye

Johnson Alma Brooklyn

Brooks Senator Brooklyn


Input:
Find all the list of names and city of the customer?
1. ∏ NAME, CITY (CUSTOMER)
Output:
NAME CITY

Jones Harrison

Smith Rye

Hays Harrison

Curry Rye

Johnson Brooklyn

Brooks Brooklyn
Find those customers who live in Rye.
∏ name (σ city=”Rye”) (Customer)
Selects and projects columns named as subject and author from the
relation Books.
∏subject, author (Books)

3. Union Operation: It Combines data from two union compatible relation


having same number of columns. Suppose there are two tuples R and S. The
union operation contains all the tuples that are either in R or S or both in R & S.
It eliminates the duplicate tuples. It is denoted by ∪. Notation: R ∪ S
A union operation must hold the following condition:
o R and S must have the attribute of the same number.
o Duplicate tuples are eliminated automatically.
Example: DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO

Johnson A-101

Smith A-121

Mayes A-321

Turner A-176

Johnson A-273

Jones A-472

Lindsay A-284
BORROW RELATION
CUSTOMER_NAME LOAN_NO

Jones L-17

Smith L-23

Hayes L-15

Jackson L-14

Curry L-93

Smith L-11
Williams L-17

Find the names of customers account in borrow table


∏ CUSTOMER_NAME (BORROW)

Find the names of customers account in depositor table


∏ CUSTOMER_NAME (DEPOSITOR)
Find the names of customers who are either in borrow table or in depositor
table or both
Input:
1. ∏ CUSTOMER_NAME (BORROW) ∪ ∏ CUSTOMER_NAME (DEPOSITO
R)
Output:
Question Projects the names of the authors who have
CUSTOMER_ either written a book or an article or both
NAME ∏ author (Books) ∪ ∏ author (Articles)
Johnson
4. Set Intersection:
Smith o Display all the rows that are common in two
compatible tables.
Hayes o Suppose there are two tuples R and S. The set
intersection operation contains all tuples that are in
Turner
both R & S.
o It is denoted by intersection ∩.
Jones
1. Notation: R ∩ S
Lindsay Example: Using the above DEPOSITOR table and
BORROW table
Jackson Input:
1. ∏ CUSTOMER_NAME (BORROW) ∩ ∏ CUSTOMER_
Curry NAME (DEPOSITOR)
Output:
Williams

Mayes

CUSTOMER_N
AME

Smith

Jones
5. Set Difference:
 The set-difference operation, denoted by −, allows us to find tuples
that are in one relation but are not in another. The expression r − s
produces a relation containing those tuples in r but not in s.
 Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in R but not in S.
 It is denoted by intersection minus (-).
1. Notation: R - S
Example: Using the above DEPOSITOR table and BORROW table
Find the name of customer who has account number in BORROW table but not
in DEPOSITOR
Input:
1. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR
)
Output:
CUSTOMER_NAME

Jackson

Hayes

Willians

Curry

Question Provides the name of authors who have written books but not
articles.
∏ author (Books) - ∏ author (Articles)

6. Cartesian product
 The Cartesian product is used to combine each row in one table with each
row in the other table. It is also known as a cross product.
 It is denoted by X.
 The Cartesian-product operation, denoted by a cross (×), allows us to
combine information from any two relations. We write the Cartesian
product of relations r1 and r2 as r1 × r2.
1. Notation: E X D
Example:
EMPLOYEE
EMP_ID EMP_NAME EMP_DEPT

1 Smith A

2 Harry C

3 John B
DEPARTMENT
DEPT_NO DEPT_NAME

A Marketing

B Sales

C Legal
Input:
1. EMPLOYEE X DEPARTMENT

Output:
EMP_I EMP_NA EMP_DE DEPT_ DEPT_NA
D ME PT NO ME

1 Smith A A Marketing

1 Smith A B Sales

1 Smith A C Legal

2 Harry C A Marketing

2 Harry C B Sales

2 Harry C C Legal

3 John B A Marketing

3 John B B Sales
3 John B C Legal

Question Find relation, which shows all the books and articles written by
test.

∏ author = ‘test'(Books Χ Articles)

Division Operation(/)

Division Operator (÷): Division operator A÷B can be applied if and only if:
 Attributes of B is proper subset of Attributes of A.
 The relation returned by division operator will have attributes = (All
attributes of A – All Attributes of B)
 The relation returned by division operator will return those tuples from
relation A which are associated to every B’s tuple.

Relational Algebra for Divsion


∏ ENAME, DNAME (EMP) / ∏ DName DEPT)

7. Rename Operation:
 The rename operation is used to rename the output relation. It is denoted
by rho (ρ).
 Unlike relations in the database, the results of relational-algebra
expressions do not have a name that we can use to refer to them.
 It is useful to be able to give them names; the rename operator, denoted
by the lowercase Greek letter rho (ρ), lets us do this. Given a relational-
algebra expression E, the expression ρ x (E) returns the result of
expression E under the name x.
Example: We can use the rename operator to rename STUDENT relation to
STUDENT1.
1. ρ(STUDENT1, STUDENT)

2. Query to rename the table name Project to Pro and its attributes to P, Q, R.
ρ Pro(P, Q, R) (Project)

3. Query to rename the first attribute of the table Student with attributes A, B, C
to P.
ρ (P, B, C) (Student)

Join Operations:
 A Join operation combines related tuples from different relations, if and
only if a given join condition is satisfied. It is denoted by ⋈.
 The general form of a join operation on two relations R(A1,A2,A3…An)
and S(B1,B2….Bn) is R ⋈ <join condition> S.
 (Emp⋈dept ⋈cmp)
 The result of the join is a relation Q with (n+m) attributes in that order,
one from R relation and other from S relation.

TYPES OF JOINS
1. INNER join:- In SQL, INNER JOIN selects records that have matching
values in both tables as long as the condition is satisfied. It returns the
combination of all rows from both the tables where the condition satisfies.

Syntax:-
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1 INNER JOIN table2 ON table1.matching_column = table2.
matching_column;
Example:-

emp
Eid ename deptid
101 Aman 201
102 Rajesh 202
103 Suresh 204

dept
deptid Dname
201 B.Tech
202 MCA
203 MBA
SELECT emp. ENAME, dept. dname FROM emp INNER JOIN dept
ON emp.deptid=dept.deptid;

Ename Dname
Aman Btech
Rajesh MCA

Relational Algebra for Inner join


∏ ENAME, DNAME (EMP ⋈EMP.DNO=DEPT.DNO DEPT)

2. OUTER JOIN:- It is based on matched and unmatched data. It gives


It is divided into .3 types:-
a) LEFT OUTER JOIN:- It returns a result table with matched data of two
tables then remaining rows of the left table and NULL for the right table
column.

SYNTAX:- SELECT column1,column2,.... from table1 LEFT OUTER JOIN


table2 on table1.column=table2.column;
Example:-

For example:- SELECT emp. ename, dept.dname from emp LEFT OUTER
JOIN dept on emp.deptid=dept.depid;
Ename Dname
Aman Btech
Rajesh Mca
Suresh

Relational algebra
∏ ENAME, DNAME (Emp Dept)
B) RIGHT OUTER JOIN:- It returns a result table with matched data of two
tables then remaining rows of the RIGHT table and NULL for the LEFT table
column.

SYNTAX:- SELECT column1,column2,.... from table1 RIGHT OUTER JOIN


table2 on table1.column=table2.column;

For example:- SELECT emp. ename, dept.dname from emp RIGHT OUTER
JOIN dept on emp.deptid=dept.depid;

Ename Dname
Aman Btech
Rajesh Mca
Mba

Relational algebra
∏ ENAME, DNAME (Emp Dept)

C) FULL OUTER JOIN:-It returns a result table with matched data of two
tables then remaining rows of both left and right table is NULL.

SYNTAX:- SELECT columnlist from table1 FULL OUTER JOIN table2 on


table1.column=table2.column;
For example:- SELECT emp. ename, dept.dname from emp RIGHT OUTER
JOIN dept on emp.deptid=dept.depid;

Ename Dname
Aman Btech
Rajesh Mca
Suresh
Mba

Relational algebra
∏ ENAME, DNAME (Emp Dept)

3. Natural Join:- Natural Join joins two tables based on same attribute
name and datatypes. The resulting table will contain all the attributes of
both the table but keep only one copy of each common column.
- The columns must be the same data type.
- Don’t use ON clause in a natural join.
Natural join does not use any comparison operator
Syntax:

SELECT * FROM table1 NATURAL JOIN table2;

Example : Select * from emp natural join dept;

Relational Algebra:- ∏ ENAME, DNAME ( Emp ⋈ Dept)

4. CROSS JOIN: This join produces a result where the number of rows in the
first table gets multiplied with the rows in the second table.

Ex-Select * from emp cross join dept;


Relational Algebra:- ∏ Eid,ename,deptid,dname (Emp X Dept);

5. SELF JOIN: Self-join is a regular join and here the table joins with itself
only.

Ex- Select a.eid, b.ename from emp a, emp b;


Relational Algebra:- ∏ Eid,ename (Emp X Emp);
Relational Calculus
o Relational calculus is a non-procedural query language. In the non-procedural
query language, the user is concerned with the details of how to obtain the end
results.
o The relational calculus tells what to do but never explains how to do.
o Relational calculus provide description about the query to get the result where
as relational algebra gives the method to get the result.
o Relational calculus is called declarative language.

Types of Relational calculus:


 Tuple Relational Calculus(TRC)
proposed by codd in the year 1972
works on tuples or rows

 Domain Relational Calculus(DRC)


proposed by lacroix & pirotte in the year 1977
worked on domain of attributes (columns)

Tuple Relational Calculus

Tuple Relational Calculus is a non-procedural query language unlike relational


algebra is procedural language.

Tuple Calculus provides only the description of the query but it does not
provide the methods to solve it. Thus, it explains what to do but not how to do.

In Tuple Calculus, a query is expressed as

{t| P(t)}

where t = resulting tuples,

P(t) = known as Predicate and these are the conditions that are used to
fetch tuple t

| -- filter side
Result of query

Thus, it generates set of all tuples t, such that Predicate P(t) is true for t.

Notations used

 t is a tuple variable
 t[A] denotes the value of tuple on attribute A
 t∈r denote the tuple in relation r
 P is formula similar to that of predicate calculus

Predicate calculus formula

I. set connectives :-P(t) may have various conditions logically combined


with OR (∨), AND (∧), NOT(¬).

I. It also uses quantifiers Existential quantifiers(∃) and universal


quantifiers (∀)
II. set of comparison operators(<,>,<=,>=..)
III. Implication(=>) : x=>y if x is true then y is true
IV. set of attributes and constants

Free and bound variables

the use of quantifiers ∃X and ∀X in a formula is said to bind X in the formula

A variable that is not bound is called free variable.

the variable t that appears to the left of | must be only the free variable in the
formula p(t)

in other words all other tuple variable must be bound using quantifiers.

Consider the following relations:

Branch( BranchName ,Branch City, assets)

Customer(Customername, customerStreet, customer city)

Account(Accountnumber, branchname, balance)

loan(loan number, branch name,amount)


depositor(customername , account number)

borrower( customer name, loan number)

Example queries : Tuple relational calculus(TRC)

Queries-1: Find the loan number, branch name , amount of loans of over
$1200

{t| t ∈ loan ∧ t[amount]>1200} (selection)


selects all tuples from relation loan such that the resulting loan tuples will
have amount greater than $1200.
.

Queries-2: Find the loan number for each loan of an amount greater than
1200.
{t| ∃ s ∈ loan(t[loan number] = s[loan number] ∧
s[amount]>1200)}

it selects the set of tuples t such that there exixts a tuple s in relation loan for
which the value of t & s for the loan number are equal and the value of s for
the amount attribute is greater than $1200.

Queries-3: Find the names of all customers having a loan at the “ABC”
branch.
{t | ∃ s ∈ borrower(t[customer-name] = s[customer-name] ∧ ∃ u ∈
loan(u[branch-name] = “ABC” ∧ u[loan-number] = s[loan-number]))
(Join)

Queries-4: Find the names of all customers who have a loan and an account
or both at the bank.
{t | ∃ s ∈ borrower( t[customer-name] = s[customer-name])
∨ ∃ u ∈ depositor( t[customer-name] = u[customer-name])}
(union)

Queries-5: Find the names of all customers who have a loan and an account
at the bank.
{t | ∃ s ∈ borrower( t[customer-name] = s[customer-name])
∧ ∃ u ∈ depositor( t[customer-name] = u[customer-name])}
(intersection)

Domain Relational Calculus

 Domain relational calculus is a non procedural query language.


 In Domain relational calculus the records are filtered based on the
domains or attributes.
 DRC uses the list of attributes to be selected from relation based on the
condition or predicate.
 DRC is same as TRC but differs by selecting the attributes rather the
whole tuples or rows.
 In Domain relational calculus each query is an expression of the form
{<a1, a2, a3,......... an>| P(a1, a2, a3,......... an)}
a1, a2, a3,......... an represents domain variables
P represents a predicate similar to that of the predicate calculus.
Result of the query
It is the set of all tuples a 1, a2, a3,......... an such that predicate P is true for
a1, a2, a3,......... an tuples.

Predicate calculus formula


<a1, a2, a3,......... an>∈r where r is relation on n attributes and a1, a2, a3,......... an
are domain variables.
P is a formula similar predicate calculus
II. set connectives :-P(t) may have various conditions logically combined
with OR (∨), AND (∧), NOT(¬).

III. It also uses quantifiers Existential quantifiers(∃) and universal


quantifiers (∀)
IV. set of comparison operators(<,>,<=,>=..)
V. Implication(=>) : x=>y if x is true then y is true
VI. set of domain variables and constants

Example Queries Domain relational calculus(DRC)


Query-1: Find the loan number, branch, amount of loans of greater than or
equal to 100 amount.

{≺l, b, a≻ | ≺l, b, a≻ ∈ loan ∧ (a ≥ 100)}

Query-2: Find the loan number for each loan of an amount greater or equal to
150.
{≺l≻ | ∃ b, a (≺l, b, a≻ ∈ loan ∧ (a ≥ 150)}

Query-3: Find the names of all customers having a loan at the “Main” branch
and find the loan amount .
{∃c, a∈| ∧ l (∃c, l∈∧ borrower ∧ ∃ b (≺l, b, a≻∈ loan ∧ (b = “Main”)))}
Introduction to SQL(Structured Query Language)

• It is non-procedural language. It is international standard language for


creating or manipulating relational database.
• SQL is used to perform operations on the records stored in the database
such as updating records, deleting records, creating and modifying tables.
• IBM developed the original version of SQL, originally called Structured
English Query Language (SEQUEL), as part of the System R project in
the early 1970s. The Sequel language has evolved since then, and its
name has changed to SQL (Structured Query Language).
• Today almost all RDBMS(MySQL, Oracle, Infomix, Sybase, MS
Access) uses SQL as the standard database language. SQL is used to
perform all type of data operations in RDBMS.

• The SQL language has several parts:

 Data-definition language (DDL). The SQL DDL used to


create , alter and delete tables.

 Data-manipulation language (DML). DML commands


used to insert , update and delete the data in the database.
 data Control language(DCL) The DCL consists of
commands that control the user access to database objects.
Example:- Commit, Rollback and Save point
 Data query language(DQL) this SQL commands enable
the users to query one or more tables to get information they
want. Example -select command
Characteristics of SQL
• SQL is easy to learn.
• SQL is used to access data from relational database management
systems.
• SQL can execute queries against the database.
• SQL is used to describe the data.
• SQL is used to define the data in the database and manipulate it when
needed.
• SQL is used to create and drop the database and table.
• SQL is used to create a view, stored procedure, function in a database.
• SQL allows users to set permissions on tables, procedures, and views.

Some advantages of SQL are as follows:

1. Faster Query Processing –


Large amount of data is retrieved quickly and efficiently. Operations like
Insertion, deletion, manipulation of data is also done in almost no time.
2. No Coding Skills –
For data retrieval, large number of lines of code is not required. All basic
keywords such as SELECT, INSERT INTO, UPDATE, etc are used and
also the syntactical rules are not complex in SQL, which makes it a user-
friendly language.
3. Standardised Language –
Due to documentation and long establishment over years, it provides a
uniform platform worldwide to all its users.
4. Portable –
It can be used in programs in PCs, server, laptops independent of any
platform (Operating System, etc). Also, it can be embedded with other
applications as per need/requirement/use.
5. Interactive Language –
Easy to learn and understand, answers to complex queries can be received
in seconds.
6. Multiple data views –users can view data from multiple tables.
7. High speed: - Using the SQL queries, the user can quickly and efficiently
retrieve a large amount of records from a database.
8. Easy to learn and understand: - SQL mainly consists of English
Statements and it is very easy to learn and understand a SQL query.
Disadvantages of SQL
1. Partial Control The programmers who use SQL don’t have a full control
over the database because of the hidden business rules.
2. Implementation Some of the databases go to the proprietary extensions
to standard SQL for ensuring the vendor lock-in.
3. Complex Interface – SQL has a difficult interface that makes few
users uncomfortable while dealing with the database.
4. Cost – Some versions are costly and hence, programmers cannot access
it.

SQL Data Types

The SQL standard supports a variety of built-in types, including:


a. char(n): A fixed-length character string with user-specified
length n. The full form, character, can be used instead.
b. varchar(n): A variable-length character string with user-
specified maximum length n. The full form, character varying,
is equivalent.
c. int: An integer (a finite subset of the integers that is machine
dependent). The full form, integer, is equivalent.
d. smallint: A small integer (a machine-dependent subset of the
integer type).
e. numeric( p, d): A fixed-point number with user-specified
precision. The num- ber consists of p digits (plus a sign), and d of
the p digits are to the right of the decimal point. Thus,
numeric(3,1) allows 44.5 to be stored exactly, but neither 444.5
or 0.32 can be stored exactly in a field of this type.
f. real, double precision: Floating-point and double-precision
floating-point numbers with machine-dependent precision.
g. float(n): A floating-point number, with precision of at least n
digits.
h. Date:-Date data type for storing date and time. The default format
is DD-MM-YY. Example: - ’12-OCT-94’
i. LONG:-Character data up to length of 2GB.Only one long column
is allowed per table.
j. Timestamp: The TIMESTAMP data type is used for values that
contain both date and time parts. TIMESTAMP has a range of '19-
Jan-1970 00:00:01'

SQL Literals

• A literal in SQL is a constant value used in SQL statements. It can be


used for inserting into columns of table , for updating existing column
values, for comparing with columns and various expressions that can be
used in SQL Statements.
• There are four kinds of literal values supported in SQL. They are :
Character string, Bit string, Exact numeric, and Approximate numeric.
These are explained as following below.

• Character string :
Character strings are written as a sequence of characters enveloped in
single quotes. the only quote character is delineate at intervals a
personality string by 2 single quotes. Some example of character strings
are :

• ‘My String’

• ‘I love GeeksForGeeks’

• Bit string :
A bit string is written either as a sequence of 0s and 1s enveloped in
single quotes and preceded by the letter ‘B’ or as a sequence of
positional representation system digits enveloped in single quotes and
preceded by the letter X’ some examples are given below :

• B ’10001011′

• B ’1′

• Exact numeric :
These literals ar written as a signed or unsigned decimal variety
probably with mathematical notation. Samples of actual numeric literals
are given below :

• 8

• +88.88

• Approximate numeric :
Approximate numeric literals are written as actual numeric literals
followed by the letter ‘E’, followed by a signed or unsigned number.
Some example are :

• 6E6

• 66.6E6
• +66E-6

SQL Commands
o SQL commands are instructions. It is used to communicate with the
database. It is also used to perform specific tasks, functions, and queries
of data.
o SQL can perform various tasks like create a table, add data to tables, drop
the table, modify the table, set permission for users.

Types of SQL Commands

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

1. Data Definition Language (DDL)


o DDL changes the structure of the table like creating a table, deleting a
table, altering a table, etc.
o All the command of DDL are auto-committed that means it permanently
save all the changes in the database.

Here are some commands that come under DDL:

o CREATE
o ALTER
o DROP
o TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(
100), DOB DATE);

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax DROP TABLE ;

Example DROP TABLE EMPLOYEE;

c. ALTER: It is used to alter the structure of the database. This change could be
either to modify the characteristics of an existing attribute or probably to add a
new attribute.

1. To add a new column in the table


Syntax ALTER TABLE table_name ADD column_name COLUMN-
definition;
Example -ALTER TABLE STU ADD(ADDRESS VARCHAR2(20));
2. To modify existing column in the table:
Syntax ALTER TABLE MODIFY(COLUMN DEFINITION....);

EXAMPLE ALTER TABLE STU MODIFY (NAME VARCHAR2(20));


3. ALTER TABLE - Drop COLUMN in table
ALTER TABLE Customers DROP COLUMN Email;
4. Rename Table:
SyntaxALTER TABLE oldtablename RENAME TO newtablename;
Example :- Alter table stu rename to emp;
5. Rename columns:- ALTER TABLE Student RENAME COLUMN
city TO location;

d. TRUNCATE: It is used to delete all the rows from the table and free the
space containing the table.
Syntax: TRUNCATE TABLE table_name;

Example: TRUNCATE TABLE EMPLOYEE;

2. Data Manipulation Language


o DML commands are used to modify the database. It is responsible for all
form of changes in the database.
o The command of DML is not auto-committed that means it can't
permanently save all the changes in the database. They can be rollback.

Here are some commands that come under DML:

o INSERT
o UPDATE
o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data


into the row of a table.

Syntax: INSERT INTO TABLE_NAME (col1, col2, col3,.... col N)


VALUES (value1, value2, value3, .... valueN);

Or

INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN


);

For example: INSERT INTO stu VALUES ("Sonoo", "DBMS");

b. UPDATE: This command is used to update or modify the value of a column


in the table.

Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = value
N] [WHERE CONDITION]

For example:

UPDATE students SET Name = 'Sonoo' WHERE Rollno = '3'

c. DELETE: It is used to remove one or more row from a table.


Syntax: DELETE FROM table_name [WHERE condition];

For example:

DELETE FROM students WHERE name='Sonoo';


3. Data Control Language

DCL commands are used to grant and take back authority from any database
user.

Here are some commands that come under DCL:

o Grant
o Revoke

a. Grant: It is used to give user access privileges to a database.

SYNTAX:- GRANT privilege_name


ON object_name
TO {user_name}
[WITH GRANT OPTION];

Example Create user mno identified by pass;


GRANT select ON workers TO MNO;
Grant create session to MNO;
commit;
………………….
Connect mno/pass;
Select * from system.workers;

b. Revoke: It is used to take back permissions from the user.

Syntax:
REVOKE <privilege list>
ON <relation name or view name>
FROM <user name>;

For Example:- REVOKE select ON workers FROM MNO;

4. Transaction Control Language

TCL commands can only use with DML commands like INSERT, DELETE
and UPDATE only.
These operations are automatically committed in the database that's why they
cannot be used while creating tables or dropping them.

Here are some commands that come under TCL:

o COMMIT
o ROLLBACK
o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the


database.

Syntax:

COMMIT;

Example:

DELETE FROM CUSTOMERS WHERE AGE = 25;


COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not


already been saved to the database.

Syntax:

ROLLBACK;

Example:

DELETE FROM CUSTOMERS WHERE AGE = 25;


ROLLBACK;

c. SAVEPOINT: It is used to roll the transaction back to a certain point without


rolling back the entire transaction.

Syntax: SAVEPOINT SAVEPOINT_NAME;

Example create table stud(rollno int,name char(12));


savepoint a;
insert into stud values(101,'aman');
savepoint b;
rollback to a;

5. Data Query Language

DQL is used to fetch the data from the database.

It uses only one command:

o SELECT

a. SELECT: This is the same as the projection operation of relational algebra.


It is used to select the attribute based on the condition described by WHERE
clause.

Syntax:

SELECT expressions FROM TABLES WHERE conditions;

For example:

SELECT emp_name FROM employee WHERE age > 20;


SQL Operators

SQL statements generally contain some reserved words or characters that are
used to perform operations such as comparison and arithmetical operations etc.
These reserved words or characters are known as operators.

Generally there are three types of operators in SQL:

1. SQL Arithmetic Operators


2. SQL Comparison Operators
3. SQL Logical Operators

SQL Arithmetic Operators

Assume 'variable a' holds 10 and 'variable b' holds 20, then −

Operator Description Example

+ (Addition) Adds values on either side of the operator. a+b


will give
30

Subtracts right hand operand from left hand operand. a - b will


- (Subtraction)
give -10

* Multiplies values on either side of the operator. a * b will


(Multiplication) give 200

Divides left hand operand by right hand operand. b / a will


/ (Division)
give 2

Divides left hand operand by right hand operand and b%a


% (Modulus) returns remainder. will give
0

Example of Arithmetic Operator in SQL

SELECT 15+10-5*5/5 FROM dual;

SELECT code, (commission*2) FROM agents;

SQL Comparison Operators

Assume 'variable a' holds 10 and 'variable b' holds 20, then −

Operato Description Example


r

Checks if the values of two operands are equal or not, if yes (a = b) is


=
then condition becomes true. not true.

Checks if the values of two operands are equal or not, if (a != b)


!=
values are not equal then condition becomes true. is true.

Checks if the values of two operands are equal or not, if (a <> b)


<>
values are not equal then condition becomes true. is true.
Checks if the value of left operand is greater than the value of (a > b) is
>
right operand, if yes then condition becomes true. not true.

Checks if the value of left operand is less than the value of (a < b) is
<
right operand, if yes then condition becomes true. true.

Checks if the value of left operand is greater than or equal to (a >= b)


>= the value of right operand, if yes then condition becomes true. is not
true.

Checks if the value of left operand is less than or equal to the (a <= b)
<=
value of right operand, if yes then condition becomes true. is true.

Example of Comparison Operators in SQL

SELECT * FROM agents WHERE commission> 2;

SELECT * FROM agents WHERE commission<= 5

SQL Logical Operators

Here is a list of all the logical operators available in SQL.


Sr.No Operator & Description
.

AND The AND operator allows the existence of multiple conditions in an


1
SQL statement's WHERE clause.

NOT The NOT operator reverses the meaning of the logical operator with
2 which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This
is a negate operator.

OR The OR operator is used to combine multiple conditions in an SQL


3 statement's WHERE clause.
Example of Logical Operators in SQL

 SELECT code, area FROM agent WHERE code = 1 AND area = ‘knp’;
 SELECT code, area FROM agent WHERE code = 1 OR area = ‘knp’;
 SELECT * FROM agent WHERE NOT code>1;

Set Operators

Set operators combine the results of two separate queries into single result.
following table shows different set operators

Different Set Operators

Operator Returns

UNION All distinct rows selected by either query

INTERSECT Return common rows selected by both queries

MINUS All distinct rows selected by the first query but not the second

UNION ALL All rows selected by either query, including all duplicates

Operator Precedence
Precedence is the order in which Oracle evaluates different operators in the
same expression. When evaluating an expression containing multiple operators,
Oracle evaluates operators with higher precedence before evaluating those with
lower precedence. Oracle evaluates operators with equal precedence from left to
right within an expression. Operators listed on the same line have the same
precedence.
Aggregate Functions:-
Aggregate functions in DBMS take multiple rows from the table and return a
value according to the query.
All the aggregate functions are used in Select statement.
SQL aggregate function is used to perform the calculations on multiple rows of
a single column of a table. It returns a single value.
It is also used to summarize the data.
Various Aggregate Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
COUNT() Function
The count function returns the number of rows in the result. It does not count
the null values.
Example: Write a query to return number of rows where salary > 20000.

Select COUNT(*) from Employee where Salary > 20000;


Types −
 COUNT(*): Counts all the number of rows of the table including null.
 COUNT( COLUMN_NAME): count number of non-null values in
column.
 COUNT( DISTINCT COLUMN_NAME): count number of distinct
values in a column.

MAX() Function
 The MAX function is used to find maximum value in the column that is
supplied as a parameter. It can be used on any type of data.
 Example − Write a query to find the maximum salary in employee table.
 Select MAX(salary) from Employee

SUM() Function
This function sums up the values in the column supplied as a parameter.
Example: Write a query to get the total salary of employees.

Select SUM(salary) from Employee

AVG() Function
This function returns the average value of the numeric column that is supplied
as a parameter.
Example: Write a query to select average salary from employee table.

Select AVG(salary) from Employee

MIN() Function
The aggregate function SQL MIN() is used to find the minimum value or
lowest value of a column or expression. This function is useful to determine the
smallest of all selected values of a column
Example: Write a query to select minimum salary from employee table.

Select min(salary) from Employee

SQL Group by Clause


It is used in SQL select statement to collect data across multiple records and
group the results by one or more columns. The GROUP BY statement is often
used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the
result-set by one or more columns.
o The SELECT statement is used with the GROUP BY clause in the SQL
query.
o WHERE clause is placed before the GROUP BY clause in SQL.
o ORDER BY clause is placed after the GROUP BY clause in SQL.

Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
Having Clause condition
ORDER BY column1, column2;

Emp table:-

Empid Empname address salary


101 Ajay Knp 50,000
102 Amit Lko 80,000
103 Devesh Knp 60,000
104 Rajesh Lko 70,000
For Example:-
a)Group with name and count total no of employees

select empname,count(emp) from emp group by name;


b)Find the emp name and sum of all emp salary

Select empname ,sum(salary) from emp group by name;

c)Find the empname and total salary increment by 1000 of all employees;

Select empname ,sum(salary) from emp group by name;

d)Find the all the empid with minimum salary

select empid, min(salary) from emp group by empid;

Having Clause:
The having clause tells SQL to include only certain groups produced by the
group by clause in the query result set. Having is used to specify the search
criteria when group by is used.
For Example
a) Find the empname and total salary of all employees except employee
'Ajay'
Select empname ,sum(salary) from emp group by empname having
empname<>'ajay';

b)Display the emp salary , name of employee whose second character of


name contains 'm'

Select salary, empname from emp group by empname, salary having empname
like '_m%';

Where Clause

The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified condition.


WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Find the name of employee that has deptname cs

select empname from emp where deptname='cs';

Difference between Where and Having Clause:-

Order by Clause:- The ORDER BY keyword is used to sort the result-set in


ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To
sort the records in descending order, use the DESC keyword.

ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
a) Display all the empname with salary in ascending order

select empname,salary from emp order by empname asc;

b)Display all the empid ,empname,salary in decreasing order of salary

select empid,empname,salary from emp order by salary desc;

G) IN Clause:- The IN operator allows you to specify multiple values in a


WHERE clause. The IN operator is a shorthand for multiple OR conditions.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

For Example:- Consider StoreInfo table

Storename Sales
Los angeles 1500
San diego 250
San franciso 300
Boston 700

Select * from storeinfo where storename IN(‘Los Angeles’,’San Diego’);


Result:-
Storename Sales
Los Angeles 1500
San diego 250

H) BETWEEN KEYWORD:- The BETWEEN operator selects values within


a given range. The values can be numbers, text, or dates.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

For Example:- Consider StoreInfo table


Select * from StoreInfo where sales between 200 and 350;
Result:-
Storename Sales
San diego 250
Los Angeles 300

I) 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 represents a single character
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

For Example:- Consider StoreInfo Table


Select * from storeinfo where storename like’%AN%’;

Storename Sales
Los Angeles 1500
San diego 250
Los Angeles 300
Sub Queries:-
A subquery is a query within another query. The outer query is called
as main query and inner query is called as subquery.
A Subquery or Inner query or a Nested query is a query within another SQL
query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a
condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
You can place the Subquery in a number of SQL
clauses: WHERE clause, HAVING clause, FROM clause.
There are a few rules that subqueries must follow −
 Subqueries must be enclosed within parentheses.
 A subquery can have only one column in the SELECT clause, unless
multiple columns are in the main query for the subquery to compare its
selected columns.
 ORDER BY command cannot be used in a
Subquery. GROUPBY command can be used to perform same function
as ORDER BY command.
 Subqueries that return more than one row can only be used with multiple
value operators such as the IN operator.

Sub Queries with the SELECT Statement

Subqueries are most frequently used with the SELECT statement. The basic
syntax is as follows −

SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE ... );

For Example BOOK TABLE

ISBN TITLE PUB_YEA UNIT AUTHOR PUBLISHER


R PRICE NAME NAME
1001 ORACLE 2004 399 AROA PHI
1002 DBMS 2004 400 BASU TECHNICAL
2001 DOS 2003 250 SINHA NIRALI
2002 ADBMS 2004 450 BASU TECHNICAL
2003 UNIX 2000 300 KAPOOR SCITECH

Author Table:

Authorname Pubadd
Aroa Us
Kapoor Canada
Basu India
Sinha India

Ques : -Display the title ,author and publisher name of all books published
in 2000, 2002 and 2004.

SQL> select title ,author and publisher name, PUB_YEAR from book where
pub_year in('2000', '2002', '2004');
TITLE AUTHOR PUBLISHER PUB_YEAR
NAME NAME
ORACLE AROA PHI 2004
DBMS BASU TECHNICAL 2004
ADBMS BASU TECHNICAL 2004
UNIX KAPOOR SCITECH 2000

Ques: Get details of author who have published book in the year 2004

SQL> Select * from author where authorname in( select AUTHORNAME


from book where pub_year=2004);

NOT IN

Display the title, author and publisher name of all books except those which are
published in the year 2002, 2004 ,2005.

SQL>select title, author , publisher name from book where pub_year not in
('2002','2004','2005');

Get titles of all books written by author not living in india

SQL> Select title from book where author not in (select authorname from
author where pubadd='India');

Set Comparison

Nested subqueries are used to compare sets.SQL use various operators such as
<,<=,>,>=,<>,any ,all etc to compare sets.

Ques: Display the titles of books have price greater than at least one book
published in year 2004

SQL> select distinct title from book where unitprice > some (select unitprice
from book where pub_year=2004;

>some means outer query is true if the unit price of the row is greater than at
least one values of all unit prices published in year 2004

Ques Display the titles of books that have price greater than that all books
publiser in year 2004.
SQL> select distinct title from book where unitprice > all (select unitprice from
book where pub_year=2004;

>all means outer query is true if the unitprice of all row is greater than all values
of unitprice published in year 2004.

Subqueries with the INSERT Statement

Subqueries also can be used with INSERT statements. The INSERT statement
uses the data returned from the subquery to insert into another table . The
structure of both tables must be same.

The basic syntax is as follows.


INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]

SQL> INSERT INTO employee SELECT * FROM emp WHERE empid IN


(SELECT empid FROM emp);

Subqueries with the UPDATE Statement

The subquery can be used in conjunction with the UPDATE statement. Either
single or multiple columns in a table can be updated when using a subquery
with the UPDATE statement.
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
SQL> UPDATE employee
SET SALARY = SALARY * 0.25
WHERE empid IN (SELECT empid FROM emp);
Subqueries with the DELETE Statement

The subquery can be used in conjunction with the DELETE statement like with
any other statements mentioned above.
The basic syntax is as follows.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
SQL> DELETE FROM employee
WHERE empid IN (SELECT empid FROM emp);

Exists and not Exists in sub queries

Ques:- get the title names of all book for which authorname exist in author
table.

select title from book where exists(select * from author where


book.authorname=author.authorname);

Ques:- get the title names of all book for which no authorname exist in
author table.

select title from book where not exists(select * from author where
book.authorname=author.authorname);

Views in SQL
 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 condition or all the
rows of a table.
 A View in SQL as a logical subset of data from one or more tables.
Views are used to restrict data access. A View contains no data of its
own but it's like window through which data from tables can be viewed
or changed. The table on which a View is based are called BASE
Tables.
BOOK TABLE

ISBN TITLE PUB_YEA UNIT AUTHOR PUBLISHER


R PRICE NAME NAME
1001 ORACLE 2004 399 AROA PHI
1002 DBMS 2004 400 BASU TECHNICAL
2001 DOS 2003 250 SINHA NIRALI
2002 ADBMS 2004 450 BASU TECHNICAL
2003 UNIX 2000 300 KAPOOR SCITECH

Author Table:

Authorname Pubadd
Aroa Us
Kapoor Canada
Basu India
Sinha India

1. Creating view A view can be created using the CREATE VIEW statement.
We can create a view from a single table or multiple tables.
CREATE VIEW view_name AS SELECT column1, column2.....
FROM table_name WHERE condition;

2. Creating View from a single table:- In this example, we create a View


named DetailsView from the table book.

Query:
CREATE VIEW DetailsView AS SELECT title, author_name
FROM book ;

To display data of View: - SELECT * FROM DetailsView;

4. Deleting View:-
A view can be deleted using the Drop View statement.

Syntax DROP VIEW view_name;

Example: If we want to delete the View MarksView, we can do this as:


DROP VIEW DetailsView;
Types of Views in SQL:

Simple View and Complex View. Simple views can only contain a single base
table. Complex views can be constructed on more than one base table. In
particular, complex views can contain: join conditions, a group by clause, a
order by clause.

Creating View from a single table(Simple View):- In this example, we create


a View named DetailsView from the table book.

Simple View Query:


CREATE VIEW Details AS SELECT Isbn, title, pub_year, author_name,
unit_price FROM book ;

Creating View from multiple tables (Complex view)


View from multiple tables can be created by simply include multiple tables in
the SELECT statement.
In the given example, a view is created named MarksView from two tables
book and author

Complex View Query:


CREATE VIEW MarksView AS SELECT book.isbn,sum(unitprice) as
sumprice FROM book, author WHERE book.authorname = author.authorname
group by book.isbn order by book.isbn ;

Difference Between Simple and Complex View:

Simple View Complex View

Contains only one single base


table or is created from only Contains more than one base tables or is
one table. created from more than one tables.

We cannot use aggregate


functions like MAX(),
COUNT(), etc. We can use aggregate functions.

Does not contain groups of data It can contain groups of data using group
using group by clause. by clause
DML operations could be
performed through a simple DML operations could not always be
view. performed through a complex view.

INSERT, DELETE and


UPDATE are directly possible We cannot apply INSERT, DELETE and
on a simple view. UPDATE on complex view directly.

In Simple View one cannot However on other hand in case of


include NOT NULL columns Complex view, NOT NULL columns can
from base table. be included in complex view.

Read Only view


SQL> Create view readonlyview as select isbn,title,pub_year from book
with read only;
view can be used for data manipulation that is the user can perform insert,
update and the delete operation on the view. the views on which data
manipulation can be done are called updatable view . views that do not allow
data manipulation are called Readonly view.
Indexes in SQL
o Indexes are special lookup tables. It is used to retrieve data from the
database very fast.
o An Index is used to speed up select queries and where clauses. But it
shows down the data input with insert and update statements. Indexes can
be created or dropped without affecting the data.
o An index in a database is just like an index in the back of a book.
o For example: When you reference all pages in a book that discusses a
certain topic, you first have to refer to the index, which alphabetically
lists all the topics and then referred to one or more specific page numbers.
Types of Index in SQL

1. Simple Index or Single Column index

It is used to create an index on a single table. It allows duplicate value.

Syntax
CREATE INDEX index_name ON table_name (column1, column2, ...);

Example

CREATE INDEX idx_name ON Persons (LastName, FirstName);

2. Composite Indexes

A composite index is an index on two or more columns of a table. Its basic


syntax is as follows.
CREATE INDEX index_name on table_name (column1, column2)

3. Unique Index

It is used to create a unique index on a table. It does not allow duplicate value.

Syntax

CREATE UNIQUE INDEX index_name ON table_name (column1, column2, .


..);

Example

CREATE UNIQUE INDEX websites_idx ON websites (site_name);

Drop Index Statement

It is used to delete an index in a table.

Syntax

DROP INDEX index_name;

Example
DROP INDEX websites_idx;

What is PL/SQL

PL/SQL is a block structured language. The programs of PL/SQL are logical


blocks that can contain any number of nested sub-blocks. Pl/SQL stands for
"Procedural Language extension of SQL" that is used in Oracle. PL/SQL is
integrated with Oracle database (since version 7). The functionalities of
PL/SQL usually extended after each release of Oracle database. Although
PL/SQL is closely integrated with SQL language, yet it adds some
programming constraints that are not available in SQL.

PL/SQL is a combination of SQL along with the procedural features of


programming languages. It was developed by Oracle Corporation in the early
90's to enhance the capabilities of SQL. PL/SQL is one of three key
programming languages embedded in the Oracle Database, along with SQL
itself and Java. This tutorial will give you great understanding on PL/SQL to
proceed with Oracle database and other advanced RDBMS concepts.

PL/SQL is a block structured language that can have multiple blocks in it.

PL/SQL language such as conditional statements, triggers, procedures, cursors


etc. There are also given PL/SQL interview questions and quizzes to help you
better understand the PL/SQL language.

SQL stands for Structured Query Language i.e. used to perform operations on
the records stored in database such as inserting records, updating records,
deleting records, creating, modifying and dropping tables, views etc.

PL/SQL stands for “Procedural Language extensions to the Structured Query


Language”. SQL is a popular language for both querying and updating data in
the relational database management systems (RDBMS). PL/SQL adds many
procedural constructs to SQL language to overcome some limitations of SQL.
Besides, PL/SQL provides a more comprehensive programming language
solution for building mission-critical applications on Oracle Databases.

PL/SQL is a highly structured and readable language. Its constructs express the
intent of the code clearly. Also, PL/SQL is a straightforward language to learn.

PL/SQL is a standard and portable language for Oracle Database development.


If you develop a program that executes on an Oracle Database, you can quickly
move it to another compatible Oracle Database without any changes.
PL/SQL is an embedded language. PL/SQL only can execute in an Oracle
Database. It was not designed to use as a standalone language like Java, C#, and
C++. In other words, you cannot develop a PL/SQL program that runs on a
system that does not have an Oracle Database.

PL/SQL is a high-performance and highly integrated database language.


Besides PL/SQL, you can use other programming languages such as Java, C#,
and C++. However, it is easier to write efficient code in PL/SQL than other
programming languages when it comes to interacting with the Oracle Database.
In particular, you can use PL/SQL specific constructs like
the FORALL statement that helps improve database performance.

PL/SQL architecture

The following picture illustrates the PL/SQL architecture:

PL/SQL engine is in charge of compiling PL/SQL code into byte-code and


executes the executable code. The PL/SQL engine can only be installed in an
Oracle Database server or an application development tool such as Oracle
Forms.

Triggers in PL/SQL
Triggers are stored programs, which are automatically executed or fired when
some events occur. Triggers are, in fact, written to be executed in response to
any of the following events −
 A database manipulation (DML) statement (DELETE, INSERT, or
UPDATE)
 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF,
STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the
event is associated.
Benefits of Triggers
Triggers can be written for the following purposes −

 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

Creating Triggers

The syntax for creating a trigger is −


CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER
ON table_name
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
 CREATE [OR REPLACE] TRIGGER trigger_name − Creates or
replaces an existing trigger with the trigger_name.
 {BEFORE | AFTER } − This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML
operation.
 [ON table_name] − This specifies the name of the table associated with
the trigger.
 [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger
will be executed for each row being affected. Otherwise the trigger will
execute just once when the SQL statement is executed, which is called a
table level trigger.
 WHEN (condition) − This provides a condition for rows for which the
trigger would fire. This clause is valid only for row-level triggers.
Example
To start with, we will be using the CUSTOMERS table we had created and
used in the previous chapters −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that
would fire for INSERT or UPDATE or DELETE operations performed on the
CUSTOMERS table. This trigger will display the salary difference between the
old values and new values −
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
Trigger created.
The following points need to be considered here −
 OLD and NEW references are not available for table-level triggers,
rather you can use them for record-level triggers.
 If you want to query the table in the same trigger, then you should use
the AFTER keyword, because triggers can query the table or change it
again only after the initial changes are applied and the table is back in a
consistent state.
 The above trigger has been written in such a way that it will fire before
any DELETE or INSERT or UPDATE operation on the table, but you
can write your trigger on a single or multiple operations, for example
BEFORE DELETE, which will fire whenever a record will be deleted
using the DELETE operation on the table.

Triggering a Trigger

Let us perform some DML operations on the CUSTOMERS table. Here is one
INSERT statement, which will create a new record in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
When a record is created in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following
result −
Old salary:
New salary: 7500
Salary difference:
Because this is a new record, old salary is not available and the above result
comes as null. Let us now perform one more DML operation on the
CUSTOMERS table. The UPDATE statement will update an existing record in
the table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following
result −
Old salary: 1500
New salary: 2000
Salary difference: 500

PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which
performs one or more specific tasks. It is just like procedures in other
programming languages.
The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the
parameters or variables passed to the procedure.
o Body: The body contains a declaration section, execution section and
exception section similar to a general PL/SQL block.

How to pass parameters in procedure:

When you want to create a procedure or function, you have to define parameters
.There is three ways to pass parameters in procedure:

1. IN parameters: The IN parameter can be referenced by the procedure or


function. The value of the parameter cannot be overwritten by the
procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the
procedure or function, but the value of the parameter can be overwritten
by the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the
procedure or function and the value of the parameter can be overwritten
by the procedure or function.

Creating a Procedure
A procedure is created with the CREATE OR REPLACE
PROCEDURE statement. The simplified syntax for the CREATE OR
REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
 procedure-name specifies the name of the procedure.
 [OR REPLACE] option allows the modification of an existing procedure.
 The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and
OUT represents the parameter that will be used to return a value outside
of the procedure.
 procedure-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a
standalone procedure.

Parameter Modes in PL/SQL Subprograms

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

S.No Parameter Mode & Description

IN
An IN parameter lets you pass a value to the subprogram. It is a read-
only parameter. Inside the subprogram, an IN parameter acts like a
1 constant. It cannot be assigned a value. You can pass a constant,
literal, initialized variable, or expression as an IN parameter. You can
also initialize it to a default value; however, in that case, it is omitted
from the subprogram call. It is the default mode of parameter
passing. Parameters are passed by reference.
OUT
An OUT parameter returns a value to the calling program. Inside the
2
subprogram, an OUT parameter acts like a variable. You can change
its value and reference the value after assigning it. The actual
parameter must be variable and it is passed by value.

IN OUT
An IN OUT parameter passes an initial value to a subprogram and
returns an updated value to the caller. It can be assigned a value and
3 the value can be read.
The actual parameter corresponding to an IN OUT formal parameter
must be a variable, not a constant or an expression. Formal parameter
must be assigned a value. Actual parameter is passed by value.

IN & OUT Mode Example 1


This program finds the minimum of two values. Here, the procedure takes two
numbers using the IN mode and returns their minimum using the OUT
parameters.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
Minimum of (23, 45) : 23

PL/SQL procedure successfully completed.


IN & OUT Mode Example 2
This procedure computes the square of value of a passed value. This example
shows how we can use the same parameter to accept a value and then return
another result.
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
Square of (23): 529

PL/SQL procedure successfully completed.

Create procedure Another example

In this example, we are going to insert record in user table. So you need to
create user table first.

Table creation:

create table user(id number(10) primary key,name varchar2(100));


Now write the procedure code to insert record in user table.

Procedure Code:

create or replace procedure "INSERTUSER"


(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into user values(id,name);
end;
/

PL/SQL program to call procedure

Let's see the code to call above created procedure.

BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully');
END;
/

Now, see the "USER" table, you will see one record is inserted.

ID Name

101 Rahul

PL/SQL Drop Procedure

Syntax for drop procedure


DROP PROCEDURE procedure_name;

Example of drop procedure

DROP PROCEDURE pro1;

Cursors In PL/SQL
A cursor is a pointer that points to a result of a query. PL/SQL has two
types of cursors: implicit cursors and explicit cursors.
Oracle creates a memory area, known as the context area, for processing an
SQL statement, which contains all the information needed for processing the
statement; for example, the number of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor. A cursor holds the rows (one or more) returned by a SQL
statement. The set of rows the cursor holds is referred to as the active set.

Declare a cursor

Before using an explicit cursor, you must declare it in the declaration section of
a block or package as follows:

CURSOR cursor_name IS query;


Code language: SQL (Structured Query Language) (sql)

In this syntax:

 First, specify the name of the cursor after the CURSOR keyword.
 Second, define a query to fetch data after the IS keyword.
Open a cursor

Before start fetching rows from the cursor, you must open it. To open a cursor,
you use the following syntax:

OPEN cursor_name;
Fetch from a cursor

The FETCH statement places the contents of the current row into variables. The
syntax of FETCH statement is as follows:

FETCH cursor_name INTO variable_list;


Code language: SQL (Structured Query Language) (sql)

To retrieve all rows in a result set, you need to fetch each row till the last one.

Closing a cursor

After fetching all rows, you need to close the cursor with the CLOSE statement:

CLOSE cursor_name;

Explicit Cursor Attributes


A cursor has four attributes to which you can reference in the following format:

cursor_name%attribute
Code language: SQL (Structured Query Language) (sql)

where cursor_name is the name of the explicit cursor.

1) %ISOPEN

This attribute is TRUE if the cursor is open or FALSE if it is not.

2) %FOUND

This attribute has four values:

 NULL before the first fetch


 TRUE if a record was fetched successfully
 FALSE if no row returned
 INVALID_CURSOR if the cursor is not opened
3) %NOTFOUND

This attribute has four values:

 NULL before the first fetch


 FALSE if a record was fetched successfully
 TRUE if no row returned
 INVALID_CURSOR if the cursor is not opened

3) %ROWCOUNT

The %ROWCOUNT attribute returns the number of rows fetched from the
cursor. If the cursor is not opened, this attribute returns INVALID_CURSOR.

Types of Cursors
You can name a cursor so that it could be referred to in a program to fetch and
process the rows returned by the SQL statement, one at a time. There are two
types of cursors −

 Implicit cursors
 Explicit cursors

Implicit Cursors

Implicit cursors are automatically created by Oracle whenever an SQL


statement is executed, when there is no explicit cursor for the statement.
Programmers cannot control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an
implicit cursor is associated with this statement. For INSERT operations, the
cursor holds the data that needs to be inserted. For UPDATE and DELETE
operations, the cursor identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor,
which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed
for use with the FORALL statement. The following table provides the
description of the most used attributes −

S.No Attribute & Description


%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one
or more rows or a SELECT INTO statement returned one or more rows.
Otherwise, it returns FALSE.

%NOTFOUND
2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE,
or DELETE statement affected no rows, or a SELECT INTO statement
returned no rows. Otherwise, it returns FALSE.

%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.

%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as shown


below in the example.
Example of CURSOR
We will be using the CUSTOMERS table we had created and used in the
previous chapters.
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each
customer by 500 and use the SQL%ROWCOUNT attribute to determine the
number of rows affected −

DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
6 customers selected

PL/SQL procedure successfully completed.


If you check the records in customers table, you will find that the rows have
been updated −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors

Explicit cursors are programmer-defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration
section of the PL/SQL Block. It is created on a SELECT Statement which
returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −

 Declaring the cursor for initializing the memory


 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory

Declaring the Cursor

Declaring the cursor defines the cursor with a name and the associated
SELECT statement. For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor

Opening the cursor allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it. For example, we will
open the above defined cursor as follows −
OPEN c_customers;

Fetching the Cursor

Fetching the cursor involves accessing one row at a time. For example, we will
fetch rows from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor

Closing the cursor means releasing the allocated memory. For example, we
will close the above-opened cursor as follows −
CLOSE c_customers;

Example
Following is a complete example to illustrate the concepts of explicit cursors

DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
PL/SQL procedure successfully completed.

You might also like