Download RDBMS - E

Document related concepts

Tandem Computers wikipedia , lookup

Microsoft Access wikipedia , lookup

Oracle Database wikipedia , lookup

Relational algebra wikipedia , lookup

Database wikipedia , lookup

Functional Database Model wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Ingres (database) wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Clusterpoint wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Null (SQL) wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Join (SQL) wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Database model wikipedia , lookup

SQL wikipedia , lookup

Relational model wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
UNIT – I
Data base Management System and RDBMS – Normalization – Oracle terminology – Database
Connection – Creating tables – The Basics of SQL : SQL Grammar.
What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and
for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft
Access.A Relational database management system (RDBMS) is a database management system
(DBMS) that is based on the relational model as introduced by E. F. Codd.
Creating tables
The data in RDBMS is stored in database objects called tables. The table is a collection
of related data entries and it consists of columns and rows.
Remember, a table is the most common and simplest form of data storage in a relational
database. Following is the example of a CUSTOMERS table:
The create table statement is used to create a new table. Here is the format of a simple create
table statement:
create table "tablename"
("column1" "data type",
"column2" "data type",
"column3" "data type");
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota
| 2000.00 |
+----+----------+-----+-----------+----------+
The table and column names must start with a letter and can be followed by letters, numbers, or
underscores - not to exceed a total of 30 characters in length. Do not use any SQL reserved
keywords as names for tables or column names (such as "select", "create", "insert", etc).
Data types specify what the type of data can be for that particular column. If a column called
"Last_Name", is to be used to hold names, then that particular column should have a "varchar"
(variable-length character) data type.
Here are the most common Data types:
char(size)
Fixed-length character string. Size is specified in parenthesis. Max 255 bytes.
varchar(size)
Variable-length character string. Max size is specified in parenthesis.
number(size)
Number value with a max number of column digits specified in parenthesis.
date
Date value
number(size,d)
Number value with a maximum number of digits of "size" total, with a maximum number
of "d" digits to the right of the decimal.
What is field?
Every table is broken up into smaller entities called fields. The fields in the
CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific information about every record
in the table.
What is record, or row?
A record, also called a row of data, is each individual entry that exists in a table. For example
there are 3 records in the above CUSTOMERS table. Following is a single row of data or record
in the CUSTOMERS table:
+----+----------+-----+-----------+----------+
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
A record is a horizontal entity in a table.
What is column?
A column is a vertical entity in a table that contains all information associated with a specific
field in a table.
For example, a column in the CUSTOMERS table is ADDRESS which represents location
description and would consist of the following:
+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| +----+------+
What is NULL value?
A NULL value in a table is a value in a field that appears to be blank which means A field with a
NULL value is a field with no value.
It is very important to understand that a NULL value is different than a zero value or a field that
contains spaces. A field with a NULL value is one that has been left blank during record
creation.
SQL Constraints:
Constraints are the rules enforced on data columns on table. These are used to limit the type of
data that can go into a table. This ensures the accuracy and reliability of the data in the database.
Contraints could be column level or table level. Column level constraints are applied only to one
column where as table level constraints are applied to the whole table.
Following are commonly used constraints available in SQL:







NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint : Provides a default value for a column when none is specified.
UNIQUE Constraint: Ensures that all values in a column are different.
PRIMARY Key: Uniquely identified each rows/records in a database table.
FOREIGN Key: Uniquely identified a rows/records in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy
certain conditions.
INDEX: Use to create and retrieve data from the database very quickly.
Data Integrity:
The following categories of the data integrity exist with each RDBMS:




Entity Integrity : There are no duplicate rows in a table.
Domain Integrity : Enforces valid entries for a given column by restricting the type, the
format, or the range of values.
Referential integrity : Rows cannot be deleted, which are used by other records.
User-Defined Integrity : Enforces some specific business rules that do not fall into
entity, domain, or referential integrity.
Database Normalization
Database normalization is the process of efficiently organizing data in a database. There are two
reasons of the normalization process:
1. Eliminating redundant data, for example, storing the same data in more than one tables.
2. Ensuring data dependencies make sense.
Both of these are worthy goals as they reduce the amount of space a database consumes and
ensure that data is logically stored. Normalization consists of a series of guidelines that help
guide you in creating a good database structure.
Normalization guidelines are divided into normal forms; think of form as the format or the way a
database structure is laid out. The aim of normal forms is to organize the database structure so
that it complies with the rules of first normal form, then second normal form, and finally third
normal form.
It's your choice to take it further and go to fourth normal form, fifth normal form, and so on, but
generally speaking, third normal form is enough.
1. First Normal Form (1NF)
2. Second Normal Form (2NF)
ORACLE
3. Third
Normal
Form
(3NF)
It is very large and multi-user database management system. Oracle is a relational database
management system developed by 'Oracle Corporation'.
Oracle works to efficiently manage its resource, a database of information, among the multiple
clients requesting and sending data in the network.
It is an excellent database server choice for client/server computing. Oracle supports all major
operating systems for both clients and servers, including MSDOS, NetWare, UnixWare, OS/2
and most UNIX flavors.
History:
Oracle began in 1977 and celebrating its 32 wonderful years in the industry (from 1977 to 2009).








1977 - Larry Ellison, Bob Miner and Ed Oates founded Software Development
Laboratories to undertake development work.
1979 - Version 2.0 of Oracle was released and it became first commercial relational
database and first SQL database. The company changed its name to Relational Software
Inc. (RSI).
1981 - RSI started developing tools for Oracle.
1982 - RSI was renamed to Oracle Corporation.
1983 - Oracle released version 3.0, rewritten in C language and ran on multiple
platforms.
1984 - Oracle version 4.0 was released. It contained features like concurrency control multi-version read consistency etc.
1985 - Oracle version 4.0 was released. It contained features like concurrency control multi-version read consistency etc.
2007 - Oracle has released Oracle11g. The new version focused on better partitioning,
easy migration etc.
Features:






Concurrency
Concurrency
Read Consistency
Locking
Mechanisms
Quiesce Database
Portability






Selfmanaging
database
SQL*Plus
ASM
Scheduler
Resource Manager
Data Warehousing







Materialized views
Bitmap indexes
Table compression
Parallel Execution
Analytic SQL
Data mining
Partitioning
SQL BASICS:
SQL is a standard language for accessing and manipulating databases.



SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL is an ANSI (American National Standards Institute) standard
What Can SQL do?










SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and viewsr
ADVANTAGES OF DBMS:
Scalable: Describes the ability of a system to adapt to different amounts of data and numbers of users
while maintaining the same performance. In a scalable system those can be increased through the
extension of the computing capacity without any programming work.
Expandability: New applications or other additions like new user interfaces can be realised without
interfering with already working applications.
Standardised and Combined Features: Features for data definition, data organisation and data integrity
can be standardised and combined.
More Efficient System Operation and Development: It is possible to have more efficient features for
maintaining system and further developing of the system.
Access Control: Access to a database or parts of it (like single tables) can be controlled or restricted for
each user but also for user groups.
Recovery and Back-up: A database management system has features which allow to recover data sets,
for example, after a failed transaction or a system crash. Additionally, a back-up from the whole system
can be made to store in a save place.
Quicker Application Development: As all the data handling is 'delegated' to the database managment
system it is possible to develop new applications quick and flexible.
Disadvantages of dbms
1. Increased costs.
Database systems require sophisticated hardware and software and highly skilled personnel.
The cost of maintaining the hardware, software, and personnel required to operate and manage
a database system can be substantial. Training, licensing, and regulation compliance costs are
often overlooked when database systems are implemented.
2. Management complexity.
Database systems interface with many different technologies and have a significant impact on a
company’s resources and culture. The changes introduced by the adoption of a database
system must be properly managed to ensure that they help advance the company’s objectives.
Given the fact that database systems hold crucial company data that are accessed from multiple
sources, security issues must be assessed constantly.
3. Maintaining currency.
To maximize the efficiency of the database system, you must keep your system current.
Therefore, you must perform frequent updates and apply the latest patches and security
measures to all components. Because database technology advances rapidly, personnel
training costs tend to be significant. Vendor dependence. Given the heavy investment in
technology and personnel training, companies might be reluctant to change database vendors.
As a consequence, vendors are less likely to offer pricing point advantages to existing
customers, and those customers might be limited in their choice of database system
components.
4. Frequent upgrade/replacement cycles.
DBMS vendors frequently upgrade their products by adding new functionality. Such new
features often come bundled in new upgrade versions of the software. Some of these versions
require hardware upgrades. Not only do the upgrades themselves cost money, but it also costs
money to train database users and administrators to properly use and manage the new
features.
DBMS Keys
A key is an attribute (also known as column or field) or a combination of attribute that is
used to identify records. Sometimes we might have to retrieve data from more than one
table, in those cases we require to join tables with the help of keys. The purpose of the key
is to bind data together across tables without repeating all of the data in every table.
The various types of key with e.g. in SQL are mentioned below, (For examples let suppose
we have an Employee Table with attributes ‘ID’ , ‘Name’ ,’Address’ , ‘Department_ID’
,’Salary’)
(I) Super Key – An attribute or a combination of attribute that is used to identify the
records uniquely is known as Super Key. A table can have many Super Keys.
E.g. of Super Key
1 ID
2 ID, Name
3 ID, Address
4 ID, Department_ID
5 ID, Salary
6 Name, Address
7 Name, Address, Department_ID ………… So on as any combination which can identify the
records uniquely will be a Super Key.
(II) Candidate Key – It can be defined as minimal Super Key or irreducible Super Key.
In other words an attribute or a combination of attribute that identifies the record uniquely
but none of its proper subsets can identify the records uniquely.
E.g. of Candidate Key
1 Code
2 Name, Address
For above table we have only two Candidate Keys (i.e. Irreducible Super Key) used to
identify the records from the table uniquely. Code Key can identify the record uniquely and
similarly combination of Name and Address can identify the record uniquely, but neither
Name nor Address can be used to identify the records uniquely as it might be possible that
we have two employees with similar name or two employees from the same house.
(III) Primary Key – A Candidate Key that is used by the database designer for unique
identification of each row in a table is known as Primary Key. A Primary Key can consist of
one or more attributes of a table.
E.g. of Primary Key - Database designer can use one of the Candidate Key as a Primary
Key. In this case we have “Code” and “Name, Address” as Candidate Key, we will consider
“Code” Key as a Primary Key as the other key is the combination of more than one
attribute.
(IV) Foreign Key – A foreign key is an attribute or combination of attribute in one base
table that points to the candidate key (generally it is the primary key) of another table. The
purpose of the foreign key is to ensure referential integrity of the data i.e. only values that
are supposed to appear in the database are permitted.
E.g. of Foreign Key – Let consider we have another table i.e. Department Table with
Attributes “Department_ID”, “Department_Name”, “Manager_ID”, ”Location_ID” with
Department_ID as an Primary Key. Now the Department_ID attribute of Employee Table
(dependent or child table) can be defined as the Foreign Key as it can reference to the
Department_ID attribute of the Departments table (the referenced or parent table), a
Foreign Key value must match an existing value in the parent table or be NULL.
(V) Composite Key – If we use multiple attributes to create a Primary Key then that
Primary Key is called Composite Key (also called a Compound Key or Concatenated Key).
E.g. of Composite Key, if we have used “Name, Address” as a Primary Key then it will be
our Composite Key.
(VI) Alternate Key – Alternate Key can be any of the Candidate Keys except for the
Primary Key.
E.g. of Alternate Key is “Name, Address” as it is the only other Candidate Key which is not
a Primary Key.
(VII) Secondary Key – The attributes that are not even the Super Key but can be still
used for identification of records (not unique) are known as Secondary Key.
E.g. of Secondary Key can be Name, Address, Salary, Department_ID etc. as they can
identify the records but they might not be unique.
UNIT – II
Data manipulation – data types – Insertions , updation and deletion operation – SELECT Command –
Where clause modifying structure – views – Sequences, SQL & Plus commands.
Data Types
The following is a list of general SQL datatypes that may not be supported by all relational
databases.
Data Type
Syntax
Explanation (if applicable)
integer
integer
smallint
smallint
numeric
numeric(p,s)
Where p is a precision value; s is a scale value. For example,
numeric(6,2) is a number that has 4 digits before the decimal
and 2 digits after the decimal.
decimal
decimal(p,s)
Where p is a precision value; s is a scale value.
real
real
Single-precision floating point number
double precision
double precision Double-precision floating point number
float
float(p)
Where p is a precision value.
character
char(x)
Where x is the number of characters to store. This data type
is space padded to fill the number of characters specified.
character varying
varchar2(x)
Where x is the number of characters to store. This data type
does NOT space pad.
bit
bit(x)
Where x is the number of bits to store.
bit varying
bit varying(x)
Where x is the number of bits to store. The length can vary
up to x.
date
date
Stores year, month, and day values.
time
time
Stores the hour, minute, and second values.
timestamp
timestamp
Stores year, month, day, hour, minute, and second values.
time with time
zone
time with time
zone
Exactly the same as time, but also stores an offset from UTC
of the time specified.
timestamp with
time zone
timestamp with
time zone
Exactly the same as timestamp, but also stores an offset from
UTC of the time specified.
year-month interval
Contains a year value, a month value, or both.
day-time interval
Contains a day value, an hour value, a minute value, and/or a
second value.
Insertions , updation and deletion operation
The INSERT statement is used to insert new records in a table.
The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their
values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
SQL INSERT INTO Example
We have the following "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
Now we want to insert a new row in the "Persons" table.
We use the following SQL statement:
INSERT INTO Persons
VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
The "Persons" table will now look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Johan
Bakken 2
Stavanger
Insert Data Only in Specified Columns
It is also possible to only add data in specific columns.
The following SQL statement will add a new row, but only add data in the "P_Id", "LastName"
and the "FirstName" columns:
INSERT INTO Persons (P_Id, LastName, FirstName)
VALUES (5, 'Tjessem', 'Jakob')
The "Persons" table will now look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Johan
Bakken 2
Stavanger
5
Tjessem
Jakob
The UPDATE Statement
The UPDATE statement is used to update records in a table.
The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
SQL UPDATE Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Johan
5
Tjessem
Jakob
Bakken 2
Stavanger
Now we want to update the person "Tjessem, Jakob" in the "Persons" table.
We use the following SQL statement:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'
The "Persons" table will now look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
Stavanger
4
Nilsen
Johan
Bakken 2
Stavanger
5
Tjessem
Jakob
Nissestien 67
Sandnes
SQL UPDATE Warning
Be careful when updating records. If we had omitted the WHERE clause in the example above,
like this:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
The "Persons" table would have looked like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Nissestien 67
Sandnes
2
Svendson
Tove
Nissestien 67
Sandnes
3
Pettersen
Kari
Nissestien 67
Sandnes
4
Nilsen
Johan
Nissestien 67
Sandnes
5
Tjessem
Jakob
Nissestien 67
Sandnes
The DELETE statement is used to delete records in a table.
The DELETE Statement
The DELETE statement is used to delete rows in a table.
SQL DELETE Syntax
DELETE FROM table_name
WHERE some_column=some_value
SQL DELETE Example
The "Persons" table:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn
Sandnes
2
Svendson
Tove
Borgvn
Sandnes
3
Pettersen
Kari
Storgt
Stavanger
4
Nilsen
Johan
Bakken
Stavanger
5
Tjessem
Jakob
Nissestien
Sandnes
Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.
We use the following SQL statement:
DELETE FROM Persons
WHERE LastName='Tjessem' AND FirstName='Jakob'
The "Persons" table will now look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn
Sandnes
2
Svendson
Tove
Borgvn
Sandnes
3
Pettersen
Kari
Storgt
Stavanger
4
Nilsen
Johan
Bakken2
Stavanger
Delete All Rows
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
DELETE FROM table_name
or
DELETE * FROM table_name
SQL WHERE Clause modifying structures
The WHERE clause is used to filter records.
The WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
WHERE Clause Example
The "Persons" table:
P_Id LastName FirstName Address
1
Hansen
Ola
2
Svendson Tove
City
Timoteivn 10 Sandnes
Borgvn 23
Sandnes
3
Pettersen Kari
Storgt 20
Stavanger
Now we want to select only the persons living in the city "Sandnes" from the table above.
We use the following SELECT statement:
SELECT * FROM Persons
WHERE City='Sandnes'
The result-set will look like this:
P_Id
LastName
FirstName
Address
City
1
Hansen
Ola
Timoteivn 10
Sandnes
2
Svendson
Tove
Borgvn 23
Sandnes
Quotes Around Text Fields
SQL uses single quotes around text values (most database systems will also accept double
quotes).
However, numeric values should not be enclosed in quotes.
For text values:
This is correct:
SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove
For numeric values:
This is correct:
SELECT * FROM Persons WHERE Year=1965
This is wrong:
SELECT * FROM Persons WHERE Year='1965'
Operators Allowed in the WHERE Clause
With the WHERE clause, the following operators can be used:
Operator
Description
=
Equal
<>
Not equal
>
Greater than
<
Less than
>=
Greater than or equal
<=
Less than or equal
BETWEEN
Between an inclusive range
LIKE
Search for a pattern
IN
To specify multiple possible values for a column
Note: In some versions of SQL the < > operator may be written as ! =
VIEWS AND SEQUENCES.
REFER FOURTH UNIT.
SQL PLUS COMMANDS.
SQL*Plus commands
The following commands can be issued in SQL*Plus (in addition to the
standard SQL commands.)
@pathname
Run (START) an SQL Script
@MyScript.sql parameter1 parameter2
parameter3 .
In the SQL-Script, refer to the parameters
as &1, &2, and &3.
@@pathname
Run (START) an SQL Script.
@@ will call a sub-script from the same
directory as the main script.
@variable
A substitution variable
ACCEPT
User input
ACC[EPT]
variable [NUM[BER]|CHAR|DATE] [FORMAT
format]
[DEFAULT default] [PROMPT
text|NOPROMPT] [HIDE]
APPEND
Add text to the end of the current line in
the buffer.
A[PPEND] text_to_add
BREAK
Specify where and how formatting will
change.
BREAK ON {column|expr|ROW|REPORT} action
BTITLE
Place and format a title at the bottom of
each page.
BTITLE printspec [text|variable]
BTITLE [OFF|ON]
CHANGE
Change text on the current line.
C /oldval/newval
CLEAR
Clear the SQL*Plus screen and the screen
buffer.
CLEAR
{BREAKS|BUFFER|COLUMNS|COMPUTES|SCREEN|SQL TIMING}
COLUMN
Change display width of a column.
COMPUTE
Calculate and display totals.
CONNECT
Connect to a database as a specified user.
connect username/password@SID
COPY
Copy data from a query into a table (local
or remote)
DEFINE
Display a user variable ,DEFINE varName
DEL
Delete the current line in the SQL buffer
DESC[RIBE] Describe a table, column, view, synonym,
function .procedure, package or package contents.
EDIT
Load the SQL*Plus buffer into an editor.
By default, saves the file to AFIEDT.BUF
EXECUTE
Run a single PLSQL statement
EXEC :answer := EMP_PAY.BONUS('SMITH')
EXIT [n]
Commit, logoff and exit (n = error code)
EXIT SQL.SQLCODE
GET file
Retrieve a previously stored command file
HOST
Execute a host operating system command
HOST CD scripts
Edit sql buffer - add line(s) to the
INPUT
buffer
LIST n m
Edit sql buffer - display buffer lines n
to m .For all lines - specify m as LAST
PAUSE message
Wait for the user to hit RETURN
RUN
Execute (or re-execute) commands in the
SQL*Plus buffer .Lists the commands before running
RUNFORM
Run a SQL*Forms application
SAVE file
Save the contents of the SQL*Plus buffer
in a command file
SET
Display or change SQL*Plus settings
SHOW
List the value of a system variable (see
PRINT)
SHUTDOWN [ABORT|IMMEDIATE|NORMAL|TRANSACTIONAL]
SPOOL file Store query results in file
SPOOL OFF
STA[RT]
STARTUP
TIMING
STOP}
TTITLE
Turn off spooling
SPOOL OUT sends file to printer
Run an SQL Script (see @)
[NoMOUNT|MOUNT|OPEN]
Record timing data TIMING {START | SHOW |
Define a page title.
Difference b/w sql and sql plus refer Xerox.
Unit 3:
Manipulating strings – Dealing with Dates - handling Numbers – defining table and
Column constraints - Table Indexes.
Strings manipulation.
SQL string functions are used primarily for string manipulation. The following table
details the important string functions:
Name
Description
ASCII()
Return numeric value of left-most character
BIT_LENGTH()
Return length of argument in bits
CHAR_LENGTH()
Return number of characters in argument
CHAR()
Return the character for each integer passed
CONCAT()
Return concatenated string
CONV()
Convert numbers between different number bases
FORMAT()
Return a number formatted to specified number of
decimal places
INSERT()
Insert a substring at the specified position up to the
specified number of characters
INSTR()
Return the index of the first occurrence of substring
LCASE()
Synonym for LOWER()
LEFT()
Return the leftmost number of characters as
specified
LENGTH()
Return the length of a string in bytes
LOAD_FILE()
Load the named file
LOWER()
Return the argument in lowercase
MID()
Return a substring starting from the specified
position
OCT()
Return a string representation of the octal argument
POSITION()
A synonym for LOCATE()
QUOTE()
Escape the argument for use in an SQL statement
REPEAT()
Repeat a string the specified number of times
REPLACE()
Replace occurrences of a specified string
REVERSE()
Reverse the characters in a string
RIGHT()
Return the specified rightmost number of characters
SOUNDEX()
Return a soundex string
SOUNDS LIKE
Compare sounds
SPACE()
Return a string of the specified number of spaces
STRCMP()
Compare two strings
TRIM()
Remove leading and trailing spaces
UCASE()
Synonym for UPPER()
UNHEX()
Convert each pair of hexadecimal digits to a
character
UPPER()
Convert to uppercase
Date function:

Date storage
Oracle stores dates in an internal numeric format, representing:





Century
Year
Month
Day
Hours, Minutes, Seconds .
operators that used on date type data




e.g.
date + number
date – number
date – date
date +number/24
Select hiredate, hiredate+7, hiredate-7
From EMP Where hiredate Like ‘%JUN%’
MONTHS_BETWEEN(date1,date2)
Select MONTHS_BETWEEN (SYSDATE,hiredate),
MONTHS_BETWEEN(‘01-JAN-94’,’05-NOV-98’)
From table name
CURRENT_DATE ( )
Returns the current date.
CURRENT_TIME ()
Returns the current local time.
EXTRACT (extract-field FROM extractsource)
Returns the extract-field portion of the extractsource. The extract-source argument is a
datetime or interval expression.
CURRENT_TIMESTAMP ()
Returns the current local date and local time
as a timestamp value.
CURDATE ( )
HOUR (time_exp)
Returns the hour based on the hour field in
time_exp as an integer value in the range of
0-23.
Returns the current date.
CURTIME ( )
Returns the current local time.
DAYNAME (date_exp)
Returns a character string containing the data
source/specific name of the day (for example,
Sunday through Saturday).
DAYOFMONTH (date_exp)
Returns the day of the month based on the
month field in date_exp as an integer value in
the range of 1-31.
DAYOFWEEK (date_exp)
Returns the day of the week based on the
week field in date_exp as an integer value in
the range of 1-7, where 1 represents Sunday.
MINUTE (time_exp)
Returns the minute based on the minute field
in time_exp as an integer value in the range
of 0-59.
MONTH (date_exp)
Returns the month based on the month field
in date_exp as an integer value in the range
of 1-12.
MONTHNAME(date_exp)
Returns a character string containing the
data source/specific name of the month (for
example, January through December).
Currently only supports English locale.
DAYOFYEAR(date_exp)
Returns the day of the year based on the year
field in date_exp as an integer value in the
range of 1-366.
NOW ( )
Returns current date and time as a timestamp
value.
QUARTER(date_exp)
Returns the quarter in date_exp as an integer
value in the range of 1-4, where 1 represents
January 1 through March 31.
SECOND (time_exp)
Returns the second based on the second field
in time_exp as an integer value in the range
of 0-59.
TIMESTAMPADD (interval, integer_exp, timestamp_exp)
Returns a timestamp offset by the specified interval.
Interval can be one of the following values
SQL_TSI_FRAC_SECOND (in billionths of a second)
SQL_TSI_SECOND
SQL_TSI_MINUTE
SQL_TSI_HOUR
SQL_TSI_DAY
SQL_TSI_WEEK
SQL_TSI_MONTH
SQL_TSI_QUARTER
SQL_TSI_YEAR
Example:
SELECT timestampadd(SQL_TSI_HOUR, 3, {ts “1998-01-11 10:00:00”});
Returns: 1998-01-01 13:00:00
Example:
SELECT timestampadd(SQL_TSI_DAY, -3, {ts “1998-01-11 10:00:00”});
Returns: 1998-01-08 10:00:00
HANDLING NUMBERS
ABS(X)
The ABS() function returns the absolute value of X. Consider the following example:
SQL> SELECT ABS(2);
| ABS(2)
| 2
1 row in set (0.00 sec)
|
|
ACOS(X)
This function returns the arccosine of X. The value of X must range between .1 and 1 or NULL
will be returned. Consider the following example:
SQL> SELECT ACOS(1);
+---------------------------------------------------------+
| ACOS(1)
|
+---------------------------------------------------------+
| 0.000000
ASIN(X)
The ASIN() function returns the arcsine of X. The value of X must be in the range of .1 to 1 or
NULL is returned.
SQL> SELECT ASIN(1);
+---------------------------------------------------------+
| ASIN(1)
|
+---------------------------------------------------------+
| 1.5707963267949
ATAN(X)
This function returns the arctangent of X.
SQL> SELECT ATAN(1);
+---------------------------------------------------------+
| ATAN(1)
|
+---------------------------------------------------------+
| 0.78539816339745
ATAN2(Y,X)
This function returns the arctangent of the two arguments: X and Y. It is similar to the arctangent
of Y/X, except that the signs of both are used to find the quadrant of the result.
SQL> SELECT ATAN2(3,6);
+---------------------------------------------------------+
| ATAN2(3,6)
|
+---------------------------------------------------------+
| 0.46364760900081
BIT_AND(expression)
The BIT_AND function returns the bitwise AND of all bits in expression. The basic premise is
that if two corresponding bits are the same, then a bitwise AND operation will return 1, while if
they are different, a bitwise AND operation will return 0. The function itself returns a 64-bit
integer value. If there are no matches, then it will return 18446744073709551615. The following
example performs the BIT_AND function on the PRICE column grouped by the MAKER of the
car:
SQL> SELECT
MAKER, BIT_AND(PRICE) BITS
FROM CARS GROUP BY MAKER
+---------------------------------------------------------+
|MAKER
BITS
|
+---------------------------------------------------------+
|CHRYSLER
512
|
|FORD
12488
|
|HONDA
2144
BIT_COUNT(numeric_value)
The BIT_COUNT() function returns the number of bits that are active in numeric_value. The
following example demonstrates using the BIT_COUNT() function to return the number of
active bits for a range of numbers:
SQL> SELECT
BIT_COUNT(2) AS TWO,
BIT_COUNT(4) AS FOUR,
BIT_COUNT(7) AS SEVEN
+-----+------+-------+
| TWO | FOUR | SEVEN |
+-----+------+-------+
|
1 |
1 |
3 |
+-----+------+-------+
BIT_OR(expression)
The BIT_OR() function returns the bitwise OR of all the bits in expression. The basic premise of
the bitwise OR function is that it returns 0 if the corresponding bits match, and 1 if they do not.
The function returns a 64-bit integer, and, if there are no matching rows, then it returns 0. The
following example performs the BIT_OR() function on the PRICE column of the CARS table,
grouped by the MAKER:
SQL> SELECT
MAKER, BIT_OR(PRICE) BITS
FROM CARS GROUP BY MAKER
+---------------------------------------------------------+
|MAKER
BITS
|
+---------------------------------------------------------+
|CHRYSLER
62293
|
|FORD
16127
|
|HONDA
32766
CONV(N,from_base,to_base)
The purpose of the CONV() function is to convert numbers between different number bases. The
function returns a string of the value N converted from from_base to to_base. The minimum base
value is 2 and the maximum is 36. If any of the arguments are NULL, then the function returns
NULL. Consider the following example, which converts the number 5 from base 16 to base 2:
SQL> SELECT CONV(5,16,2);
+---------------------------------------------------------+
| CONV(5,16,2)
|
+---------------------------------------------------------+
| 101
COS(X)
This function returns the cosine of X. The value of X is given in radians.
SQL>SELECT COS(90);
+---------------------------------------------------------+
| COS(90)
|
+---------------------------------------------------------+
| -0.44807361612917
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
COT(X)
This function returns the cotangent of X. Consider the following example:
SQL>SELECT COT(1);
+---------------------------------------------------------+
| COT(1)
|
+---------------------------------------------------------+
| 0.64209261593433
EXP(X)
This function returns the value of e (the base of the natural logarithm) raised to the power of X.
SQL>SELECT EXP(3);
+---------------------------------------------------------+
| EXP(3)
|
+---------------------------------------------------------+
| 20.085537
|
+--------------
LEAST(N1,N2,N3,N4,......)
The LEAST() function is the opposite of the GREATEST() function. Its purpose is to return the
least-valued item from the value list (N1, N2, N3, and so on). The following example shows the
proper usage and output for the LEAST() function:
SQL>SELECT LEAST(3,5,1,8,33,99,34,55,67,43);
+---------------------------------------------------------+
| LEAST(3,5,1,8,33,99,34,55,67,43)
|
+---------------------------------------------------------+
| 1
MOD(N,M)
This function returns the remainder of N divided by M. Consider the following example:
SQL>SELECT MOD(29,3);
+---------------------------------------------------------+
| MOD(29,3)
|
+---------------------------------------------------------+
| 2
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
OCT(N)
The OCT() function returns the string representation of the octal number N. This is equivalent to
using CONV(N,10,8).
SQL>SELECT OCT(12);
+---------------------------------------------------------+
| OCT(12)
|
+---------------------------------------------------------+
| 14
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
PI()
This function simply returns the value of pi. SQL internally stores the full double-precision value
of pi.
SQL>SELECT PI();
+---------------------------------------------------------+
| PI()
|
+---------------------------------------------------------+
| 3.141593
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
POW(X,Y)
POWER(X,Y)
These two functions return the value of X raised to the power of Y.
SQL> SELECT POWER(3,3);
+---------------------------------------------------------+
| POWER(3,3)
|
+---------------------------------------------------------+
| 27
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
RADIANS(X)
This function returns the value of X, converted from degrees to radians.
SQL>SELECT RADIANS(90);
+---------------------------------------------------------+
| RADIANS(90)
|
+---------------------------------------------------------+
|1.570796
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
ROUND(X)
ROUND(X,D)
This function returns X rounded to the nearest integer. If a second argument, D, is supplied, then
the function returns X rounded to D decimal places. D must be positive or all digits to the right
of the decimal point will be removed. Consider the following example:
SQL>SELECT ROUND(5.693893);
+---------------------------------------------------------+
| ROUND(5.693893)
|
+---------------------------------------------------------+
| 6
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQL>SELECT ROUND(5.693893,2);
+---------------------------------------------------------+
| ROUND(5.693893,2)
|
+---------------------------------------------------------+
| 5.69
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
SIGN(X)
This function returns the sign of X (negative, zero, or positive) as .1, 0, or 1.
SQL>SELECT SIGN(-4.65);
+---------------------------------------------------------+
| SIGN(-4.65)
|
+---------------------------------------------------------+
| -1
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQL>SELECT SIGN(0);
+---------------------------------------------------------+
| SIGN(0)
|
+---------------------------------------------------------+
| 0
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQL>SELECT SIGN(4.65);
+---------------------------------------------------------+
| SIGN(4.65)
|
+---------------------------------------------------------+
| 1
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
SIN(X)
This function returns the sine of X. Consider the following example:
SQL>SELECT SIN(90);
+---------------------------------------------------------+
| SIN(90)
|
+---------------------------------------------------------+
| 0.893997
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
SQRT(X)
This function returns the non-negative square root of X. Consider the following example:
SQL>SELECT SQRT(49);
+---------------------------------------------------------+
| SQRT(49)
|
+---------------------------------------------------------+
| 7
|
+---------------------------------------------------------+
1 row in set (0.00 sec)
STD(expression)
STDDEV(expression)
The STD() function is used to return the standard deviation of expression. This is equivalent to
taking the square root of the VARIANCE() of expression. The following example computes the
standard deviation of the PRICE column in our CARS table:
SQL>SELECT STD(PRICE) STD_DEVIATION FROM CARS;
| STD_DEVIATION
|
| 7650.2146
|
+
TAN(X)
This function returns the tangent of the argument X, which is expressed in radians.
SQL>SELECT TAN(45);
+---------------------------------------------------------+
| TAN(45)
|
+---------------------------------------------------------+
| 1.619775
defining table and Column
constraints
Constraints
Constraints let you define the way the Database Engine automatically enforces the
integrity of a database. Constraints define rules regarding the values allowed in columns and are
the standard mechanism for enforcing integrity. The query optimizer also uses constraint
definitions to build high-performance query execution plans.
Classes of Constraints
SQL Server supports the following classes of constraints:

NOT NULL specifies that the column does not accept NULL values.


CHECK constraints enforce domain integrity by limiting the values that can be put in a
column.
A CHECK constraint specifies a Boolean (evaluates to TRUE, FALSE, or unknown)
search condition that is applied to all values that are entered for the column. All values
that evaluate to FALSE are rejected. You can specify multiple CHECK constraints for
each column. The following sample shows creating the constraint chk_id. This constraint
additionally enforces the domain of the primary key by making sure that only numbers
within a specified range are entered for the key.
CREATE TABLE cust_sample
(
cust_id
int
PRIMARY KEY,
cust_name
char(50),
cust_address
char(50),
cust_credit_limit
money,
CONSTRAINT chk_id CHECK (cust_id BETWEEN 0 and 10000 )
)

UNIQUE constraints enforce the uniqueness of the values in a set of columns.
In a UNIQUE constraint, no two rows in the table can have the same value for the
columns. Primary keys also enforce uniqueness, but primary keys do not allow for NULL
as one of the unique values.



PRIMARY KEY constraints identify the column or set of columns that have values that
uniquely identify a row in a table.
No two rows in a table can have the same primary key value. You cannot enter NULL for
any column in a primary key. We recommend using a small, integer column as a primary
key. Each table should have a primary key. A column or combination of columns that
qualify as a primary key value is referred to as a candidate key. The following example
creates the part_sample table and specifies the part_nmbr field as the primary key.
CREATE TABLE part_sample
(part_nmbr
int
PRIMARY KEY,
part_name
char(30),
part_weight
decimal(6,2),
part_color
char(15) );

o
FOREIGN KEY constraints identify and enforce the relationships between tables.
A foreign key in one table points to a candidate key in another table. In the
following example, the order_part table establishes a foreign key that references the
part_sample table defined previously.
CREATE TABLE order_part
(order_nmbr
int,
part_nmbr
int
FOREIGN KEY REFERENCES part_sample(part_nmbr)
ON DELETE NO ACTION,
qty_ordered
int);
GO
You cannot insert a row with a foreign key value, except NULL, if there is no candidate
key with that value. The ON DELETE clause controls what actions are taken when you
try to delete a row to which existing foreign keys point. The ON DELETE clause has the
following options:
o
o
o
o
NO ACTION specifies that the deletion fails with an error.
CASCADE specifies that all the rows with foreign keys pointing to the deleted
row are also deleted.
o SET NULL specifies that all rows with foreign keys pointing to the deleted row
are set to NULL.
SET DEFAULT specifies that all rows with foreign keys pointing to the deleted
row are set to their default value.
The ON UPDATE clause defines the actions that are taken if you try to update a
candidate key value to which existing foreign keys point. This clause also supports the
NO ACTION, CASCADE, SET NULL and SET DEFAULT options.
Column and Table Constraints
Constraints can be column constraints or table constraints. A column constraint is
specified as part of a column definition and applies only to that column. The constraints in the
previous examples are column constraints. A table constraint is declared independently from a
column definition and can apply to more than one column in a table. Table constraints must be
used when more than one column must be included in a constraint.
For example, if a table has two or more columns in the primary key, you must use a table
constraint to include both columns in the primary key. Consider a table that records events
occurring in a computer in a factory. Assume that events of several types can occur at the same
time, but that no two events occurring at the same time can be of the same type. This can be
enforced in the table by including both the event_type and event_time columns in a two-column
primary key, as shown in the following example.
CREATE TABLE factory_process
(event_type
int,
event_time
datetime,
event_site
char(50),
event_desc
char(1024),
CONSTRAINT event_key PRIMARY KEY (event_type, event_time) )
Table Indexes
Microsoft® SQL Server™ 2000 supports indexes defined on any column in a table, including
computed columns.
If a table is created with no indexes, the data rows are not stored in any particular order. This
structure is called a heap.
The two types of SQL Server indexes are:

Clustered
Clustered indexes sort and store the data rows in the table based on their key values.
Because the data rows are stored in sorted order on the clustered index key, clustered
indexes are efficient for finding rows. There can only be one clustered index per table,
because the data rows themselves can only be sorted in one order. The data rows
themselves form the lowest level of the clustered index.
The only time the data rows in a table are stored in sorted order is when the table contains
a clustered index. If a table has no clustered index, its data rows are stored in a heap.

Nonclustered
Nonclustered indexes have a structure completely separate from the data rows. The
lowest rows of a nonclustered index contain the nonclustered index key values and each
key value entry has pointers to the data rows containing the key value. The data rows are
not stored in order based on the nonclustered key.
The pointer from an index row in a nonclustered index to a data row is called a row
locator. The structure of the row locator depends on whether the data pages are stored in
a heap or are clustered. For a heap, a row locator is a pointer to the row. For a table with a
clustered index, the row locator is the clustered index key.
The only time the rows in a table are stored in any specific sequence is when a clustered index is
created on the table. The rows are then stored in sequence on the clustered index key. If a table
only has nonclustered indexes, its data rows are stored in a unordered heap.
Indexes can be unique, which means no two rows can have the same value for the index key.
Otherwise, the index is not unique and multiple rows can share the same key value.
There are two ways to define indexes in SQL Server. The CREATE INDEX statement creates
and names an index. The CREATE TABLE statement supports the following constraints that
create indexes:

PRIMARY KEY creates a unique index to enforce the primary key.

UNIQUE creates a unique index.

CLUSTERED creates a clustered index.

NONCLUSTERED creates a nonclustered index.
When you create an index on SQL Server 2000, you can specify whether the keys are stored in
ascending or descending order.
SQL Server 2000 supports indexes defined on computed columns, as long as the expression
defined for the column meets certain restrictions, such as only referencing columns from the
table containing the computed column, and being deterministic.
A fill factor is a property of a SQL Server index that controls how densely the index is packed
when created. The default fill factor usually delivers good performance, but in some cases it may
be beneficial to change the fill factor. If the table is going to have many updates and inserts,
create an index with a low fill factor to leave more room for future keys. If the table is a readonly table that will not change, create the index with a high fill factor to reduce the physical size
of the index, which lowers the number of disk reads SQL Server uses to navigate through the
index. Fill factors are only applied when the index is created. As keys are inserted and deleted,
the index will eventually stabilize at a certain density.
Indexes not only speed up the retrieval of rows for selects, they also usually increase the speed of
updates and deletes. This is because SQL Server must first find a row before it can update or
delete the row. The increased efficiency of using the index to locate the row usually offsets the
extra overhead needed to update the indexes, unless the table has a lot of indexes.
This example shows the Transact-SQL syntax for creating indexes on a table.
USE pubs
GO
CREATE TABLE emp_sample
(emp_id
int
PRIMARY KEY CLUSTERED,
emp_name
char(50),
emp_address
char(50),
emp_title
char(25)
UNIQUE NONCLUSTERED )
GO
CREATE NONCLUSTERED INDEX sample_nonclust ON emp_sample(emp_name)
GO
Deciding which particular set of indexes will optimize performance depends on the mix of
queries in the system. Consider the clustered index on emp_sample.emp_id. This works well if
most queries referencing emp_sample have equality or range comparisons on emp_id in their
WHERE clauses. If the WHERE clauses of most queries reference emp_name instead of
emp_id, performance could be improved by instead making the index on emp_name the
clustered index.
Many applications have a complex mix of queries that is difficult to estimate by interviewing
users and programmers. SQL Server 2000 provides an Index Tuning Wizard to help design
indexes in a database. The easiest way to design indexes for large schemas with complex access
patterns is to use the Index Tuning Wizard.
UNIT – IV
Sophisticated queries – Builtin group functions – The join
operation, views, sequences and synonyms.
SQL GROUP Functions
Group functions are built-in SQL functions that operate on groups of rows and return one value
for the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT
SQL COUNT (): This function returns the number of rows in the table that satisfies the
condition specified in the WHERE condition. If the WHERE condition is not specified, then the
query returns the total number of rows in the table.
For Example: If you want the number of employees in a particular department, the query would
be:
SELECT COUNT (*) FROM employee
WHERE dept = 'Electronics';
The output would be '2' rows.
If you want the total number of employees in all the department, the query would take the form:
SELECT COUNT (*) FROM employee;
The output would be '5' rows.
SQL DISTINCT(): This function is used to select the distinct rows.
For Example: If you want to select all distinct department names from employee table, the
query would be:
SELECT DISTINCT dept FROM employee;
To get the count of employees with unique name, the query would be:
SELECT COUNT (DISTINCT name) FROM employee;
SQL MAX(): This function is used to get the maximum value from a column.
To get the maximum salary drawn by an employee, the query would be:
SELECT MAX (salary) FROM employee;
SQL MIN(): This function is used to get the minimum value from a column.
To get the minimum salary drawn by an employee, he query would be:
SELECT MIN (salary) FROM employee;
SQL AVG(): This function is used to get the average value of a numeric column.
To get the average salary, the query would be
SELECT AVG (salary) FROM employee;
SQL SUM(): This function is used to get the sum of a numeric column
To get the total salary given out to the employees,
SELECT SUM (salary) FROM employee;
The Join Operation
The join operation is the mechanism that allows tables to be related to one another. A join
operation retrieves columns from two or more tables. For example, if you were joining two
tables, the retrieval criteria would specify the condition that a column in the first table--;which is
defined as a foreign key--;is equal to a column in the second table--;which is the primary key
referenced by the foreign key. A join operation in which the join's WHERE clause contains
additional conditions is called an equi-join. The general syntax for the SELECT statement
enables you to join more than two tables.
SELECT select-list
FROM table1, table2, ... , tableN
WHERE table1.column1 = table2.column2 and
...
table2.column3 = tableN.columnN
...
additional-conditions
The variables are as follows: select-list is the set of columns and expressions from table1 through
tableN.
table1 through tableN are the tables from which column values are retrieved.
column1 through columnN are the columns in table1 through tableN that are related.
additional-conditions are optional query criteria.
Please note that you are not required to reference column1 through columnN in the select-list.
A Simple Two-Table Join
A simple two-table join illustrates the use of this syntax. As you recall, the repair store database
includes the Repair_Header table, which contains basic information about a customer's repair ID,
and the Customer table that contains customer data. In order to prevent the storage of redundant
data, the Repair_Header table stores only one piece of information about the customer: the
Customer ID. By joining the Repair_Header table with the Customer table based on the
Customer_ID column, you can retrieve additional customer data.
SQL> select Repair_id, Last_Name, First_Name
2
from Repair_Header, Customer
3
where
4
Repair_Header.Customer_ID = Customer.Customer_ID
5
order by Repair_ID;
REPAIR_ID LAST_NAME
FIRST_NAME
--------- ------------------------------ -----------------------------501 Martinez
Steve
502 Smyth
Julie
503 Horace
Michelle
504 Pareski
Monica
505 Moran
Sarah
Here's an analysis of each element of the SELECT statement. The select list consists of the three
columns of interest: Repair_ID, Last_Name, and First_Name. The list of tables is made up of
Repair_Header and Customer. The WHERE clause instructs Personal Oracle7 to return only rows
in which Customer_ID in the Repair_Header table can be matched with a row in the Customer
table that has the same value for Customer_ID.
The columns in the select-list can appear in any order; for example, the following query is
perfectly acceptable:
SQL> select Last_Name, First_Name, Repair_ID
2
from Repair_Header, Customer
3
where
4
Repair_Header.Customer_ID = Customer.Customer_ID
5
order by Last_Name;
LAST_NAME
FIRST_NAME
REPAIR_ID
------------------------------ ------------------------------ --------Horace
Michelle
503
Martinez
Steve
501
Moran
Sarah
505
Pareski
Monica
504
Smyth
Julie
502
The query lists Last_Name, First_Name, and Repair_ID, even though Repair_Header is listed
before Customer in the table list.
Ambiguous Columns
You need to keep in mind that each reference to a column in a join must be unambiguous. In this
context unambiguous means that if the column exists in more than one table referenced in the
join, the column name is qualified by the table name. Oracle returns an error message if you
reference a column ambiguously.
SQL> select Customer_ID, Last_Name, First_Name, Repair_ID
2
from Repair_Header, Customer
3
where
4
Repair_Header.Customer_ID = Customer.Customer_ID
5
order by Last_Name;
select Customer_ID, Last_Name, First_Name, Repair_ID
*
ERROR at line 1:
ORA-00918: column ambiguously defined
Oracle returns the error message because Customer_ID, which is referenced in the first line of
the SELECT statement, appears in both the Repair_Header and Customer tables. To correct this
problem, you must qualify the Customer_ID column with the table name.
SQL> select Customer.Customer_ID, Last_Name, First_Name, Repair_ID
2
from Repair_Header, Customer
3
where
4
Repair_Header.Customer_ID = Customer.Customer_ID
5
order by Last_Name;
CUSTOMER_ID LAST_NAME
FIRST_NAME
REPAIR_ID
----------- -------------------- --------------- --------1005 Horace
Michelle
503
1002 Martinez
Steve
501
1008 Moran
Sarah
505
1006 Pareski
Monica
504
1003 Smyth
Julie
502
Multiple-Table Joins
As you see, the syntax for the SELECT statement doesn't limit the number of tables that can be
joined. As an example, you can join these three tables--;Repair_Header, Repair_Item, and
Product--;to retrieve a description of each repair item.
SQL> select R.Repair_ID, Customer_ID, Item_Number, Description
2
from Repair_Header R, Repair_Item I, Product P
3
where
4
R.Repair_ID = I.Repair_ID and
5
I.Product_ID = P.Product_ID and
6
I.Manufacturer_ID = P.Manufacturer_ID
7
order by R.Repair_ID, Item_Number;
REPAIR_ID CUSTOMER_ID ITEM_NUMBER DESCRIPTION
--------- ----------- ----------- ---------------------------------------501
1002
1 CD PLAYER, SINGLE-DISK
502
1003
1 CCD Camera
503
1005
1 Pre-amp, 120 W per channel
504
1006
1 PRE AMPLIFIER 150 WATTS/CHANNEL
505
1008
1 AMP, PROFESSIONAL 800W RMS PER CHANNEL
506
1010
1 Tuner
506
1010
2 PREAMP, 460 W/RMS
7 rows selected.
Notice that an alias has been specified for each of the three tables:



R for Repair_Header
I for Repair_Item
P for Product
Although table aliases are optional, you should use them in multiple-table joins because they
reduce the size of the SELECT statement and simplify its appearance.
Self-Joins
Another form of a two-table join is the self-join. This type of join is used when a table
has a foreign key that references its own primary key. A good example of the self-join is the
Product_Assembly table discussed earlier in this chapter. The primary key of the
Product_Assembly table is Product_ID. Every product--;except a complete product--;belongs to
an assembly. Therefore, Assembly_ID is a foreign key that references Product_ID
Outer Joins
You've seen that a multiple-table join returns only columns from each table where the join
conditions are met. Consider the following example in which you have two tables--;an Employee
table and an Employee_ Dependent table. An employee may have zero, one, or several
dependents. Accordingly, a row in the Employee table may have zero or more related rows in the
Employee_Dependent table. Here are the contents of the tables:
SQL> select Employee_ID, Last_Name, First_Name
2
from Employee
3
order by Employee_ID;
EMPLOYEE_ID LAST_NAME
FIRST_NAME
----------- ------------------------------ -------------------1001 SMITH
JEAN
1002 HERNANDEZ
RANDY
1003 GLEASON
PAUL
1004 BARRETT
SARAH
1005 HIGGINS
BEN
1006 YEN
CINDY
1007 GILROY
MAX
1008 CARSON
BETH
1009 SWANSON
HARRY
9 rows selected.
SQL> select Employee_ID, Last_Name, First_Name, Relationship
2
from Employee_Dependent
3
order by Employee_ID;
EMPLOYEE_ID LAST_NAME
FIRST_NAME
RELATIONSHIP
----------- ------------------------------ -------------------- -------------1001 SMITH
JARED
CHILD
1006 YEN
RANDY
SPOUSE
1007 GILROY
ARTHUR
CHILD
1007 GILROY
CATHY
SPOUSE
1007 GILROY
HORACE
CHILD
Join (SQL)
An SQL join clause combines records from two or more tables in a database. It creates a set that
can be saved as a table or used as is. A JOIN is a means for combining fields from two tables by
using values common to each. ANSI standard SQL specifies four types of JOIN: INNER, OUTER,
LEFT, and RIGHT. As a special case, a table (base table, view, or joined table) can JOIN to itself in
a self-join.
A programmer writes a JOIN predicate to identify the records for joining. If the evaluated
predicate is true, the combined record is then produced in the expected format, a record set or a
temporary table.
SQL Views
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if
the data were coming from one single table.
SQL CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view.
SQL CREATE VIEW Examples
If you have the Northwind database you can see that it has several views installed by default.
The view "Current Product List" lists all active products (products that are not discontinued)
from the "Products" table. The view is created with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
We can query the view above as follows:
SELECT * FROM [Current Product List]
Another view in the Northwind sample database selects every product in the "Products" table
with a unit price higher than the average unit price:
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)
We can query the view above as follows:
SELECT * FROM [Products Above Average Price]
Another view in the Northwind database calculates the total sale for each category in 1997. Note
that this view selects its data from another view called "Product Sales for 1997":
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName
We can query the view above as follows:
SELECT * FROM [Category Sales For 1997]
We can also add a condition to the query. Now we want to see the total sale only for the category
"Beverages":
SELECT * FROM [Category Sales For 1997]
WHERE CategoryName='Beverages'
SQL Updating a View
SQL CREATE OR REPLACE VIEW Syntax
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Now we want to add the "Category" column to the "Current Product List" view. We will update
the view with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName,Category
FROM Products
WHERE Discontinued=No
SQL Dropping a View
You can delete a view with the DROP VIEW command.
SQL DROP VIEW Syntax
DROP VIEW view_name
Managing Views, Sequences, and
Synonyms
This chapter describes the management of views, sequences, and synonyms and
contains the following topics:



Managing Views
Managing Sequences
Managing Synonyms
Managing Views
A view is a logical representation of another table or combination of tables. A view
derives its data from the tables on which it is based. These tables are called base
tables. Base tables might in turn be actual tables or might be views themselves. All
operations performed on a view actually affect the base table of the view. You can use
views in almost the same way as tables. You can query, update, insert into, and delete
from views, just as you can standard tables.
Views can provide a different representation (such as subsets or supersets) of the data
that resides within other tables and views. Views are very powerful because they allow
you to tailor the presentation of data to different types of users.
Creating Views
To create a view, you must meet the following requirements:


To create a view in your schema, you must have the CREATE VIEW privilege. To
create a view in another user's schema, you must have the CREATE ANY VIEW
system privilege. You can acquire these privileges explicitly or through a role.
The owner of the view (whether it is you or another user) must have been
explicitly granted privileges to access all objects referenced in the view definition.
The owner cannot have obtained these privileges through roles. Also, the
functionality of the view depends on the privileges of the view owner. For

example, if the owner of the view has only the INSERT privilege for Scott's emp
table, then the view can be used only to insert new rows into the emp table, not
to SELECT, UPDATE, or DELETE rows.
If the owner of the view intends to grant access to the view to other users, the
owner must have received the object privileges to the base objects with the
GRANT OPTION or the system privileges with the ADMIN OPTION.
You can create views using the CREATE VIEW statement. Each view is defined by a query
that references tables, materialized views, or other views. As with all subqueries, the
query that defines a view cannot contain the FOR UPDATE clause.
The following statement creates a view on a subset of data in the emp table:
CREATE VIEW sales_staff AS
SELECT empno, ename, deptno
FROM emp
WHERE deptno = 10
WITH CHECK OPTION CONSTRAINT sales_staff_cnst;
The query that defines the sales_staff view references only rows in department 10.
Furthermore, the CHECK OPTION creates the view with the constraint (named
sales_staff_cnst) that INSERT and UPDATE statements issued against the view cannot
result in rows that the view cannot select. For example, the following INSERT statement
successfully inserts a row into the emp table by means of the sales_staff view, which
contains all rows with department number 10:
INSERT INTO sales_staff VALUES (7584, 'OSTER', 10);
However, the following INSERT statement returns an error because it attempts to insert
a row for department number 30, which cannot be selected using the sales_staff
view:
INSERT INTO sales_staff VALUES (7591, 'WILLIAMS', 30);
The view could have been constructed specifying the WITH READ ONLY clause, which
prevents any updates, inserts, or deletes from being done to the base table through the
view. If no WITH clause is specified, the view, with some restrictions, is inherently
updatable.
Join Views
You can also create views that specify more than one base table or view in the FROM
clause. These are called join views. The following statement creates the
division1_staff view that joins data from the emp and dept tables:
CREATE VIEW division1_staff AS
SELECT ename, empno, job, dname
FROM emp, dept
WHERE emp.deptno IN (10, 30)
AND emp.deptno = dept.deptno;
An updatable join view is a join view where UPDATE, INSERT, and DELETE operations
are allowed. See "Updating a Join View" for further discussion.
Creating Views with Errors
If there are no syntax errors in a CREATE VIEW statement, the database can create the
view even if the defining query of the view cannot be executed. In this case, the view is
considered "created with errors." For example, when a view is created that refers to a
nonexistent table or an invalid column of an existing table, or when the view owner
does not have the required privileges, the view can be created anyway and entered into
the data dictionary. However, the view is not yet usable.
To create a view with errors, you must include the FORCE clause of the CREATE VIEW
statement.
CREATE FORCE VIEW AS ...;
By default, views with errors are created as INVALID. When you try to create such a
view, the database returns a message indicating the view was created with errors. If
conditions later change so that the query of an invalid view can be executed, the view
can be recompiled and be made valid (usable). For information changing conditions and
their impact on views, see "Managing Object Dependencies".
Replacing Views
To replace a view, you must have all of the privileges required to drop and create a
view. If the definition of a view must change, the view must be replaced; you cannot
use an ALTER VIEW statement to change the definition of a view. You can replace views
in the following ways:

You can drop and re-create the view.
Altering Views
You use the ALTER VIEW statement only to explicitly recompile a view that is invalid. If
you want to change the definition of a view,
The ALTER VIEW statement lets you locate recompilation errors before run time. To
ensure that the alteration does not affect the view or other objects that depend on it,
you can explicitly recompile a view after altering one of its base tables.
To use the ALTER VIEW statement, the view must be in your schema, or you must have
the ALTER ANY TABLE system privilege.
Dropping Views
You can drop any view contained in your schema. To drop a view in another user's
schema, you must have the DROP ANY VIEW system privilege. Drop a view using the
DROP VIEW statement. For example, the following statement drops the emp_dept view:
DROP VIEW emp_dept;
Managing Sequences
Sequences are database objects from which multiple users can generate unique
integers. The sequence generator generates sequential numbers, which can help to
generate unique primary keys automatically, and to coordinate keys across multiple
rows or tables.
Without sequences, sequential values can only be produced programmatically. A new
primary key value can be obtained by selecting the most recently produced value and
incrementing it. This method requires a lock during the transaction and causes multiple
users to wait for the next value of the primary key; this waiting is known as
serialization. If developers have such constructs in applications, then you should
encourage the developers to replace them with access to sequences. Sequences
eliminate serialization and improve the concurrency of an application.
Creating Sequences
To create a sequence in your schema, you must have the CREATE SEQUENCE system
privilege. To create a sequence in another user's schema, you must have the CREATE
ANY SEQUENCE privilege.
Create a sequence using the CREATE SEQUENCE statement. For example, the following
statement creates a sequence used to generate employee numbers for the empno
column of the emp table:
CREATE SEQUENCE emp_sequence
INCREMENT BY 1
START WITH 1
NOMAXVALUE
NOCYCLE
CACHE 10;
Notice that several parameters can be specified to control the function of sequences.
You can use these parameters to indicate whether the sequence is ascending or
descending, the starting point of the sequence, the minimum and maximum values, and
the interval between sequence values. The NOCYCLE option indicates that the sequence
cannot generate more values after reaching its maximum or minimum value.
The CACHE clause preallocates a set of sequence numbers and keeps them in memory
so that sequence numbers can be accessed faster. When the last of the sequence
numbers in the cache has been used, the database reads another set of numbers into
the cache.
The database might skip sequence numbers if you choose to cache a set of sequence
numbers. For example, when an instance abnormally shuts down (for example, when
an instance failure occurs or a SHUTDOWN ABORT statement is issued), sequence numbers
that have been cached but not used are lost. Also, sequence numbers that have been
used but not saved are lost as well. The database might also skip cached sequence
numbers after an export and import. See Oracle Database Utilities for details.
Altering Sequences
To alter a sequence, your schema must contain the sequence, or you must have the
ALTER ANY SEQUENCE system privilege. You can alter a sequence to change any of the
parameters that define how it generates sequence numbers except the sequence
starting number. To change the starting point of a sequence, drop the sequence and
then re-create it.
Alter a sequence using the ALTER SEQUENCE statement. For example, the following
statement alters the emp_sequence:
ALTER SEQUENCE emp_sequence
INCREMENT BY 10
MAXVALUE 10000
CYCLE
CACHE 20;
Using Sequences
To use a sequence, your schema must contain the sequence or you must have been
granted the SELECT object privilege for another user's sequence. Once a sequence is
defined, it can be accessed and incremented by multiple users (who have SELECT object
privilege for the sequence containing the sequence) with no waiting. The database does
not wait for a transaction that has incremented a sequence to complete before that
sequence can be incremented again.
The examples outlined in the following sections show how sequences can be used in
master/detail table relationships. Assume an order entry system is partially comprised of
two tables, orders_tab (master table) and line_items_tab (detail table), that hold
information about customer orders. A sequence named order_seq is defined by the
following statement:
CREATE SEQUENCE Order_seq
START WITH 1
INCREMENT BY 1
NOMAXVALUE
NOCYCLE
CACHE 20;
Dropping Sequences
You can drop any sequence in your schema. To drop a sequence in another schema,
you must have the DROP ANY SEQUENCE system privilege. If a sequence is no longer
required, you can drop the sequence using the DROP SEQUENCE statement. For example,
the following statement drops the order_seq sequence:
DROP SEQUENCE order_seq;
When a sequence is dropped, its definition is removed from the data dictionary. Any
synonyms for the sequence remain, but return an error when referenced.
Managing Synonyms
A synonym is an alias for a schema object. Synonyms can provide a level of
security by masking the name and owner of an object and by providing location
transparency for remote objects of a distributed database. Also, they are convenient to
use and reduce the complexity of SQL statements for database users.
Synonyms allow underlying objects to be renamed or moved, where only the synonym
needs to be redefined and applications based on the synonym continue to function
without modification.
You can create both public and private synonyms. A public synonym is owned by the
special user group named PUBLIC and is accessible to every user in a database. A
private synonym is contained in the schema of a specific user and available only to the
user and the user's grantees.
Creating Synonyms
To create a private synonym in your own schema, you must have the CREATE SYNONYM
privilege. To create a private synonym in another user's schema, you must have the
CREATE ANY SYNONYM privilege. To create a public synonym, you must have the CREATE
PUBLIC SYNONYM system privilege.
Create a synonym using the CREATE SYNONYM statement. The underlying schema object
need not exist, nor do you need privileges to access the object. The following statement
creates a public synonym named public_emp on the emp table contained in the schema
of jward:
CREATE PUBLIC SYNONYM public_emp FOR jward.emp
When you create a synonym for a remote procedure or function, you must qualify the
remote object with its schema name. Alternatively, you can create a local public
synonym on the database where the remote object resides, in which case the database
link must be included in all subsequent calls to the procedure or function.
Using Synonyms in DML Statements
You can successfully use any private synonym contained in your schema or any public
synonym, assuming that you have the necessary privileges to access the underlying
object, either explicitly, from an enabled role, or from PUBLIC. You can also reference
any private synonym contained in another schema if you have been granted the
necessary object privileges for the private synonym.
You can only reference another user's synonym using the object privileges that you
have been granted. For example, if you have the SELECT privilege for the jward.emp
synonym, then you can query the jward.emp synonym, but you cannot insert rows using
the jward.emp synonym.
A synonym can be referenced in a DML statement the same way that the underlying
object of the synonym can be referenced. For example, if a synonym named emp refers
to a table or view, then the following statement is valid:
INSERT INTO emp (empno, ename, job)
VALUES (emp_sequence.NEXTVAL, 'SMITH', 'CLERK');
If the synonym named fire_emp refers to a standalone procedure or package
procedure, then you could execute it with the command
EXECUTE Fire_emp(7344);
Dropping Synonyms
You can drop any private synonym in your own schema. To drop a private synonym in
another user's schema, you must have the DROP ANY SYNONYM system privilege. To drop
a public synonym, you must have the DROP PUBLIC SYNONYM system privilege.
Drop a synonym that is no longer required using DROP SYNONYM statement. To drop a
private synonym, omit the PUBLIC keyword. To drop a public synonym, include the
PUBLIC keyword.
For example, the following statement drops the private synonym named emp:
DROP SYNONYM emp;
The following statement drops the public synonym named public_emp:
DROP PUBLIC SYNONYM public_emp;
When you drop a synonym, its definition is removed from the data dictionary. All
objects that reference a dropped synonym remain. However, they become invalid (not
usable.
UNIT – V
Transaction – the Basics of PL/SQL creating and using stored procedures, Functions and Packages –
Retrieving Data with cursors. Enforcing Business Rules with Database triggers.
. Basic Structure of PL/SQL
PL/SQL stands for Procedural Language/SQL. PL/SQL extends SQL by adding
constructs found in procedural languages, resulting in a structural language that is more powerful
than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks,
which can be nested within each other. Typically, each block performs a logical action in he
program.
A block has the following structure:
DECLARE
/* Declarative section: variables, types, and local subprograms. */
BEGIN
/* Executable section: procedural and SQL statements go here. */
/* This is the only section of the block that is required. */
EXCEPTION
/* Exception handling section: error handling statements go here. */
END;
Only the executable section is required. The other sections are optional. The only
SQL statements allowed in a PL/SQL program are SELECT, INSERT, UPDATE, DELETE and several
other data manipulation statements plus some transaction control. However, the SELECT
statement has a special form in which a single tuple is placed in variables. Data definition
statements like CREATE, DROP, or ALTER are not allowed. The executable section also contains
constructs such as assignments, branches, loops, procedure calls, and triggers. PL/SQL is
not case sensitive. C style comments (/* ... */) may be used.
To execute a PL/SQL program, we must follow the program text itself by


A line with a single dot ("."), and then
A line with run;
As with Oracle SQL programs, we can invoke a PL/SQL program either by typing it in sqlplus
.
Variables and Types
Information is transmitted between a PL/SQL program and the database through variables.
Every variable has a specific type associated with it. That type can be



One of the types used by SQL for database columns
A generic type used in PL/SQL such as NUMBER
Declared to be the same as the type of some database column
The most commonly used generic type is NUMBER. Variables of type NUMBER can hold either an
integer or a real number. The most commonly used character string type is VARCHAR(n), where n
is the maximum length of the string in bytes. This length is required, and there is no default. For
example, we might declare:
DECLARE
price
NUMBER;
myBeer VARCHAR(20);
Note that PL/SQL allows BOOLEAN variables, even though Oracle does not support BOOLEAN as a
type for database columns.
DECLARE
myBeer Beers.name%TYPE;
gives PL/SQL variable myBeer whatever type was declared for the name column in relation
Beers.
A variable may also have a type that is a record with several fields. The simplest way to declare
such a variable is to use %ROWTYPE on a relation name. The result is a record type in which the
fields have the same names and types as the attributes of the relation. For instance:
DECLARE
beerTuple Beers%ROWTYPE;
makes variable beerTuple be a record with fields name and manufacture, assuming that the
relation has the schema Beers(name, manufacture).
The initial value of any variable, regardless of its type, is NULL. We can assign values to
variables, using the ":=" operator. The assignment can occur either immediately after the type of
the variable is declared, or anywhere in the executable portion of the program. An example:
DECLARE
a NUMBER := 3;
BEGIN
a := a + 1;
END;
run;
This program has no effect when run, because there are no changes to the database.
Procedures
PL/SQL procedures behave very much like procedures in other programming language.
Here is an example of a PL/SQL procedure addtuple1 that, given an integer i, inserts the tuple
(i, 'xxx') into the following example relation:
CREATE TABLE T2 (
a INTEGER,
b CHAR(10)
);
CREATE PROCEDURE addtuple1(i IN NUMBER) AS
BEGIN
INSERT INTO T2 VALUES(i, 'xxx');
END addtuple1;
run;
A procedure is introduced by the keywords CREATE PROCEDURE followed by the
procedure name and its parameters. An option is to follow CREATE by OR REPLACE. The
advantage of doing so is that should you have already made the definition, you will not get an
error. On the other hand, should the previous definition be a different procedure of the same
name, you will not be warned, and the old procedure will be lost.
There can be any number of parameters, each followed by a mode and a type. The possible
modes are IN (read-only), OUT (write-only), and INOUT (read and write
Following the arguments is the keyword AS (IS is a synonym). Then comes the body, which is
essentially a PL/SQL block. We have repeated the name of the procedure after the END, but this
is optional. However, the DECLARE section should not start with the keyword DECLARE. Rather,
following AS we have:
... AS
<local_var_declarations>
BEGIN
<procedure_body>
END;
.
run;
The run at the end runs the statement that creates the procedure; it does not execute the
procedure. To execute the procedure, use another PL/SQL statement, in which the procedure is
invoked as an executable statement. For example:
BEGIN addtuple1(99); END;
.
run;
Printing Variables
. A more couth way is to define a bind variable, which is the only kind that may be printed with
a print command. Bind variables are the kind that must be prefixed with a colon in PL/SQL
statements, such as :new discussed in the section on triggers.
The steps are as follows:
1. We declare a bind variable as follows:
VARIABLE <name> <type>
where the type can be only one of three things: NUMBER, CHAR, or CHAR(n).
2. We may then assign to the variable in a following PL/SQL statement, but we must prefix
it with a colon.
3. Finally, we can execute a statement
PRINT :<name>;
outside the PL/SQL statement
Here is a trivial example, which prints the value 1.
VARIABLE x NUMBER
BEGIN
:x := 1;
END;
.
run;
PRINT :x;
Stored Procedure
A stored procedure or in simple a proc is a named PL/SQL block which performs one
or more specific task. This is similar to a procedure in other programming languages. A
procedure has a header and a body. The header consists of the name of the procedure and the
parameters or variables passed to the procedure. The body consists or declaration section,
execution section and exception section similar to a general PL/SQL Block. A procedure is
similar to an anonymous PL/SQL Block but it is named for repeated usage.
We
can
pass
1)IN-parameters
2)OUT-parameters
3) IN OUT-parameters
parameters
to
procedures
in
three
ways.
A procedure may or may not return any value.
General Syntax to create a procedure is:
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous
PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE
together the procedure is created if no other procedure with the same name exists or the existing
procedure is replaced with the current code.
Execution of a Stored Procedure.
There are two ways to execute a procedure.
1) From the SQL prompt.
EXECUTE [or EXEC] procedure_name;
2) Within another procedure – simply use the procedure name.
procedure_name;
PL/SQL Packages
A package is a schema object that groups logically related PL/SQL types, items, and
subprograms. Packages usually have two parts, a specification and a body, although sometimes
the body is unnecessary. The specification (spec for short) is the interface to your applications; it
declares the types, variables, constants, exceptions, cursors, and subprograms available for use.
The body fully defines cursors and subprograms, and so implements the spec.
To create packages, use the CREATE PACKAGE statement, which you can execute interactively
from SQL*Plus. Here is the syntax:
CREATE [OR REPLACE] PACKAGE package_name
[AUTHID {CURRENT_USER | DEFINER}]
{IS | AS}
[PRAGMA SERIALLY_REUSABLE;]
[collection_type_definition ...]
[record_type_definition ...]
[subtype_definition ...]
[collection_declaration ...]
[constant_declaration ...]
[exception_declaration ...]
[object_declaration ...]
[record_declaration ...]
[variable_declaration ...]
[cursor_spec ...]
[function_spec ...]
[procedure_spec ...]
[call_spec ...]
[PRAGMA RESTRICT_REFERENCES(assertions) ...]
END [package_name];
The spec holds public declarations, which are visible to your application. You must declare
subprograms at the end of the spec after all other items (except pragmas that name a specific
function; such pragmas must follow the function spec).
The body holds implementation details and private declarations, which are hidden from your
application. Following the declarative part of the package body is the optional initialization part,
which typically holds statements that initialize package variables.
A call spec lets you publish a Java method or external C function in the Oracle data dictionary.
The call spec publishes the routine by mapping its name, parameter types, and return type to their
SQL counterparts..
Advantages of PL/SQL Packages
Modularity
Packages let you encapsulate logically related types, items, and subprograms in a named PL/SQL
module. Each package is easy to understand, and the interfaces between packages are simple,
clear, and well defined. This aids application development.
Easier Application Design
When designing an application, all you need initially is the interface information in the package
specs. You can code and compile a spec without its body. Then, stored subprograms that
reference the package can be compiled as well. You need not define the package bodies fully
until you are ready to complete the application.
Information Hiding
With packages, you can specify which types, items, and subprograms are public (visible and
accessible) or private (hidden and inaccessible). For example, if a package contains four
subprograms, three might be public and one private. The package hides the implementation of
the private subprogram so that only the package (not your application) is affected if the
implementation changes. This simplifies maintenance and enhancement. Also, by hiding
implementation details from users, you protect the integrity of the package.
Added Functionality
Packaged public variables and cursors persist for the duration of a session. So, they can be shared
by all subprograms that execute in the environment. Also, they allow you to maintain data across
transactions without having to store it in the database.
Better Performance
When you call a packaged subprogram for the first time, the whole package is loaded into
memory. So, later calls to related subprograms in the package require no disk I/O. Also,
packages stop cascading dependencies and thereby avoid unnecessary recompiling.
Cursor
A cursor is a variable that runs through the tuples of some relation. This relation can
be a stored table, or it can be the answer to some query. A cursor is a temporary work area
created in the system memory when a SQL statement is executed. A cursor contains information
on a select statement and the rows of data accessed by it. This temporary work area is used to
store the data retrieved from the database, and manipulate this data. A cursor can hold more than
one row, but can process only one row at a time. The set of rows the cursor holds is called the
active set.
To use cursors in SQL procedures, you need to do the following:
1. Declare a cursor that defines a result set.
2. Open the cursor to establish the result set.
3. Fetch the data into local variables as needed from the cursor, one row at a time.
4. Close the cursor when done
To work with cursors you must use the following SQL statements:
 DECLARE CURSOR
 OPEN
 FETCH
 CLOSE
