You are on page 1of 55

DBMS

Database is a collection of related data and data is a collection of facts and figures that can
be processed to produce information.
Mostly data represents recordable facts. Data aids in producing information, which is based
on facts. For example, if we have data about marks obtained by all students, we can then
conclude about toppers and average marks.
A database management system stores data in such a way that it becomes easier to retrieve,
manipulate, and produce information.

Characteristics
Traditionally, data was organized in file formats. DBMS was a new concept then, and all the
research was done to make it overcome the deficiencies in traditional style of data
management. A modern DBMS has the following characteristics

Real-world entity A modern DBMS is more realistic and uses real-world entities to
design its architecture. It uses the behavior and attributes too. For example, a school
database may use students as an entity and their age as an attribute.

Relation-based tables DBMS allows entities and relations among them to form
tables. A user can understand the architecture of a database just by looking at the table
names.

Isolation of data and application A database system is entirely different than its
data. A database is an active entity, whereas data is said to be passive, on which the
database works and organizes. DBMS also stores metadata, which is data about data,
to ease its own process.

Less redundancy DBMS follows the rules of normalization, which splits a relation
when any of its attributes is having redundancy in values. Normalization is a
mathematically rich and scientific process that reduces data redundancy.

Consistency Consistency is a state where every relation in a database remains


consistent. There exist methods and techniques, which can detect attempt of leaving
database in inconsistent state. A DBMS can provide greater consistency as compared
to earlier forms of data storing applications like file-processing systems.

Query Language DBMS is equipped with query language, which makes it more
efficient to retrieve and manipulate data. A user can apply as many and as different
filtering options as required to retrieve a set of data. Traditionally it was not possible
where file-processing system was used.

--1--

ACID Properties DBMS follows the concepts of Atomicity, Consistency, Isolation,


and Durability (normally shortened as ACID). These concepts are applied on
transactions, which manipulate data in a database. ACID properties help the database
stay healthy in multi-transactional environments and in case of failure.

Multiuser and Concurrent Access DBMS supports multi-user environment and


allows them to access and manipulate data in parallel. Though there are restrictions on
transactions when users attempt to handle the same data item, but users are always
unaware of them.

Multiple views DBMS offers multiple views for different users. A user who is in
the Sales department will have a different view of database than a person working in
the Production department. This feature enables the users to have a concentrate view
of the database according to their requirements.

Security Features like multiple views offer security to some extent where users are
unable to access data of other users and departments. DBMS offers methods to
impose constraints while entering data into the database and retrieving the same at a
later stage. DBMS offers many different levels of security features, which enables
multiple users to have different views with different features. For example, a user in
the Sales department cannot see the data that belongs to the Purchase department.
Additionally, it can also be managed how much data of the Sales department should
be displayed to the user. Since a DBMS is not saved on the disk as traditional file
systems, it is very hard for miscreants to break the code.

Users
A typical DBMS has users with different rights and permissions who use it for different
purposes. Some users retrieve data and some back it up. The users of a DBMS can be broadly
categorized as follows

Administrators Administrators maintain the DBMS and are responsible for


administrating the database. They are responsible to look after its usage and by whom
it should be used. They create access profiles for users and apply limitations to
maintain isolation and force security. Administrators also look after DBMS resources
like system license, required tools, and other software and hardware related
maintenance.
--2--

Designers Designers are the group of people who actually work on the designing
part of the database. They keep a close watch on what data should be kept and in what
format. They identify and design the whole set of entities, relations, constraints, and
views.

End Users End users are those who actually reap the benefits of having a DBMS.
End users can range from simple viewers who pay attention to the logs or market rates
to sophisticated users such as business analysts.

--3--

DBMS - Architecture
The design of a DBMS depends on its architecture. It can be centralized or decentralized or
hierarchical. The architecture of a DBMS can be seen as either single tier or multi-tier. An ntier architecture divides the whole system into related but independent n modules, which can
be independently modified, altered, changed, or replaced.
In 1-tier architecture, the DBMS is the only entity where the user directly sits on the DBMS
and uses it. Any changes done here will directly be done on the DBMS itself. It does not
provide handy tools for end-users. Database designers and programmers normally prefer to
use single-tier architecture.
If the architecture of DBMS is 2-tier, then it must have an application through which the
DBMS can be accessed. Programmers use 2-tier architecture where they access the DBMS by
means of an application. Here the application tier is entirely independent of the database in
terms of operation, design, and programming.

3-tier Architecture
A 3-tier architecture separates its tiers from each other based on the complexity of the users
and how they use the data present in the database. It is the most widely used architecture to
design a DBMS.

Database (Data) Tier At this tier, the


database resides along with its query
processing languages. We also have the
relations that define the data and their
constraints at this level.

Application (Middle) Tier At this tier


reside the application server and the
programs that access the database. For a
user, this application tier presents an
abstracted view of the database. Endusers are unaware of any existence of
the database beyond the application. At
the other end, the database tier is not
aware of any other user beyond the
application tier. Hence, the application layer sits in the middle and acts as a mediator
between the end-user and the database.

User (Presentation) Tier End-users operate on this tier and they know nothing
about any existence of the database beyond this layer. At this layer, multiple views of
the database can be provided by the application. All views are generated by
applications that reside in the application tier.
--4--

Multiple-tier database architecture is highly modifiable, as almost all its components are
independent and can be changed independently.

DBMS - Data Models


Data models define how the logical structure of a database is modeled. Data Models are
fundamental entities to introduce abstraction in a DBMS. Data models define how data is
connected to each other and how they are processed and stored inside the system.
The very first data model could be flat data-models, where all the data used are to be kept in
the same plane. Earlier data models were not so scientific, hence they were prone to introduce
lots of duplication and update anomalies.

Entity-Relationship Model
Entity-Relationship (ER) Model is based on the notion of real-world entities and relationships
among them. While formulating real-world scenario into the database model, the ER Model
creates entity set, relationship set, general attributes and constraints.
ER Model is best used for the conceptual design of a database.
ER Model is based on

Entities and their attributes.

Relationships among entities.

These concepts are explained below.

Entity An entity in an ER Model is a real-world entity having properties called


attributes. Every attribute is defined by its set of values called domain. For
example, in a school database, a student is considered as an entity. Student has various
attributes like name, age, class, etc.

Relationship The logical association among entities is called relationship.


Relationships are mapped with entities in various ways. Mapping cardinalities define
the number of association between two entities.
Mapping cardinalities
--5--

o one to one
o one to many
o many to one
o many to many

RDBMS
What is RDBMS
RDBMS stands for Relational Database Management Systems..
All modern database management systems like SQL, MS SQL Server, IBM DB2, ORACLE,
My-SQL and Microsoft Access are based on RDBMS.
It is called Relational Data Base Management System (RDBMS) because it is based on
relational model introduced by E.F. Codd.

How it works
Data is represented in terms of tuples (rows) in RDBMS.
Relational database is most commonly used database. It contains number of tables and each
table has its own primary key.
Due to a collection of organized set of tables, data can be accessed easily in RDBMS.

Brief History of RDBMS


During 1970 to 1972, E.F. Codd published a paper to propose the use of relational database
model.
RDBMS is originally based on that E.F. Codd's relational model invention.

What is table
The RDBMS database uses tables to store data. A table is a collection of related data entries
and contains rows and columns to store data.
A table is the simplest example of data storage in RDBMS.
Let's see the example of student table.
ID
1

Name
Ajeet
--6--

AGE

COURSE

24

B.Tech

aryan

20

C.A

What is field
Field is a smaller entity of the table which contains specific information about every record in
the table. In the above example, the field in the student table consist of id, name, age, course.

--7--

What is row or record


A row of a table is also called record. It contains the specific information of each individual
entry in the table. It is a horizontal entity in the table. For example: The above table contains
5 records.
Let's see one record/row in the table.
1

ARUN

24

M.C.A

What is column
A column is a vertical entity in the table which contains all information associated with a
specific field in a table. For example: "name" is a column in the above table which contains
all information about student's name.
Arun
Aryan

NULL Values
The NULL value of the table specifies that the field has been left blank during record
creation. It is totally different from the value filled with zero or a field that contains space.

Data Integrity
There are the following categories of data integrity exist with each RDBMS:
Entity integrity: It specifies that there should be no duplicate rows in a table.
Domain integrity: It enforces valid entries for a given column by restricting the type, the
format, or the range of values.
Referential integrity: It specifies that rows cannot be deleted, which are used by other
records.
User-defined integrity: It enforces some specific business rules that are defined by users.
These rules are different from entity, domain or referential integrity.

Difference between DBMS and RDBMS


Although DBMS and RDBMS both are used to store information in physical database but
there are some remarkable differences between them.
--8--

The main differences between DBMS and RDBMS are given below:
No.

DBMS

RDBMS

1
)

DBMS applications store data as


file.

RDBMS applications store data in a tabular form.

2
)

In DBMS, data is generally


stored in either a hierarchical
form or a navigational form.

In RDBMS, the tables have an identifier called


primary key and the data values are stored in the
form of tables.

3
)

Normalization is not present in


DBMS.

Normalization is present in RDBMS.

4
)

DBMS does not apply any


security with regards to data
manipulation.

RDBMS defines the integrity constraint for the


purpose of ACID (Atomocity, Consistency,
Isolation and Durability) property.

5
)

DBMS uses file system to store


data, so there will be no relation
between the tables.

in RDBMS, data values are stored in the form of


tables, so a relationship between these data
values will be stored in the form of a table as
well.

6
)

DBMS has to provide some


uniform methods to access the
stored information.

RDBMS system supports a tabular structure of


the data and a relationship between them to
access the stored information.

7
)

DBMS does
not
distributed database.

RDBMS supports distributed database.

8
)

DBMS is meant to be for small


organization and deal with small
data. it supports single user.

RDBMS is designed to handle large amount of


data. it supports multiple users.

9
)

Examples of DBMS are file


systems, xml etc.

Example of RDBMS are mysql, postgre, sql


server, oracle etc.

support

What is Database

A database is an organized collection of data.


Database handlers create database in such a way that only one set of software program
provide access of data to all the users.
The main purpose of database is to operate large amount of information by storing,
retrieving and managing.
There are many dynamic websites on the world wide web now a days which are
handled through databases. For example, a model to checks the availability of rooms
in a hotel. It is an example of dynamic website that uses database.
There are many database available like MySQL, Sybase, Oracle, Mango DB,
Informix, Postgre, SQL Server etc.
SQL or Structured Query Language is used to perform operation on the data stored in
a database. SQL depends on relational algebra and tuple relational calculus.
--9--

A cylindrical structure is used to display the image of a database.

SQL
What is SQL?
SQL is Structured Query Language, which is a computer language for storing, manipulating
and retrieving data stored in relational database.
SQL is the standard language for Relation Database System. All relational database
management systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL
Server use SQL as standard database language.
Also, they are using different dialects, such as:

MS SQL Server using T-SQL,

Oracle using PL/SQL,

MS Access version of SQL is called JET SQL (native format), etc

Why SQL?

Allows users to access data in relational database management systems.

Allows users to describe the data.

Allows users to define the data in database and manipulate that data.

Allows to embed within other languages using SQL modules, libraries & precompilers.

Allows users to create and drop databases and tables.

Allows users to create view, stored procedure, functions in a database.

Allows users to set permissions on tables, procedures, and views

What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL
and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and
Microsoft Access.
A Relational database management system (RDBMS) is a database management system
(DBMS) that is based on the relational model as introduced by E. F. Codd.

What is table ?
The data in RDBMS is stored in database objects called tables. The table is a collection of
related data entries and it consists of columns and rows.
--10--

Remember, a table is the most common and simplest form of data storage in a relational
database.

What is field?
Every table is broken up into smaller entities called fields. The fields in
the CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific
information about every record in the table.

What is record or row?


A record, also called a row of data, is each individual entry that exists in
a table. For example, there are 7 records in the above CUSTOMERS
table.
A record is a horizontal entity in a table.

What is column?
A column is a vertical entity in a table that contains all information
associated with a specific field in a table.

What is NULL value?


A NULL value in a table is a value in a field that appears to be blank
which means A field with a NULL value is a field with no value.
It is very important to understand that a NULL value is different than a
zero value or a field that contains spaces. A field with a NULL value is
one that has been left blank during record creation.

SQL Constraints:
Constraints are the rules enforced on data columns on 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 column level or table level. Column level constraints
are applied only to one column where as table level constraints are
applied to the whole table.

SQL Syntax:
SQL is followed by unique set of rules and guidelines called Syntax. This
tutorial gives you a quick start with SQL by listing all the basic SQL
Syntax:
All the SQL statements start with any of the keywords like SELECT,
INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the
statements end with a semicolon (;).

--11--

Important point to be noted is that SQL is case insensitive which


means SELECT and select have same meaning in SQL statements but
MySQL make difference in table names. So if you are working with
MySQL then you need to give table names as they exist in the database.

SQL SELECT Statement:


SELECT column1, column2....columnN
FROM table_name;

SQL DISTINCT Clause:


SELECT DISTINCT column1, column2....columnN
FROM table_name;

SQL WHERE Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION;

SQL AND/OR Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;

SQL IN Clause:
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);

SQL BETWEEN Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;

SQL Like Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE column_name LIKE { PATTERN };

SQL ORDER BY Clause:


SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};

SQL GROUP BY Clause:


SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;

SQL COUNT Clause:


--12--

SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;

SQL HAVING Clause:


SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);

SQL CREATE TABLE Statement:


CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);

SQL DROP TABLE Statement:


DROP TABLE table_name;

SQL CREATE INDEX Statement :


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

SQL DROP INDEX Statement :


ALTER TABLE table_name
DROP INDEX index_name;

SQL DESC Statement :


DESC table_name;

SQL TRUNCATE TABLE Statement:


TRUNCATE TABLE table_name;

SQL ALTER TABLE Statement:


ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};

SQL ALTER TABLE Statement (Rename) :


ALTER TABLE table_name RENAME TO new_table_name;

SQL INSERT INTO Statement:


INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);

SQL UPDATE Statement:


UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];

--13--

--14--

SQL DELETE Statement:


DELETE FROM table_name
WHERE {CONDITION};

SQL CREATE DATABASE Statement:


CREATE DATABASE database_name;

SQL DROP DATABASE Statement:


DROP DATABASE database_name;

SQL USE Statement:


USE DATABASE database_name;

SQL COMMIT Statement:


COMMIT;

SQL ROLLBACK Statement:


ROLLBACK;

SQL Statement

AND / OR

Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition
ALTER TABLE table_name
ADD column_name datatype

ALTER TABLE

or
ALTER TABLE table_name
DROP COLUMN column_name
SELECT column_name AS column_alias
FROM table_name

AS (alias)

or
SELECT column_name
FROM table_name AS table_alias

BETWEEN

SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2

CREATE
DATABASE

CREATE DATABASE database_name

CREATE TABLE

CREATE TABLE table_name


(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
...
)

CREATE INDEX

CREATE INDEX index_name


ON table_name (column_name)
or
CREATE UNIQUE INDEX index_name

--15--

SQL Statement

Syntax
ON table_name (column_name)