There are two types of cursors in PL/SQL:
Implicit cursors:
These are created by default when DML statements like, INSERT, UPDATE, and
DELETE statements are executed. They are also created when a SELECT statement that returns
just one row is executed.
Explicit cursors:
They must be created when you are executing a SELECT statement that returns more
than one row. Even though the cursor stores multiple records, only one record can be processed
at a time, which is called as current row. When you fetch a row the current row position moves
to next row.
Both implicit and explicit cursors have the same functionality, but they differ in the way they are
accessed.
The following example demonstrates the basic use of a read-only cursor within an SQL procedure:
CREATE PROCEDURE sum_salaries(OUT sum INTEGER)
LANGUAGE SQL
BEGIN
DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
DECLARE p_sum INTEGER;
DECLARE p_sal INTEGER;
DECLARE c CURSOR FOR SELECT SALARY FROM EMPLOYEE;
SET p_sum = 0;
OPEN c;
FETCH FROM c INTO p_sal;
WHILE(SQLSTATE = '00000') DO
SET p_sum = p_sum + p_sal;
FETCH FROM c INTO p_sal;
END WHILE;
CLOSE c;
SET sum = p_sum;
END%
Functions
PL/SQL Functions
What is a Function in PL/SQL?
A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a
procedure
may
or
may
not
return
a
value.
The General Syntax to create a function is:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
1) Return Type: The header section defines the return type of the function. The return
datatype can be any of the oracle datatype like varchar, number etc.
2) The execution and exception section both should return a value which is of the datatype
defined in the header section.
For example, let’s create a frunction called ''employer_details_func' similar to the one created in
stored proc
1> CREATE OR REPLACE FUNCTION employer_details_func
2>
RETURN VARCHAR(20);
3> IS
5>
emp_name VARCHAR(20);
6> BEGIN
7>
SELECT first_name INTO emp_name
8>
FROM emp_tbl WHERE empID = '100';
9>
RETURN emp_name;
10> END;
11> /
In the example we are retrieving the ‘first_name’ of employee with empID 100 to variable
‘emp_name’.
The return type of the function is VARCHAR which is declared in line no 2.
The function returns the 'emp_name' which is of type VARCHAR as the return value in line no
9.
How to execute a PL/SQL Function?
A function can be executed in the following ways.
1) Since a function returns a value we can assign it to a variable.
employee_name
:=
employer_details_func;
If ‘employee_name’ is of datatype varchar we can store the name of the employee by assigning
the return type of the function to it.
2) As a part of a SELECT statement
SELECT employer_details_func FROM dual;
3) In a PL/SQL Statements like,
dbms_output.put_line(employer_details_func);
This line displays the value returned by the function.
Triggers
A trigger is a pl/sql block structure which is fired when a DML statements like Insert,
Delete, Update is executed on a database table. A trigger is triggered automatically when an
associated DML statement is executed.
Syntax of Triggers
The Syntax for creating a trigger is:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS name1 NEW AS name2]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;









CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given name
or overwrites an existing trigger with the same name.
{BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the trigger get fired.
i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger on a
view. before and after cannot be used to create a trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event. More than
one triggering events can be used together separated by OR keyword. The trigger gets fired at
all the specified triggering event.
[OF col_name] - This clause is used with update triggers. This clause is used when you want to
trigger an event only when a specific column is updated.
CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given name
or overwrites an existing trigger with the same name.
[ON table_name] - This clause identifies the name of the table or view to which the trigger is
associated.
[REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new values of
the data being changed. By default, you reference the values as :old.column_name or
:new.column_name. The reference names can also be changed from old (or new) to any other
user-defined name. You cannot reference old values when inserting a record, or new values
when deleting a record, because they do not exist.
[FOR EACH ROW] - This clause is used to determine whether a trigger must fire when each row
gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is
executed(i.e.statement level Trigger).
WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired only for
rows that satisfy the condition specified.
Types of PL/SQL Triggers
There are two types of triggers based on the which level it is triggered.
1) Row level trigger - An event is triggered for each row upated, inserted or deleted.
2) Statement level trigger - An event is triggered for each sql statement executed.