CREATE VIEW

CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition
DELETE FROM table_name
WHERE some_column=some_value
or

DELETE

DELETE FROM table_name


(Note: Deletes the entire table!!)
DELETE * FROM table_name
(Note: Deletes the entire table!!)

DROP DATABASE

DROP DATABASE database_name

DROP INDEX

DROP INDEX table_name.index_name (SQL Server)


DROP INDEX index_name ON table_name (MS Access)
DROP INDEX index_name (DB2/Oracle)
ALTER TABLE table_name
DROP INDEX index_name (MySQL)

DROP TABLE

DROP TABLE table_name

EXISTS

IF EXISTS (SELECT * FROM table_name WHERE id = ?)


BEGIN
--do what needs to be done if exists
END
ELSE
BEGIN
--do what needs to be done if not
END

GROUP BY

SELECT column_name, aggregate_function(column_name)


FROM table_name
WHERE column_name operator value
GROUP BY column_name

HAVING

SELECT column_name, aggregate_function(column_name)


FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value

IN

SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
INSERT INTO table_name
VALUES (value1, value2, value3,....)

INSERT INTO

or
INSERT INTO table_name
(column1, column2, column3,...)
VALUES (value1, value2, value3,....)

INNER JOIN

SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name

LEFT JOIN

SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

--16--

SQL Statement

Syntax

RIGHT JOIN

SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name

FULL JOIN

SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name

LIKE

SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern

ORDER BY

SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]

SELECT

SELECT column_name(s)
FROM table_name

SELECT *

SELECT *
FROM table_name

SELECT DISTINCT

SELECT DISTINCT column_name(s)


FROM table_name
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_table_name

SELECT INTO

or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name

SELECT TOP

SELECT TOP number|percent column_name(s)


FROM table_name

TRUNCATE TABLE

TRUNCATE TABLE table_name

UNION

SELECT column_name(s) FROM table_name1


UNION
SELECT column_name(s) FROM table_name2

UNION ALL

SELECT column_name(s) FROM table_name1


UNION ALL
SELECT column_name(s) FROM table_name2

UPDATE

UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value

WHERE

SELECT column_name(s)
FROM table_name
WHERE column_name operator value

--17--

SQL - Operators:
SQL Arithmetic Operators:
Assume variable a holds 10 and variable b holds 20, then:
Show Examples
Operator

Description

Example

Addition - Adds values on either side of the operator

a + b will give
30

Subtraction - Subtracts right hand operand from left hand operand

a - b will give
-10

Multiplication - Multiplies values on either side of the operator

a * b will give
200

Division - Divides left hand operand by right hand operand

b / a will give
2

Modulus - Divides left hand operand by right hand operand and returns remainder

b % a will give
0

SQL Comparison Operators:


Assume variable a holds 10 and variable b holds 20, then:
Operator

Description

Example

Checks if the values of two operands are equal or not, if yes then condition becomes
true.

(a = b) is not
true.

!=

Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.

(a != b) is
true.

<>

Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true.

(a <> b) is
true.

>

Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true.

(a > b) is not
true.

<

Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true.

(a < b) is
true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand,
if yes then condition becomes true.

(a >= b) is
not true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if
yes then condition becomes true.

(a <= b) is
true.

!<

Checks if the value of left operand is not less than the value of right operand, if yes then
condition becomes true.

(a !< b) is
false.

!>

Checks if the value of left operand is not greater than the value of right operand, if yes
then condition becomes true.

(a !> b) is
true.

--18--

SQL Logical Operators:


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

Description

ALL

The ALL operator is used to compare a value to all values in another value set.

AND

The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.

ANY

The ANY operator is used to compare a value to any applicable value in the list according to the condition.

BETWEEN

The BETWEEN operator is used to search for values that are within a set of values, given the minimum
value and the maximum value.

EXISTS

The EXISTS operator is used to search for the presence of a row in a specified table that meets certain
criteria.

IN

The IN operator is used to compare a value to a list of literal values that have been specified.

LIKE

The LIKE operator is used to compare a value to similar values using wildcard operators.

NOT

The NOT operator reverses the meaning of the logical operator with 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 statement's WHERE clause.

IS NULL

The NULL operator is used to compare a value with a NULL value.

UNIQUE

The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).

STRUCTURED DATA
Accessing structured data with SQL is quite different from the full text search of
documents on the Web. Structured data in the relational model means data that can
be represented in tables -- rows and columns. Each row in a table represents a
different object, and the columns represent various "attributes" of the object. The
columns have names and integrity constraints that specify valid values.
Since the column values are named and are represented in a consistent format, you
can select rows very precisely, based on their contents. This is especially helpful in
dealing with numeric data. You can also join together data from different tables,
based on matching column values. You can do useful types of analysis, listing
objects that are in one table and missing (or present, or have specific attributes)
from a related table. You can extract from a large table precisely those rows of
interest, regrouping them and generating simple statistics on them.
--19--

This document contains examples of:


creating a table
creating a view
inserting rows
updating rows
deleting rows
commit -- making changes permanent
rollback -- undoing temporary changes
enforcing integrity constraints
using an Embedded C program
INTERACTIVE SQL EXAMPLES

create a table to store information about weather


observation stations:
-- No duplicate ID fields allowed
CREATE TABLE STATION
(ID INTEGER PRIMARY KEY,
CITY CHAR(20),
STATE CHAR(2),
LAT_N REAL,
LONG_W REAL);
populate the table STATION with a few rows:
INSERT INTO STATION VALUES (13, 'Phoenix', 'AZ', 33, 112);
INSERT INTO STATION VALUES (44, 'Denver', 'CO', 40, 105);
INSERT INTO STATION VALUES (66, 'Caribou', 'ME', 47, 68);
query to look at table STATION in undefined order:
SELECT * FROM STATION;
--20--

ID
13
44
66

CITY
Phoenix
Denver
Caribou

STATE
AZ
CO
ME

LAT_N
33
40
47

LONG_W
112
105
68

query to select Northern stations (Northern latitude > 39.7):


-- selecting only certain rows is called a "restriction".
SELECT * FROM STATION
WHERE LAT_N > 39.7;
ID
44

CITY
Denver

STATE

LAT_N

CO

40

LONG_W
105

query to select only ID, CITY, and STATE columns:


-- selecting only certain columns is called a "projection".
SELECT ID, CITY, STATE FROM STATION;
ID
13
44
66

CITY

STATE

Phoenix
Denver
Caribou

AZ
CO
ME

query to both "restrict" and "project":


SELECT ID, CITY, STATE FROM STATION
WHERE LAT_N > 39.7;
ID
44
66

CITY

STATE

Denver
Caribou

CO
ME

create another table to store normalized temperature and precipitation data:


-- ID field must match some STATION table ID
(so name and location will be known).
-- allowable ranges will be enforced for other values.
-- no duplicate ID and MONTH combinations.
-- temperature is in degrees Fahrenheit.
-- rainfall is in inches.

--21--

CREATE TABLE STATS


(ID INTEGER REFERENCES STATION(ID),
MONTH INTEGER CHECK (MONTH BETWEEN 1 AND 12),
TEMP_F REAL CHECK (TEMP_F BETWEEN -80 AND 150),
RAIN_I REAL CHECK (RAIN_I BETWEEN 0 AND 100),
PRIMARY KEY (ID, MONTH));
populate the table STATS with some statistics for January and July:
INSERT INTO STATS VALUES (13, 1, 57.4, 0.31);
INSERT INTO STATS VALUES (13, 7, 91.7, 5.15);
INSERT INTO STATS VALUES (44, 1, 27.3, 0.18);
INSERT INTO STATS VALUES (44, 7, 74.8, 2.11);
INSERT INTO STATS VALUES (66, 1, 6.7, 2.10);
INSERT INTO STATS VALUES (66, 7, 65.8, 4.52);
query to look at table STATS in undefined order:
SELECT * FROM STATS;
ID

MONTH

TEMP_F

RAIN_I

13

57.4

.31

13

91.7

5.15

44

27.3

.18

44

74.8

2.11

66

6.7

2.1

66

65.8

4.52

query to look at table STATS, picking up location information by joining with


table STATION on the ID column:
-- matching two tables on a common column is called a "join".
-- the column names often match, but this is not required.
-- only the column values are required to match.
SELECT * FROM STATION, STATS
WHERE STATION.ID = STATS.ID;

--22--

ID
13
13
44
44
66
66

CITY
Phoenix
Phoenix
Denver
Denver
Caribou
Caribou

ST
AZ
AZ
CO
CO
ME
ME

LAT_N
33
33
40
40
47
47

LONG_W
112
112
105
105
68
68

ID
13
13
44
44
66
66

MONTH
1
7
1
7
1
7

TEMP_F RAIN_I
57.4
.31
91.7
5.15
27.3
.18
74.8
2.11
6.7
2.1
65.8
4.52

query to look at the table STATS, ordered by month and greatest rainfall,
with columns rearranged:
SELECT MONTH, ID, RAIN_I, TEMP_F
FROM STATS
ORDER BY MONTH, RAIN_I DESC;
MONTH

ID

RAIN_I

1 66
1 13
1 44
7 13
7 66
7 44

TEMP_F
2.1
.31
.18
5.15
4.52
2.11

6.7
57.4
27.3
91.7
65.8
74.8

Interactive SQL Update Examples

update all rows of table STATS to compensate for faulty


rain gauges known to read 0.01 inches low:
UPDATE STATS SET RAIN_I = RAIN_I + 0.01;
and take a look:
SELECT * FROM STATS;
ID
13
13
44

MONTH

TEMP_F
1
7
1

RAIN_I
57.4
91.7
27.3

--23--

.32
5.16
.19

44
66
66

7
1
7

74.8
6.7
65.8

2.12
2.11
4.53

update one row, Denver's July temperature reading, to correct a data entry
error:
UPDATE STATS SET TEMP_F = 74.9
WHERE ID = 44
AND MONTH = 7;
and take a look:
SELECT * FROM STATS;
ID

MONTH

13
13
44
44
66
66

TEMP_F
1
7
1
7
1
7

RAIN_I
57.4
91.7
27.3
74.9
6.7
65.8

make the above changes permanent:


-- they were only temporary until now.
COMMIT WORK;
update two rows, Denver's rainfall readings:
UPDATE STATS SET RAIN_I = 4.50
WHERE ID = 44;
and take a look:

--24--

.32
5.16
.19
2.12
2.11
4.53

SELECT * FROM STATS;


ID

MONTH

13
13
44
44
66
66

TEMP_F
1
7
1
7
1
7

RAIN_I
57.4
91.7
27.3
74.9
6.7
65.8

.32
5.16
4.5
4.5
2.11
4.53

Oops! We meant to update just the July reading! Undo that update:
-- undoes only updates since the last COMMIT WORK.
ROLLBACK WORK;
and take a look:
SELECT * FROM STATS;
ID

MONTH

13
13
44
44
66
66

TEMP_F
1
7
1
7
1
7

RAIN_I
57.4
91.7
27.3
74.9
6.7
65.8

now update Denver's July rainfall reading and make it permanent:


UPDATE STATS SET RAIN_I = 4.50
WHERE ID = 44
AND MONTH = 7;
COMMIT WORK;
and take a look:

--25--

.32
5.16
.19
2.12
2.11
4.53

SELECT * FROM STATS;


ID

MONTH

13

TEMP_F
1

RAIN_I
57.4

.32

delete July data and East Coast data from both tables:
-- note that we use longitude values from the related STATION table to determine
which STAT stations were east of 90 degrees.
DELETE FROM STATS
WHERE MONTH = 7
OR ID IN (SELECT ID FROM STATION
WHERE LONG_W < 90);
DELETE FROM STATION WHERE LONG_W < 90;
COMMIT WORK;
and take a look:

SELECT * FROM STATION;


ID
13
44

CITY

ST

Phoenix
Denver

LAT_N

AZ
CO

33
40

LONG_W
112
105

SELECT * FROM STATS;


ID
13
44

MONTH
1
1

TEMP_F
57.4
27.3

Embedded SQL C Program Example

Embedded C program to do the following:


--26--

RAIN_I
.32
.19

Starting with a station name (Denver, in this example), look


up the station ID.
Print the station ID.
List all rows for that station ID.
shows single-row select and use of cursor
note that all C-language variables used in SQL statements
are declared in the DECLARE SECTION.
note that all SQL statements begin with the syntax EXEC
SQL and terminate with a semicolon.

--27--

#include<stdio.h>
#include<string.h>
EXEC SQL BEGIN DECLARE SECTION;
long station_id;
long mon;
float temp;
float rain;
char city_name[21];
long SQLCODE;
EXEC SQL END DECLARE SECTION;
main()
{
/* the CONNECT statement, if needed, goes here */
strcpy(city_name,"Denver");
EXEC SQL SELECT ID INTO :station_id
FROM STATION
WHERE CITY = :city_name;
if (SQLCODE == 100)
{
printf("There is no station for city %s\n",city_name);
exit(0);
}
printf("For the city %s, Station ID is %ld\n",city_name,station_id);
printf("And here is the weather data:\n");
EXEC SQL DECLARE XYZ CURSOR FOR
SELECT MONTH, TEMP_F, RAIN_I
FROM STATS
WHERE ID = :station_id
ORDER BY MONTH;
EXEC SQL OPEN XYZ;
while (SQLCODE != 100) {
EXEC SQL FETCH XYZ INTO :mon, :temp, :rain;
if (SQLCODE == 100)
printf("end of list\n");
else
printf("month = %ld, temperature = %f, rainfall =
%f\n",mon,temp,rain);
}
EXEC SQL CLOSE XYZ;
exit(0);
}

Execution log:
For the city Denver, Station ID is 44
And here is the weather data:
month = 1, temperature = 27.299999, rainfall = 0.180000
month = 7, temperature = 74.800003, rainfall = 2.110000
--28--

end of list

--29--

Oracle
What is Oracle
Oracle database is a relational database management system. It is known as Oracle database,
OracleDB or simply Oracle. It is produced and marketed by Oracle Corporation.
Oracle database is the first database designed for enterprise grid computing. The enterprise
grid computing provides the most flexible and cost effective way to manage information and
applications.

Different editions of Oracle database


Following are the four editions of the Oracle database.
o Enterprise Edition: It is the most robust and secure edition. It offers all features,
including superior performance and security.
o Standard Edition: It provides the base functionality for users that do not require
Enterprise Edition's robust package.
o Express Edition (XE): It is the lightweight, free and limited Windows and Linux
edition.
o Oracle Lite: It is designed for mobile devices.

The Oracle Corporation


Oracle Corporation is the largest software company in the field of database business. Its
relational database was the first to support SQL which has since become the industry
standard.
Oracle database is one of the most trusted and widely used relational database engines. The
biggest rival of Oracle database is Microsoft's SQL Server.
History of Oracle
Oracle was originally developed by Lawrence Ellison (Larry Ellision) and his two friends and
former co-worker in 1977. Oracle DB runs on the most major platforms like Windows,
UNIX, Linux and Mac OS.

Oracle CREATE TABLE


In Oracle, CREATE TABLE statement is used to create a new table in the database.
--30--

To create a table, you have to name that table and define its columns and datatype for each
column.
Syntax:
CREATE TABLE table_name
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
column_n datatype [ NULL | NOT NULL ]
);

Parameters used in syntax


o table_name: It specifies the name of the table which you want to create.
o column1, column2, ... column n: It specifies the columns which you want to add in
the table. Every column must have a datatype. Every column should either be defined
as "NULL" or "NOT NULL". In the case, the value is left blank; it is treated as
"NULL" as default.

Oracle CREATE TABLE Example


Here we are creating a table named customers. This table doesn't have any primary key.
CREATE TABLE customers
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50)
);
This table contains three columns
o customer_id: It is the first column created as a number datatype (maximum 10 digits
in length) and cannot contain null values.
o customer_name: it is the second column created as a varchar2 datatype (50
maximum characters in length) and cannot contain null values.
o city: This is the third column created as a varchar2 datatype. It can contain null
values.

Oracle CREATE TABLE Example with primary key


CREATE TABLE customers
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50),
CONSTRAINT customers_pk PRIMARY KEY (customer_id)
);
--31--

What is Primary key


A primary key is a single field or combination of fields that contains a unique record. It must
be filled. None of the field of primary key can contain a null value. A table can have only one
primary key.
In Oracle, total number of columns cannot be more than 32.
CREATE TABLE AS Statement
The CREATE TABLE AS statement is used to create a table from an existing table by
copying the columns of existing table.
Note: If you create the table in this way, the new table will contain records from the
existing table.
Syntax:
CREATE TABLE new_table
AS (SELECT * FROM old_table);
Create Table Example: copying all columns of another table
In this example, we are creating a "newcustomers" table by copying all the columns from the
already existing table "Customers".
CREATE TABLE newcustomers
AS (SELECT * FROM customers WHERE customer_id < 5000);
Table created.
This table is named as "newcustomers" and having the same columns of "customers" table.
Create Table Example: copying selected columns of another table
Syntax:
CREATE TABLE new_table
AS (SELECT column_1, column2, ... column_n
FROM old_table);
Let's take an example:
CREATE TABLE newcustomers2
AS (SELECT customer_id, customer_name
FROM customers
WHERE customer_id < 5000);
The above example will create a new table called "newcustomers2". This table includes the
specified columns customer_id and customer_name from the customers table.
Create Table Example: copying selected columns from multiple tables
--32--

--33--

Syntax:
1.
2.
3.
4.

CREATE VIEW view_name AS


SELECT columns
FROM tables
WHERE conditions;
Parameters:
o view_name: It specifies the name of the Oracle VIEW that you want to create.
Example:
Let's take an example to create view. In this example, we are creating two tables suppliers and
orders first.
Suppliers table:

1.
2.
3.
4.
5.
6.
7.
8.

CREATE TABLE "SUPPLIERS"


( "SUPPLIER_ID" NUMBER,
"SUPPLIER_NAME" VARCHAR2(4000),
"SUPPLIER_ADDRESS" VARCHAR2(4000)
)
/
Orders table:

1.
2.
3.
4.
5.
6.

CREATE TABLE "ORDERS"


( "ORDER_NO." NUMBER,
"QUANTITY" NUMBER,
"PRICE" NUMBER
)
/
Execute the following query to create a view name sup_orders.
Create View Query:

1.
2.
3.
4.
5.
6.

CREATE VIEW sup_orders AS


SELECT suppliers.supplier_id, orders.quantity, orders.price
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = supplier_id
WHERE suppliers.supplier_name = 'VOJO';
Output:
View created.
0.21 seconds
--34--

You can now check the Oracle VIEW by this query:


1.

SELECT * FROM sup_orders;


Output:
SUPPLIER_ID QUANTITY
PRICE
3
35
70
3
26
125
3
18
100
3 rows returned in 0.00 seconds
Oracle Update VIEW
In Oracle, the CREATE OR REPLACE VIEW statement is used to modify the definition of
an Oracle VIEW without dropping it.
Syntax:

1.
2.
3.
4.

CREATE OR REPLACE VIEW view_name AS


SELECT columns
FROM table
WHERE conditions;
Example:
Execute the following query to update the definition of Oracle VIEW called sup_orders
without dropping it.

1.
2.
3.
4.
5.
6.

CREATE or REPLACE VIEW sup_orders AS


SELECT suppliers.supplier_id, orders.quantity, orders.price
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = supplier_id
WHERE suppliers.supplier_name = 'HCL';
You can now check the Oracle VIEW by this query:

1.

SELECT * FROM sup_orders;


Output:
SUPPLIER_ID QUANTITY
1
35
70
1
26
125
1
18
100
row(s) 1 - 3 of 3

PRICE

Oracle DROP VIEW


The DROP VIEW statement is used to remove or delete the VIEW completely.
--35--

Syntax
1.
2.
3.

SELECT expressions
FROM tables
WHERE conditions;
Parameters
1) expressions: It specifies the columns or calculations that you want to retrieve.
2) tables:This parameter specifies the tables that you want to retrieve records from. There
must be at least one table within the FROM clause.
3) conditions: It specifies the conditions that must be followed for selection.
Select Example: select all fields
Let's take an example to select all fields from an already created table named customers

1.
2.

SELECT *
FROM customers;
output

Select Example: select specific fields


Example
1.
2.
3.
4.
5.

SELECT age, address, salary


FROM customers
WHERE age < 25
AND salary > '20000'
ORDER BY age ASC, salary DESC;

Select Example: select fields from multiple tables (JOIN)


--36--

1.
2.
3.
4.
5.

SELECT customers.name, courses.trainer


FROM courses
INNER JOIN customers
ON courses.course_id = course_id
ORDER BY name;
output

next prev
Oracle Insert Statement
In Oracle, INSERT statement is used to add a single record or multiple records into the
table.
Syntax: (Inserting a single record using the Values keyword):
1.
2.
3.
4.

INSERT INTO table


(column1, column2, ... column_n )
VALUES
(expression1, expression2, ... expression_n );
Syntax: (Inserting multiple records using a SELECT statement):

1.
2.
3.
4.
5.

INSERT INTO table


(column1, column2, ... column_n )
SELECT expression1, expression2, ... expression_n
FROM source_table
WHERE conditions;
Parameters:
1) table: The table to insert the records into.
2) column1, column2, ... column_n:
The columns in the table to insert values.
3) expression1, expression2, ... expression_n:
--37--

The values to assign to the columns in the table. So column1 would be assigned the value
of expression1, column2 would be assigned the value of expression2, and so on.
4) source_table:
The source table when inserting data from another table.
5) conditions:
The conditions that must be met for the records to be inserted.
Oracle Insert Example: By VALUE keyword
It is the simplest way to insert elements to a database by using VALUE keyword.
See this example:
Consider here the already created suppliers table. Add a new row where the value of
supplier_id is 23 and supplier_name is Flipkart.
1.
2.
3.
4.

See this example:


INSERT INTO suppliers
(supplier_id, supplier_name)
VALUES
(50, 'Flipkart');
Output:
1 row(s) inserted.
0.02 seconds
Oracle Insert Example: By SELECT statement
This method is used for more complicated cases of insertion. In this method insertion is
done by SELECT statement. This method is used to insert multiple elements.
See this example:
In this method, we insert values to the "suppliers" table from "customers" table. Both tables
are already created with their respective columns.

1.
2.
3.
4.
5.

Execute this query:


INSERT INTO suppliers
(supplier_id, supplier_name)
SELECT age, address
FROM customers
WHERE age > 20;
Output:
4 row(s) inserted.
0.00 seconds
--38--

You can even check the number of rows that you want to insert by following statement:
1.
2.
3.

SELECT count(*)
FROM customers
WHERE age > 20;
Output:
Count(*)

Oracle INSERT ALL statement


The Oracle INSERT ALL statement is used to insert multiple rows with a single INSERT
statement. You can insert the rows into one table or multiple tables by using only one SQL
command.
Syntax
1.
2.
3.
4.
5.

INSERT ALL
INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
INTO table_name(column1, column2, column_n) VALUES (expr1, expr2, expr_n)
INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
SELECT * FROM dual;
Parameters
1) table_name: it specifies the table in which you want to insert your records.
2) column1, column2, column_n: this specifies the columns in the table to insert values.
3) expr1, expr2, expr_n: this specifies the values to assign to the columns in the table.
Oracle INSERT ALL Example
This example specifies how to insert multiple records in one table. Here we insert three rows
into the "suppliers" table.

1.
2.
3.
4.
5.

INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (20, 'Google')
INTO suppliers (supplier_id, supplier_name) VALUES (21, 'Microsoft')
INTO suppliers (supplier_id, supplier_name) VALUES (22, 'Apple')
SELECT * FROM dual;
Output
3 row(s) inserted.
0.02 seconds
This is totally equivalent to the following three INSERT statements.

--39--

1.
2.
3.

INSERT INTO suppliers (supplier_id, supplier_name) VALUES (1000, 'Google');


INSERT INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft');
INSERT INTO suppliers (supplier_id, supplier_name) VALUES (3000, 'Apple');
Oracle INSERT ALL Example: (Insert into multiple tables)
The INSERT ALL statement can also be used to insert multiple rows into more than one table
by one command only.
In the following example, we are going to insert records into the both "suppliers" and
"customers" tables.

1.
2.
3.
4.
5.

INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (30, 'Google')
INTO suppliers (supplier_id, supplier_name) VALUES (31, 'Microsoft')
INTO customers (age, name, address) VALUES (29, 'Luca Warsi', 'New York')
SELECT * FROM dual;
Output
3 row(s) inserted.
0.03 seconds
Here, total 3 rows are inserted, 2 rows are inserted into the suppliers table and one row into
the customers table.
Oracle UPDATE Statement
In Oracle, UPDATE statement is used to update the existing records in a table. You can
update a table in 2 ways.
Traditional Update table method
Syntax:

1.
2.
3.
4.
5.
6.

UPDATE table
SET column1 = expression1,
column2 = expression2,
...
column_n = expression_n
WHERE conditions;
Update Table by selecting rocords from another table
Syntax:

1.
2.
3.

UPDATE table1
SET column1 = (SELECT expression1
FROM table2
--40--

4.
5.

WHERE conditions)
WHERE conditions;
Parameters:
1) column1, column2, ... column_n:
It specifies the columns that you want to update.
2) expression1, expression2, ...expression_n:
This specifies the values to assign to the column1, column2, ?. column_n.
3) conditions:It specifies the conditions that must be fulfilled for execution of UPDATE
stateme.
Oracle Update Example: (Update single column)

1.
2.
3.

UPDATE suppliers
SET supplier_name = 'Kingfisher'
WHERE supplier_id = 2;
This example will update the supplier_name as "Kingfisher" where "supplier_id" is 2.
Oracle Update Example: (Update multiple columns)
The following example specifies how to update multiple columns in a table. In this example,
two columns supplier_name and supplier_address is updated by a single statement.

1.
2.
3.
4.

UPDATE suppliers
SET supplier_address = 'Agra',
supplier_name = 'Bata shoes'
WHERE supplier_id = 1;
Output:
1 row(s) updated.
0.06 seconds
Oracle Update Example: (By selecting records from another table)

1.
2.
3.
4.
5.

UPDATE customers
SET name = (SELECT supplier_name
FROM suppliers
WHERE suppliers.supplier_name = customers.name)
WHERE age < 25;
Output:
2 row(s) updated.
0.02 seconds
Here, the customers table is updated by fetching the data from "suppliers" table.
--41--

PL/SQL Programs

This appendix provides several PL/SQL programs to guide you in writing your
own. The sample programs illustrate several important PL/SQL concepts and
features.
This appendix discusses the following topics:

Running the Programs


Sample 1. FOR Loop
Sample 2. Cursors
Sample 3. Scoping
Sample 4. Batch Transaction Processing
Sample 5. Embedded PL/SQL
Sample 6. Calling a Stored Procedure

Running the Programs

All the sample programs in this appendix and several others throughout this guide
are available online. So, they are preceded by the following comment:
-- available online in file '<filename>'

You can find the online files in the PL/SQL demo directory. For the location of the
directory, see the Oracle installation or user's guide for your system. Here is a list
of the files and their locations in this guide:
Filename

Location in This Guide

examp1

"Understanding the Main Features of PL/SQL"

examp2

"Conditional Control"

examp3

"Iterative Control"

examp4

"Using Aliases"

examp7

"Using Cursor FOR Loops"

examp8

"Passing Parameters to a Cursor FOR Loop"

examp5

"Some Examples of Cursor Attributes"


--42--

Filename

Location in This Guide

examp6

"Some Examples of Cursor Attributes"

examp11

"Example"

examp12

"Examples"

examp13

"Examples"

examp14

"Examples"

sample1

"Sample 1. FOR Loop"

sample2

"Sample 2. Cursors"

sample3

"Sample 3. Scoping"

sample4

"Sample 4. Batch Transaction Processing"

sample5

"Sample 5. Embedded PL/SQL"

sample6

"Sample 6. Calling a Stored Procedure"

You run some samples interactively from SQL*Plus, others from Pro*C programs.
You can experiment with the samples from any Oracle account. However, the
Pro*C examples expect you to use the scott/tiger account.
Before trying the samples, you must create some database tables, then load the
tables with data. You do that by running two SQL*Plus
scripts, exampbld and examplod, which are supplied with PL/SQL. You can find
these scripts in the PL/SQL demo directory.
The first script builds the database tables processed by the sample programs. The
second script loads (or reloads) the database tables. To run the scripts, invoke
SQL*Plus, then issue the following commands:
SQL> START exampbld

--43--

...
SQL> START examplod

Sample 1. FOR Loop

The following example uses a simple FOR loop to insert ten rows into a database
table. The values of a loop index, counter variable, and either of two character
strings are inserted. Which string is inserted depends on the value of the loop
index.
Input Table

Not applicable.
PL/SQL Block
-- available online in file 'sample1'
DECLARE
x NUMBER := 100;
BEGIN
FOR i IN 1..10 LOOP
IF MOD(i,2) = 0 THEN
-- i is even
INSERT INTO temp VALUES (i, x, 'i is even');
ELSE
INSERT INTO temp VALUES (i, x, 'i is odd');
END IF;
x := x + 100;
END LOOP;
COMMIT;
END;

Output Table
SQL> SELECT * FROM temp ORDER BY col1;
NUM_COL1 NUM_COL2
-------- -------1
100
2
200
3
300
4
400
5
500
6
600
7
700
8
800
9
900
10
1000

CHAR_COL
--------i is odd
i is even
i is odd
i is even
i is odd
i is even
i is odd
i is even
i is odd
i is even

Sample 2. Cursors

The following example uses a cursor to select the five highest paid employees from
the emp table.
Input Table
SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;
ENAME

EMPNO

SAL

--44--

---------- --------- -------KING


7839
5000
SCOTT
7788
3000
FORD
7902
3000
JONES
7566
2975
BLAKE
7698
2850
CLARK
7782
2450
ALLEN
7499
1600
TURNER
7844
1500
MILLER
7934
1300
WARD
7521
1250
MARTIN
7654
1250
ADAMS
7876
1100
JAMES
7900
950
SMITH
7369
800

PL/SQL Block
-- available online in file 'sample2'
DECLARE
CURSOR c1 is
SELECT ename, empno, sal FROM emp
ORDER BY sal DESC;
-- start with highest paid employee
my_ename VARCHAR2(10);
my_empno NUMBER(4);
my_sal
NUMBER(7,2);
BEGIN
OPEN c1;
FOR i IN 1..5 LOOP
FETCH c1 INTO my_ename, my_empno, my_sal;
EXIT WHEN c1%NOTFOUND; /* in case the number requested */
/* is more than the total
*/
/* number of employees
*/
INSERT INTO temp VALUES (my_sal, my_empno, my_ename);
COMMIT;
END LOOP;
CLOSE c1;
END;

Output Table
SQL> SELECT * FROM temp ORDER BY col1 DESC;
NUM_COL1 NUM_COL2
-------- -------5000
7839
3000
7902
3000
7788
2975
7566
2850
7698

CHAR_COL
-------KING
FORD
SCOTT
JONES
BLAKE

Sample 3. Scoping

The following example illustrates block structure and scope rules. An outer block
declares two variables named x and counter and loops four times. Inside this loop
is a sub-block that also declares a variable named x. The values inserted into
the temp table show that the two x's are indeed different.
Input Table

--45--

Not applicable.
PL/SQL Block
-- available online in file 'sample3'
DECLARE
x NUMBER := 0;
counter NUMBER := 0;
BEGIN
FOR i IN 1..4 LOOP
x := x + 1000;
counter := counter + 1;
INSERT INTO temp VALUES (x, counter, 'in OUTER loop');
/* start an inner block */
DECLARE
x NUMBER := 0; -- this is a local version of x
BEGIN
FOR i IN 1..4 LOOP
x := x + 1; -- this increments the local x
counter := counter + 1;
INSERT INTO temp VALUES (x, counter, 'inner loop');
END LOOP;
END;
END LOOP;
COMMIT;
END;

Output Table
SQL> SELECT * FROM temp ORDER BY col2;
NUM_COL1 NUM_COL2
-------- -------1000
1
1
2
2
3
3
4
4
5
2000
6
1
7
2
8
3
9
4
10
3000
11
1
12
2
13
3
14
4
15
4000
16
1
17
2
18
3
19
4
20

CHAR_COL
------------in OUTER loop
inner loop
inner loop
inner loop
inner loop
in OUTER loop
inner loop
inner loop
inner loop
inner loop
in OUTER loop
inner loop
inner loop
inner loop
inner loop
in OUTER loop
inner loop
inner loop
inner loop
inner loop

Sample 4. Batch Transaction Processing

In the next example the accounts table is modified according to instructions stored
in the action table. Each row in the action table contains an account number, an
action to be taken (I, U, or D for insert, update, or delete), an amount by which to
update the account, and a time tag used to sequence the transactions.
--46--

On an insert, if the account already exists, an update is done instead. On an update,


if the account does not exist, it is created by an insert. On a delete, if the row does
not exist, no action is taken.

--47--

Input Tables
SQL> SELECT * FROM accounts ORDER BY account_id;
ACCOUNT_ID
BAL
---------- ------1
1000
2
2000
3
1500
4
6500
5
500
SQL> SELECT * FROM action ORDER BY time_tag;
ACCOUNT_ID
---------3
6
5
7
1
9
10

O NEW_VALUE STATUS
- ---------- -------------------u
599
i
20099
d
u
1599
i
399
d
x

TIME_TAG
--------18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88

PL/SQL Block
-- available online in file 'sample4'
DECLARE
CURSOR c1 IS
SELECT account_id, oper_type, new_value FROM action
ORDER BY time_tag
FOR UPDATE OF status;
BEGIN
FOR acct IN c1 LOOP -- process each row one at a time
acct.oper_type := upper(acct.oper_type);
/*----------------------------------------*/
/* Process an UPDATE. If the account to */
/* be updated doesn't exist, create a new */
/* account.
*/
/*----------------------------------------*/
IF acct.oper_type = 'U' THEN
UPDATE accounts SET bal = acct.new_value
WHERE account_id = acct.account_id;
IF SQL%NOTFOUND THEN -- account didn't exist. Create it.
INSERT INTO accounts
VALUES (acct.account_id, acct.new_value);
UPDATE action SET status =
'Update: ID not found. Value inserted.'
WHERE CURRENT OF c1;
ELSE
UPDATE action SET status = 'Update: Success.'
WHERE CURRENT OF c1;
END IF;
/*--------------------------------------------*/
/* Process an INSERT. If the account already */
/* exists, do an update of the account
*/
/* instead.
*/
/*--------------------------------------------*/

--48--

ELSIF acct.oper_type = 'I' THEN


BEGIN
INSERT INTO accounts
VALUES (acct.account_id, acct.new_value);
UPDATE action set status = 'Insert: Success.'
WHERE CURRENT OF c1;
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
-- account already exists
UPDATE accounts SET bal = acct.new_value
WHERE account_id = acct.account_id;
UPDATE action SET status =
'Insert: Acct exists. Updated instead.'
WHERE CURRENT OF c1;
END;
/*--------------------------------------------*/
/* Process a DELETE. If the account doesn't */
/* exist, set the status field to say that
*/
/* the account wasn't found.
*/
/*--------------------------------------------*/
ELSIF acct.oper_type = 'D' THEN
DELETE FROM accounts
WHERE account_id = acct.account_id;
IF SQL%NOTFOUND THEN
-- account didn't exist.
UPDATE action SET status = 'Delete: ID not found.'
WHERE CURRENT OF c1;
ELSE
UPDATE action SET status = 'Delete: Success.'
WHERE CURRENT OF c1;
END IF;
/*--------------------------------------------*/
/* The requested operation is invalid.
*/
/*--------------------------------------------*/
ELSE -- oper_type is invalid
UPDATE action SET status =
'Invalid operation. No action taken.'
WHERE CURRENT OF c1;
END IF;
END LOOP;
COMMIT;
END;

Output Tables
SQL> SELECT * FROM accounts ORDER BY account_id;
ACCOUNT_ID
BAL
---------- -------1
399
2
2000
3
599
4
6500
6
20099
7
1599
SQL> SELECT * FROM action ORDER BY time_tag;
ACCOUNT_ID

NEW_VALUE STATUS

TIME_TAG

--49--

---------3
6
5
7
1
9
10

- ---------- --------------------u
599 Update: Success.
i
20099 Insert: Success.
d
Delete: Success.
u
1599 Update: ID not found.
Value inserted.
i
399 Insert: Acct exists.
Updated instead.
d
Delete: ID not found.
x
Invalid operation.
No action taken.

--------18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88
18-NOV-88

Sample 5. Embedded PL/SQL

The following example shows how you can embed PL/SQL in a high-level host
language such as C and demonstrates how a banking debit transaction might be
done.
Input Table
SQL> SELECT * FROM accounts ORDER BY account_id;
ACCOUNT_ID
BAL
---------- -------1
1000
2
2000
3
1500
4
6500
5
500

PL/SQL Block in a C Program


/* available online in file 'sample5' */
#include <stdio.h>
char
buf[20];
EXEC SQL BEGIN DECLARE SECTION;
int
acct;
double debit;
double new_bal;
VARCHAR status[65];
VARCHAR uid[20];
VARCHAR pwd[20];
EXEC SQL END DECLARE SECTION;
EXEC SQL INCLUDE SQLCA;
main()
{
extern double atof();
strcpy (uid.arr,"scott");
uid.len=strlen(uid.arr);
strcpy (pwd.arr,"tiger");
pwd.len=strlen(pwd.arr);
printf("\n\n\tEmbedded PL/SQL Debit Transaction Demo\n\n");
printf("Trying to connect...");
EXEC SQL WHENEVER SQLERROR GOTO errprint;
EXEC SQL CONNECT :uid IDENTIFIED BY :pwd;
printf(" connected.\n");
for (;;)
/* Loop infinitely */

--50--

printf("\n** Debit which account number? (-1 to end) ");


gets(buf);
acct = atoi(buf);
if (acct == -1) /* Need to disconnect from Oracle */
{
/* and exit loop if account is -1 */
EXEC SQL COMMIT RELEASE;
exit(0);
}
printf("
What is the debit amount? ");
gets(buf);
debit = atof(buf);
/* ---------------------------------- */
/* ----- Begin the PL/SQL block ----- */
/* ---------------------------------- */
EXEC SQL EXECUTE
DECLARE
insufficient_funds EXCEPTION;
old_bal
NUMBER;
min_bal
CONSTANT NUMBER := 500;
BEGIN
SELECT bal INTO old_bal FROM accounts
WHERE account_id = :acct;
-- If the account doesn't exist, the NO_DATA_FOUND
-- exception will be automatically raised.
:new_bal := old_bal - :debit;
IF :new_bal >= min_bal THEN
UPDATE accounts SET bal = :new_bal
WHERE account_id = :acct;
INSERT INTO journal
VALUES (:acct, 'Debit', :debit, SYSDATE);
:status := 'Transaction completed.';
ELSE
RAISE insufficient_funds;
END IF;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
:status := 'Account not found.';
:new_bal := -1;
WHEN insufficient_funds THEN
:status := 'Insufficient funds.';
:new_bal := old_bal;
WHEN OTHERS THEN
ROLLBACK;
:status := 'Error: ' || SQLERRM(SQLCODE);
:new_bal := -1;
END;
END-EXEC;
/* -------------------------------- */
/* ----- End the PL/SQL block ----- */
/* -------------------------------- */
status.arr[status.len] = '\0';
printf("\n\n
Status:
if (new_bal >= 0)

/* null-terminate */
/* the string
*/
%s\n", status.arr);

--51--

printf("
Balance is now:
/* End of loop */

$%.2f\n", new_bal);

errprint:
EXEC SQL WHENEVER SQLERROR CONTINUE;
printf("\n\n>>>>> Error during execution:\n");
printf("%s\n",sqlca.sqlerrm.sqlerrmc);
EXEC SQL ROLLBACK RELEASE;
exit(1);
}

Interactive Session
Embedded PL/SQL Debit Transaction Demo
Trying to connect... connected.
** Debit which account number? (-1 to end) 1
What is the debit amount? 300
Status: Transaction completed.
Balance is now: $700.00
** Debit which account number? (-1 to end) 1
What is the debit amount? 900
Status: Insufficient funds.
Balance is now: $700.00
** Debit which account number? (-1 to end) 2
What is the debit amount? 500
Status: Transaction completed.
Balance is now: $1500.00
** Debit which account number? (-1 to end) 2
What is the debit amount? 100
Status: Transaction completed.
Balance is now: $1400.00
** Debit which account number? (-1 to end) 99
What is the debit amount? 100
Status:

Account not found.

** Debit which account number? (-1 to end) -1

Output Tables
SQL> SELECT * FROM accounts ORDER BY account_id;
ACCOUNT_ID
BAL
---------- -----1
700
2
1400
3
1500
4
6500
5
500
SQL> SELECT * FROM journal ORDER BY date_tag;
ACCOUNT_ID
----------

ACTION
--------------------

AMOUNT
---------

--52--

DATE_TAG
---------

1
2
2

Debit
Debit
Debit

300
500
100

28-NOV-88
28-NOV-88
28-NOV-88

Sample 6. Calling a Stored Procedure

This Pro*C program connects to Oracle, prompts the user for a department
number, then calls procedure get_employees, which is stored in package personnel.
The procedure declares three index-by tables as OUT formal parameters, then
fetches a batch of employee data into the index-by tables. The matching actual
parameters are host arrays.
When the procedure finishes, it automatically assigns all row values in the indexby tables to corresponding elements in the host arrays. The program calls the
procedure repeatedly, displaying each batch of employee data, until no more data is
found.
Input Table
SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;
ENAME
EMPNO
SAL
---------- --------- -------KING
7839
5000
SCOTT
7788
3000
FORD
7902
3000
JONES
7566
2975
BLAKE
7698
2850
CLARK
7782
2450
ALLEN
7499
1600
TURNER
7844
1500
MILLER
7934
1300
WARD
7521
1250
MARTIN
7654
1250
ADAMS
7876
1100
JAMES
7900
950
SMITH
7369
800

Stored Procedure
/* available online in file 'sample6' */
#include <stdio.h>
#include <string.h>
typedef char asciz;
EXEC SQL BEGIN DECLARE SECTION;
/* Define type for null-terminated strings. */
EXEC SQL TYPE asciz IS STRING(20);
asciz username[20];
asciz password[20];
int
dept_no;
/* which department to query */
char
emp_name[10][21];
char
job[10][21];
EXEC SQL VAR emp_name is STRING (21);
EXEC SQL VAR job is STRING (21);
float salary[10];

--53--

int
done_flag;
int
array_size;
int
num_ret;
/* number of rows returned */
int
SQLCODE;
EXEC SQL END DECLARE SECTION;
EXEC SQL INCLUDE sqlca;
int print_rows();
int sqlerror();

/* produces program output


*/
/* handles unrecoverable errors */

main()
{
int i;
/* Connect to Oracle. */
strcpy(username, "SCOTT");
strcpy(password, "TIGER");
EXEC SQL WHENEVER SQLERROR DO sqlerror();
EXEC SQL CONNECT :username IDENTIFIED BY :password;
printf("\nConnected to Oracle as user: %s\n\n", username);
printf("Enter department number: ");
scanf("%d", &dept_no);
fflush(stdin);
/* Print column headers. */
printf("\n\n");
printf("%-10.10s%-10.10s%s\n", "Employee", "Job", "Salary");
printf("%-10.10s%-10.10s%s\n", "--------", "---", "------");
/* Set the array size. */
array_size = 10;
done_flag = 0;
num_ret = 0;
/* Array fetch loop - ends when NOT FOUND becomes true. */
for (;;)
{
EXEC SQL EXECUTE
BEGIN personnel.get_employees
(:dept_no, :array_size, :num_ret, :done_flag,
:emp_name, :job, :salary);
END;
END-EXEC;
print_rows(num_ret);
if (done_flag)
break;
}

/* Disconnect from Oracle. */


EXEC SQL COMMIT WORK RELEASE;
exit(0);

print_rows(n)
int n;

--54--

int i;
if (n == 0)
{
printf("No rows retrieved.\n");
return;
}
for (i = 0; i < n; i++)
printf("%10.10s%10.10s%6.2f\n",
emp_name[i], job[i], salary[i]);

}
sqlerror()
{
EXEC SQL WHENEVER SQLERROR CONTINUE;
printf("\nOracle error detected:");
printf("\n% .70s \n", sqlca.sqlerrm.sqlerrmc);
EXEC SQL ROLLBACK WORK RELEASE;
exit(1);
}

Interactive Session
Connected to Oracle as user: SCOTT
Enter department number: 20
Employee
-------SMITH
JONES
SCOTT
ADAMS
FORD

Job
--CLERK
MANAGER
ANALYST
CLERK
ANALYST

Salary
-----800.00
2975.00
3000.00
1100.00
3000.00

--55--

You might also like