OracleDoc PDF
OracleDoc PDF
RDBMS – Oracle
Let's before start working with Oracle first we have to look into a jargon of the concepts related to database
fundamentals. Following diagram maps that where is the oracle stands in our computer world. It is one of
the most widely used Relational Database Management System in the world.
DBMS: The Database Management System (DBMS) is a set of computer programs that controls the creation,
maintenance, and the use of a database. In order to manage data in database we need an efficient system
that organizes, manages and manipulates the database. Such software is called as a Database Management
System. Question rises here, what is data?
Data: The data is a collection of facts. The
word data is plural of word Datum which is
an item of factual information derived from
measurement or research. All human data
are managed under two distinct types i.e.
Characters (A, B, C, +, -, & etc.) or Numbers
(1, 2, 3, 0 etc.).
Database: The database is an organized
collection of information. It is a tool for
organizing, sorting, maintaining, calculating,
combining, and retrieving information.
The above diagram illustrates the organization in the reference of a database. This database manages data
of few persons in terms of Fields and records let's see what are these terminologies?
Field: The field is a name given to a group of similar data. It is a location where we collect information
related to same data. You can assume it as heading of that group. In other words fields are popularly called
as Column and Attribute also.
Record: The record is a collection of information about single entity. Such as "Ram Kumar, 102, Ashok Nagar,
2123456" is all about a person named Ram. So, we can say it is a collection of relative data. The Row & Tuple
are other names given to a record.
Structure: The structure is a collection of fields that organizes an order of data collection. It builds a
template or design in which data will be collected in a database.
Data Model: The structure of database is dependent on data models. A data model is collection of
conceptual tools that describe the data, data relationships, and consistency constraints. The diagram below
describes a list of various data models popular in DBMS world.
• Tables
• Indexes
• Views
• Clusters
• Synonyms
Table
In relational databases and flat file databases, a table is a set of data elements (values) that are organized
using a model of vertical columns (which are identified by their name) and horizontal rows. A table has a
specified number of columns, but can have any number of rows. Each row is identified by the values
appearing in a particular column subset which has been identified as a candidate key.
Table is another term for relations; although there is the difference in that a table is usually a multi-set (bag)
of rows whereas a relation is a set and does not allow duplicates. Besides the actual data rows, tables
generally have associated with them some meta-information, such as constraints on the table or on the
values within particular columns. The data in a table does not have to be physically stored in the database.
Views are also relational tables, but their data are calculated at query time.
Tables are the basic unit of data storage in an Oracle database. Database tables hold all user-accessible data.
Each table has columns and rows. A table that has employee information, for example, can have a column
called employee_number, and each row in that column is an employee number.
Indexes
Indexes are optional structures associated with tables. You can create indexes to increase the performance
of data retrieval. Just as the index in this manual helps you quickly locate specific information, an Oracle
database index provides an access path to table data.
Views
Views are customized presentations of data in one or more tables or other views. A view can also be
considered a stored query. Views do not contain actual data. Rather, they derive their data from the tables
on which they are based, referred to as the base tables of the views. You can query, update, insert into, and
delete views as you can with tables, with some restrictions. If the view is updatable, then all operations
performed on the view actually affect the base tables of the view. Views can provide table security by
restricting access to a predetermined set of rows and columns of a table. They also hide data complexity and
store complex queries.
Clusters
Clusters are groups of one or more tables physically stored together because they share common columns
and are often used together. Because related rows are physically stored together, disk access time improves.
Like indexes, clusters do not affect application design. Whether a table is part of a cluster is transparent to
users and to applications. SQL statements access data stored in a clustered table in the same way that they
access data stored in a non-clustered table.
Synonyms
A synonym is an alias for any table, view, materialized view, sequence, operator, procedure, function,
package, Java class schema object, user-defined object type, or another synonym. A synonym is simply an
alias, so it requires no storage other than its definition in the data dictionary.
User Server
SQL> Select … process process
User
Session
Connection
Session
• Oracle SQL Developer is a graphical tool that lets you browse, create, edit, and delete (drop)
database objects, edit and debug PL/SQL code, run SQL statements and scripts, manipulate and
export data, and create and view reports. With SQL Developer, you can connect to any target Oracle
database schema using standard Oracle database authentication. Once connected, you can perform
operations on objects in the database. You can also connect to schemas for selected third-party
(non-Oracle) databases, such as MySQL, Microsoft SQL Server, and Microsoft Access, view metadata
and data in these databases, and migrate these databases to Oracle.
You must have at least one database connection to use SQL Developer. You can create and test connections
for:
• Multiple databases
• Multiple schemas
SQL Developer automatically reads any connections defined in the tnsnames.ora file on your system. You
can export connections to an XML file. Each additional database connection created is listed in the
Connections navigator hierarchy.
Creating a Database Connection
To create a database connection, start SQL Developer and perform the following steps:
1. On the Connections tabbed page, right-click Connections and select New Connection.
2. Enter the connection name, username, password, host name, and system identifier (SID) or
Service name for the database that you want to connect to.
3. Click Test to make sure that the connection has been set correctly.
4. Click Connect.
On the Oracle tabbed page, at the bottom, enter the following options:
• Hostname: The host system for the Oracle database
• Port: Listener port
• SID: Database name
• Service name: Network service name for a remote database connection
You may want to use the shortcut keys or icons to perform certain tasks such as executing a SQL statement,
running a script, and viewing the history of SQL statements that you have executed. You can use the SQL
Worksheet toolbar that contains icons to perform the following tasks:
1. Execute Statement: Executes
the statement at the cursor in the
Enter SQL Statement box.
2. Run Script: Executes all
statements in the Enter SQL
Statement box using Script Runner.
3. Commit: Writes any changes
to the database and ends the
transaction
4. Rollback: Discards any
changes to the database, without
writing them to the database, and
ends the transaction
5. Cancel: Stops the execution of
current statement.
6. SQL History: Displays a dialog
box with information about the
SQL statements that you have
executed
7. Execute Explain Plan: Generates the execution plan, which you can see by clicking the Explain tab
8. Autotrace: Generates trace information for the statement
9. Clear: Erases the statement or statements in the Enter SQL Statement box
Executing SQL Statements
In SQL Worksheet, you can use the Enter SQL Statement box to enter a single SQL statement or multiple SQL
statements. For a single statement, the semicolon at the end is optional. When you enter the statement, the
SQL keywords are automatically highlighted. To execute a SQL statement, ensure that your cursor is within
the statement and click the Execute Statement icon. Alternatively, you can press the [F9] key. To execute
Here you have to use a user name provided by your Database Administrator. Here we are creating a new
user to work upon. Even for this we have to login into some DBA user using:
Enter user-name: SYSTEM as SYSDBA
Enter Password: MANAGER (will not be displayed on screen)
You will get SQL> prompt as
• Table name
• Column name(s)
• Data types for each column
A table can have up to 254 columns which may have different or same data types and sets of values
(domains), respectively. Possible domains are alphanumeric data (strings), numbers and date formats. A
Table name or Column names must start with any of these alphabet, number, _ , # , $. Better to start with an
alphabet only. Must be 1 to 30 character long and it should not be a reserve word of Oracle – SQL.
Data Type
A data type denotes what type of data we are going to collect into a column or we can say a nature of data
been collected into column. Here is a list of common data type used in SQL.
1 row created.
SQL> /
Enter value for perno: 1004
Enter value for pname: Anil Jain
Enter value for address: 123, 4 lane, Shah Pura
Enter value for city: New Delhi
Enter value for phone: 27878876
Enter value for dob: 12-Dec-71
Enter value for salary: 12500.50
© [email protected] RDBMS Oracle / Page 25 of 125
RDBMS using Oracle
old 1: INSERT INTO person VALUES ( &PERNO, '&PNAME', '&ADDRESS', '&CITY', '&PHONE', '&DOB',
&SALARY)
new 1: INSERT INTO person VALUES ( 1004, 'Anil Jain', '123, 4 lane, Shah Pura', 'New Delhi', '27878876', '12-
Dec-71', 12500.50)
1 row created.
SQL>
DESCRIBE: A describe command is used to display structure of table on screen as:
SQL> desc person
Name Null? Type
----------------------------------------- -------- ---------------------
PERNO NUMBER(5)
PNAME VARCHAR2(20)
ADDRESS VARCHAR2(30)
CITY VARCHAR2(20)
PHONE NUMBER(10)
DOB DATE
SALARY NUMBER(12,2)
SQL>
SELECT: In order to retrieve the information stored in the database, the SQL query language is used. Select
Command is used to query data from tables or views. The basic SELECT statement has four basic parts.
• The word 'SELECT' followed by what you want to see. That is a list of columns or * for all columns.
• The word 'FROM' followed by one or more table names from which we want to view rows.
The above two are mandatory sections of the select command.
• The word 'WHERE' followed by a condition that restrict row display for some criteria.
• The clause 'ORDER BY' followed by sorting criteria i.e. a list of columns used to arrange displayed
rows in a specific order (Ascending or descending).
In its simplest form, a SELECT statement could be written as
SQL> select * from person;
A SELECT statement retrieves information from the database. With a SELECT statement, you can use the
following capabilities:
• Projection: Select the columns in a table that are returned by a query. Select as few or as many of
the columns as required.
• Selection: Select the rows in a table that are returned by a query. Various criteria can be used to
restrict the rows that are retrieved.
• Joining: Bring together data that is stored in different tables by specifying the link between them.
Now I hope that you understand how to create a simple table and to insert rows into it. But Oracle – SQL is
not used only for maintaining simple tables as we have done. They provide us a secured way to maintain our
data using constraints.
Constraints
A constraint is a rule that restricts the values in a database. Oracle Database lets you create six types of
constraints and lets you declare them syntactically in two ways.
• As part of the definition of an individual column or attribute. This is called inline specification or
column level constraints.
• As part of the table definition. This is called out-of-line specification or table level constraint. Table
level constraint can also be applied during modification of table design (Alter Table). It is customary
to use table level constraint for defining composite keys.
Constraints Types
PRIMARY KEY: A primary key constraint combines a NOT NULL constraint and a unique constraint in a single
declaration. It prohibits multiple rows from having the same value in the same column or combination of
columns and prohibits values from being null.
UNIQUE: A unique constraint prohibits multiple rows from having the same value in the same column or
combination of columns but allows some values to be null.
NOT NULL: A NOT NULL constraint prohibits a database value from being null.
FOREIGN KEY: A foreign key constraint requires values in one table to match values in another table.
CHECK: A check constraint requires a value in the database to comply with a specified condition.
REF: A REF column by definition references an object in another object type or in a relational table. A REF
constraint lets you further describe the relationship between the REF column and the object it references.
Defining Constraints
You must have the privileges necessary to issue the statement in which you are defining the constraint. The
NOT NULL constraints must be declared inline. All other constraints can be declared either inline or out of
line. To create a foreign key constraint, in addition, the parent table or view must be in your own schema or
you must have the REFERENCES privilege on the columns of the referenced key in the parent table or view.
Oracle stores the name and the definition of the integrity constraint in the USER_ CONSTRAINTS, ALL_
CONSTRAINTS, and DBA_CONSTRAINTS data dictionary views (in the CONSTRAINT_NAME and SEARCH_
CONDITION columns, respectively).
© [email protected] RDBMS Oracle / Page 28 of 125
RDBMS using Oracle
Oracle Database does not support constraints on columns or attributes whose type is a user-defined object,
nested table, VARRAY, REF, or LOB, with two exceptions:
• NOT NULL constraints are supported for a column or attribute whose type is user-defined object,
VARRAY, REF, or LOB.
• NOT NULL, foreign key, and REF constraints are supported on a column of type REF.
CONSTRAINT constraint_name Specify a name for the constraint. If you omit this identifier, then Oracle
Database generates a name with the form SYS_C<number>.
Before defining constraints let's discuss an example of Library system having three sample tables BOOK,
MEMBER and TRANS. Following are the create table commands to apply constraints on columns of tables.
SQL> create table book
( bcode number(5) constraint bcd_pk primary key,
bname varchar2(20) not null,
author varchar2(20),
price number(10,2),
edition number(4),
status char(2) constraint bksts_chk check (status in('AV','IS','LS','DM')));
Table created.
SQL>create table member
( mcode number(5) constraint mcd_pk primary key,
mname varchar2(20) not null,
address varchar2(20),
phone number(10),
dt_of_mship date,
mfee number(10,2),
bank_acno number(16) constraint bankNo_uk unique,
status char(4) constraint mem_st_chk check (status in('CONT','LEFT','SUSP','TERM')));
Table created.
SQL> create table trans
(trcode number(5) constraint tcd_pk primary key,
bcode number(5) constraint bcd_book_FK references book(bcode),
mcode number(5) constraint mbcd_mem_FK references member(mcode),
idate date,
ldate date,
sdate date,
charges number(10,2) constraint charge_chk check(charges>20));
Table created.
NOTE : See the table list using following select command - SQL>select * from TAB;
SQL> select * from tab;
Note : It's not necessary that you use the data above. You can insert your own data. If you want you can
have data from HR user under sys sysdba. To access data you can also use SQL Developer as shown below.
Operator Purpose
= Equality Check
<> / != / ^= In Equality Check
< Less Than
<= Less Than or Equal to
> Greater Than
>= Greater Than or Equal to
Between … and … Between two values (inclusive)
Not Between … and … Not Between two values (exclusive)
In Check member in list
Not In Check member not in list
Is Null Check is a null value
Few examples:
SELECT * FROM employees WHERE salary = 3000 ;
SELECT * FROM employees WHERE salary != 3000 ;
SELECT * FROM employees WHERE first_name='Julia' ;
SELECT last_name, salary FROM employees WHERE salary <= 3000 ;
SELECT last_name, salary FROM employees WHERE salary BETWEEN 2500 AND 3500 ;
SELECT last_name, salary FROM employees WHERE salary NOT BETWEEN 2500 AND 3500 ;
SELECT last_name FROM employees WHERE last_name BETWEEN 'King' AND 'Smith';
SELECT employee_id, last_name, salary, manager_id FROM employees
WHERE manager_id IN (100, 101, 201) ;
SELECT employee_id, manager_id, department_id FROM employees WHERE
last_name IN ('Hartstein', 'Vargas');
SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL ;
Pattern Matching Using the LIKE Operator
You may not always know the exact value to search for. You can select rows that match a character pattern
by using the LIKE operator. The character pattern–matching operation is referred to as a wildcard search.
Two symbols can be used to construct the search string.
SELECT first_name FROM employees WHERE first_name LIKE 'S%' ;
The SELECT statement in the above example returns the first name from the EMPLOYEES table for any
employee whose first name begins with the letter "S." Note the uppercase "S." Consequently, names
beginning with a lowercase "s" are not returned. The LIKE operator can be used as a shortcut for some
BETWEEN comparisons. The following example displays the last names and hire dates of all employees who
joined between January, 1995 and December, 1995.
SELECT last_name, hire_date FROM employees WHERE hire_date LIKE '%95';
The % and _ symbols can be used in any combination with literal characters. The example below displays the
names of all employees whose last names have the letter "o" as the second character.
SELECT last_name FROM employees WHERE last_name LIKE '_o%' ;
The following example displays the names of all employees whose last name contains only five characters as
it have only five underscores in the pattern.
SELECT last_name FROM employees WHERE last_name LIKE '_ _ _ _ _' ;
When you need to have an exact match for the actual % and _ characters, use the ESCAPE identifier. This
option specifies what the escape character is. If you want to search for strings that contain SA_, you can use
the following SQL statement:
SELECT employee_id, last_name, job_id FROM employees WHERE job_id LIKE '%SA\_%' ESCAPE '\';
Defining Conditions Using the Logical Operators
A logical condition combines the result of two component conditions to produce a single result based on
those conditions or it inverts the result of a single condition. A row is returned only if the overall result of the
condition is true. Three logical operators are available in SQL:
• AND Returns TRUE if both component conditions are true
• OR Returns TRUE if either component condition is true
• NOT Returns TRUE if the condition is false
You can use several conditions in a single WHERE clause using the AND and OR operators as shown below.
SELECT employee_id, last_name, job_id, salary FROM employees
WHERE salary >= 10000 AND job_id LIKE '%MAN%' ;
Function Result
CONCAT('Hello', 'World') HelloWorld
SUBSTR('HelloWorld',1,5) Hello
LENGTH('HelloWorld') 10
INSTR('HelloWorld', 'W') 6
LPAD(salary,10,'*') *****24000
RPAD(salary, 10, '*') 24000*****
REPLACE BLACK and BLUE
('JACK and JUE','J','BL')
TRIM('H' FROM 'HelloWorld') elloWorld
0–49 50–99
If two digits The return date is in The return date is in
of the 0–49 the current century the century before
current the current one
year are: The return date is in The return date is in
50–99 the century after the current century
the current one
Oracle Date Format
This data is stored internally as follows:
CENTURY YEAR MONTH DAY HOUR MINUTE SECOND
19 87 06 17 17 10 43
Centuries and the Year 2000
When a record with a date column is inserted into a table, the century information is picked up from the
SYSDATE function. However, when the date column is displayed on the screen, the century component is not
displayed (by default). The DATE data type always stores year information as a four-digit number internally:
two digits for the century and two digits for the year. For example, the Oracle database stores the year as
1987 or 2004, and not just as 87 or 04.
Obtaining System Date
SYSDATE is a date function that returns the current database server date and time. You can use SYSDATE just
as you would use any other column name. For example, you can display the current date by selecting
SYSDATE from dual table.
SELECT sysdate FROM dual;
Arithmetic with Dates
Because the database stores dates as numbers, you can perform calculations using arithmetic operators
such as addition and subtraction. You can add and subtract number constants as well as dates. You can
perform the following operations:
SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS FROM employees WHERE department_id =
90;
SELECT employee_id, hire_date, MONTHS_BETWEEN (SYSDATE, hire_date) TENURE,
ADD_MONTHS (hire_date, 6) REVIEW, NEXT_DAY (hire_date, 'FRIDAY'), LAST_DAY(hire_date)
FROM employees WHERE MONTHS_BETWEEN (SYSDATE, hire_date) < 100;
Using Round and trunc
SELECT employee_id,hire_date, ROUND(hire_date, 'MONTH'), TRUNC(hire_date, 'MONTH') FROM
employees;
Conversion Functions
In some cases, the Oracle server receives data of one data type where it expects data of a different data
type. When this happens, the Oracle server can automatically convert the data to the expected data type.
This data type conversion can be done implicitly by the Oracle server or explicitly by the user.
Explicit data type conversions are done by using the conversion functions. Conversion functions convert a
value from one data type to another. Generally, the form of the function names follows the convention data
type TO data type. The first data type is the input data type and the second data type is the output.
TO_CHAR (character): This function converts NCHAR, NVARCHAR2, CLOB, or NCLOB data to the database
character set. The value returned is always VARCHAR2. When you use this function to convert a character
LOB into the database character set, if the LOB value to be converted is larger than the target type, then the
database returns an error.
SELECT TO_CHAR('01110') FROM DUAL;
TO_CHAR (datetime): converts a datetime or interval value of DATE, TIMESTAMP, TIMESTAMP WITH TIME
ZONE, or TIMESTAMP WITH LOCAL TIME ZONE datatype to a value of VARCHAR2 datatype in the format
specified by the date format fmt. If you omit fmt, then date is converted to a VARCHAR2.
SELECT TO_CHAR(sysdate, 'DD-MON-YYYY HH24:MI:SSxFF') FROM DUAL;
TO_CHAR (number): converts n to a value of VARCHAR2 datatype, using the optional number format fmt.
The value n can be of type NUMBER, BINARY_FLOAT, or BINARY_DOUBLE. If you omit fmt, then n is
converted to a VARCHAR2 value exactly long enough to hold its significant digits.
SELECT TO_CHAR('01110' + 1) FROM dual;
TO_DATE: converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to a value of DATE datatype.
SELECT TO_DATE('January 15, 1989, 11:00 A.M.', 'Month dd, YYYY, HH:MI A.M.',
'NLS_DATE_LANGUAGE = American') FROM DUAL;
SELECT TO_DATE('January 15, 1989, 11:00 A.M.','Month dd, YYYY, HH:MI A.M.',
'NLS_DATE_LANGUAGE = American') FROM DUAL;
SELECT last_name, hire_date FROM employees WHERE
hire_date = TO_DATE('May 24, 1999', 'fxMonth DD, YYYY');
TO_NUMBER: converts expr to a value of NUMBER datatype. The expr can be a BINARY_DOUBLE value or a
value of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype containing a number in the format specified by
the optional format model fmt.
SELECT TO_NUMBER('-AusDollars100','L9G999D99', ' NLS_NUMERIC_CHARACTERS = '',.''
NLS_CURRENCY = ''AusDollars'' ') "Amount" FROM DUAL;
Date & Time Formats
TO_CHAR converts a datetime data type to a value of VARCHAR2 data type in the format specified by the
format_model. A format model is a character literal that describes the format of datetime stored in a
character string. For example, the datetime format model for the string '11-Nov-1999' is 'DD-Mon-YYYY'. You
can use the TO_CHAR function to convert a date from its default format to the one that you specify.
Note :
• The format model must be enclosed with single quotation marks and is case-sensitive.
More Examples
SELECT TO_CHAR(salary, '$99,999.00') SALARY FROM employees WHERE last_name = 'Ernst';
SELECT last_name employee, TO_CHAR(salary, '$99,990.99') FROM employees WHERE
department_id = 80;
SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY') FROM employees WHERE hire_date <
TO_DATE('01-Jan-90','DD-Mon-RR');
Nesting Functions
Single-row functions can be nested to any depth. Nested functions are evaluated from the innermost level to
the outermost level. Some examples follow to show you the flexibility of these functions.
displays the last names of employees in department 60. The evaluation of the SQL statement involves three
steps:
1. The inner function retrieves the first eight characters of the last name.
Result1 = SUBSTR (LAST_NAME, 1, 8)
2. The outer function concatenates the result with _US.
Result2 = CONCAT(Result1, '_US')
3. The outermost function converts the results to uppercase.
The entire expression becomes the column heading because no column alias was given. Let's look at the
command.
SELECT last_name, UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US')) FROM employees
WHERE department_id = 60;
The example below will display the date of the next Friday that is six months from the hire date. The
resulting date should appear as Friday, August 13th, 1999. Order the results by hire date.
SELECT TO_CHAR(NEXT_DAY(ADD_MONTHS(hire_date, 6), 'FRIDAY'), 'fmDay, Month ddth, YYYY')
"Next 6 Month Review" FROM employees ORDER BY hire_date;
NVL Function
To convert a null value to an actual value, use the NVL function. You can use the NVL function to convert any
data type, but the return value is always the same as the data type of first expression. NVL Conversions for
Various Data types such as date, character, and number. Data types must match:
SELECT NVL(commission_pct,0) FROM employees;
SELECT NVL(hire_date,'01-JAN-97') FROM employees;
SELECT NVL(job_id,'No Job Yet') FROM employees;
SELECT last_name, salary, NVL(commission_pct, 0), (salary*12) + (salary*12*NVL(commission_pct,
0)) AN_SAL FROM employees;
Using the NVL2 Function
The NVL2 function examines the first expression. If the first expression is not null, then the NVL2 function
returns the second expression. If the first expression is null, then the third expression is returned.
SELECT last_name, salary, commission_pct, NVL2(commission_pct, 'SAL+COMM', 'SAL') income
FROM employees WHERE department_id IN (50, 80);
Syntax:
SELECT table1.column, table2.column
FROM table1 [NATURAL JOIN table2]
| [JOIN table2 USING (column_name)]
| [JOIN table2 ON (table1.column_name = table2.column_name)]
| [LEFT|RIGHT|FULL OUTER JOIN table2 ON (table1.column_name = table2.column_name)]
| [CROSS JOIN table2];
In the syntax:
• table1.column denotes the table and the column from which data is retrieved
• NATURAL JOIN joins two tables based on the same column name
• JOIN table2 USING column_name performs an equijoin based on the column name
• JOIN table2 ON table1.column_name = table2.column_name performs an equijoin based on the
condition in the ON clause
• LEFT/RIGHT/FULL OUTER is used to perform outer joins
• CROSS JOIN returns a Cartesian product from the two tables
Qualifying Ambiguous Column Names
When joining two or more tables, you need to qualify the names of the columns with the table name to
avoid ambiguity. Without the table prefixes, the DEPARTMENT_ID column in the SELECT list could be from
either the DEPARTMENTS table or the EMPLOYEES table. It is necessary to add the table prefix to execute
your query. If there are no common column names between the two tables, there is no need to qualify the
columns. However, using the table prefix improves performance, because you tell the Oracle server exactly
where to find the columns.
However, qualifying column names with table names can be time consuming, particularly if the table names
are lengthy. Instead, you can use table aliases. Just as a column alias gives a column another name, a table
alias gives a table another name. Table aliases help to keep SQL code smaller, therefore using less memory.
The table name is specified in full, followed by a space and then the table alias. For example, the EMPLOYEES
table can be given an alias of e, and the DEPARTMENTS table an alias of d etc.
Guidelines
• Table aliases can be up to 30 characters in length, but shorter aliases are better than longer ones.
• If a table alias is used for a particular table name in the FROM clause, then that table alias must be
substituted for the table name throughout the SELECT statement.
© [email protected] RDBMS Oracle / Page 51 of 125
RDBMS using Oracle
• Table aliases should be meaningful.
• The table alias is valid for only the current SELECT statement.
Retrieving Records with Natural Joins
In the example below the LOCATIONS table is joined to the DEPARTMENT table by the LOCATION_ID column,
which is the only column of the same name in both tables. If other common columns were present, the join
would have used them all.
SELECT department_id, department_name, location_id, city
FROM departments NATURAL JOIN locations ;
Natural Joins with a WHERE Clause
Additional restrictions on a natural join are implemented by using a WHERE clause. The following example
limits the rows of output to those with a department ID equal to 20 or 50:
SELECT department_id, department_name, location_id, city FROM departments
NATURAL JOIN locations WHERE department_id IN (20, 50);
Retrieving Records with the USING Clause
In the example below the DEPARTMENT_ID columns in the EMPLOYEES and DEPARTMENTS tables are joined
and thus the LOCATION_ID of the department where an employee works is shown.
SELECT employee_id, last_name, location_id, department_id FROM employees
JOIN departments USING (department_id) ;
When joining with the USING clause, you cannot qualify a column that is used in the USING clause itself.
Furthermore, if that column is used anywhere in the SQL statement, you cannot alias it. For example, in the
query mentioned, you should not alias the location_id column in the WHERE clause because the column is
used in the USING clause. The columns that are referenced in the USING clause should not have a qualifier
(table name or alias) anywhere in the SQL statement. For example, the following statement is valid:
SELECT l.city, d.department_name FROM locations l JOIN departments d USING (location_id)
WHERE location_id = 1400;
Because, other columns that are common in both the tables, but not used in the USING clause, must be
prefixed with a table alias otherwise you get the "column ambiguously defined" error. In the following
statement, manager_id is present in both the employees and departments table and if manager_id is not
prefixed with a table alias, it gives a "column ambiguously defined" error.
The following statement is valid:
SELECT first_name, d.department_name, d.manager_id FROM employees e JOIN departments d
USING (department_id) WHERE department_id = 50;
Retrieving Records with the ON Clause
In the following example, the DEPARTMENT_ID columns in the EMPLOYEES and DEPARTMENTS table are
joined using the ON clause. Wherever a department ID in the EMPLOYEES table equals a department ID in
the DEPARTMENTS table, the row is returned. The table alias is necessary to qualify the matching
column_names.
SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id
FROM employees e JOIN departments d ON (e.department_id = d.department_id);
You can also use the ON clause to join columns that have different names. The parenthesis around the
joined columns as in the example, (e.department_id = d.department_id) is optional. So, even ON
e.department_id = d.department_id will work.
Creating Three-Way Joins with the ON Clause
A three-way join is a join of three tables. In SQL:1999–compliant syntax, joins are performed from left to
right. So, the first join to be performed is EMPLOYEES JOIN DEPARTMENTS. The first join condition can
reference columns in EMPLOYEES and DEPARTMENTS but cannot reference columns in LOCATIONS. The
second join condition can reference columns from all three tables.
SELECT employee_id, city, department_name FROM employees e JOIN departments d
ON d.department_id = e.department_id JOIN locations l ON d.location_id = l.location_id;
The result obtained through codes in the example above can also be accomplished with the USING clause:
© [email protected] RDBMS Oracle / Page 52 of 125
RDBMS using Oracle
SELECT e.employee_id, l.city, d.department_name FROM employees e
JOIN departments d USING (department_id) JOIN locations l USING (location_id);
Applying Additional Conditions to a Join
You can apply additional conditions to the join. The example shown below performs a join on the
EMPLOYEES and DEPARTMENTS tables and, in addition, displays only employees who have a manager ID of
149. To add additional conditions to the ON clause, you can add AND clauses. Alternatively, you can use a
WHERE clause to apply additional conditions.
SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM
employees e
JOIN departments d ON (e.department_id = d.department_id) AND e.manager_id = 149 ;
Or you can use
SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM
employees e
JOIN departments d ON (e.department_id = d.department_id) WHERE e.manager_id = 149 ;
Joining a Table to Itself or Self Join
Sometimes you need to join a table to itself. To find the name of each employee's manager, you need to join
the EMPLOYEES table to itself, or perform a self-join. For example, to find the name of Lorentz's manager,
you need to:
• Find Lorentz in the EMPLOYEES table by looking at the LAST_NAME column
• Find the manager number for Lorentz by looking at the MANAGER_ID column. Lorentz's manager
number is 103.
• Find the name of the manager with EMPLOYEE_ID 103 by looking at the LAST_NAME column.
Hunold's employee number is 103, so Hunold is Lorentz's manager.
In this process, you look in the table twice. The first time you look in the table to find Lorentz in the
LAST_NAME column and the MANAGER_ID value of 103. The second time you look in the EMPLOYEE_ID
column to find 103 and the LAST_NAME column to find Hunold.
SELECT worker.last_name emp, manager.last_name mgr FROM employees worker
JOIN employees manager ON (worker.manager_id = manager.employee_id);
Nonequijoins
A nonequijoin is a join condition containing something other than an equality operator. The relationship
between the EMPLOYEES table and the JOB_GRADES table is an example of a nonequijoin. The SALARY
column in the EMPLOYEES table ranges between the values in the LOWEST_SAL and HIGHEST_SAL columns
of the JOB_GRADES table. Hence, each employee can be graded based on their salary. The relationship is
obtained using an operator other than the equality (=) operator.
SELECT e.last_name, e.salary, j.grade_level FROM employees e JOIN job_grades j
ON e.salary BETWEEN j.lowest_sal AND j.highest_sal;
Returning Records with No Direct Match with Outer Joins
If a row does not satisfy a join condition, the row does not appear in the query result. For example, in the
equijoin condition of EMPLOYEES and DEPARTMENTS tables, department ID 190 does not appear because
there are no employees with that department ID recorded in the EMPLOYEES table. Therefore, instead of
seeing 20 employees in the result set, you see 19 records. To return the department record that does not
have any employees, you can use an outer join.
INNER Versus OUTER Joins
Joining tables with the NATURAL JOIN, USING, or ON clauses results in an inner join. Any unmatched rows
are not displayed in the output. To return the unmatched rows, you can use an outer join. An outer join
returns all rows that satisfy the join condition and also returns some or all of those rows from one table for
which no rows from the other table satisfy the join condition.
There are three types of outer joins:
• LEFT OUTER
SELECT e.last_name, e.department_id, d.department_name FROM employees e
Create a role:
CREATE ROLE manager;
Grant privileges to a role:
GRANT create table, create view TO manager;
Grant a role to users:
GRANT manager TO BELL, KOCHHAR;
© [email protected]
com DBMS Oracle / Page 67 of 125
RDBM
RDBMS using Oracle
Changing User Password
The DBA creates your user account and initializes your password. You can change your password by using
the ALTER USER statement.
ALTER USER demo IDENTIFIED BY employ;
Note: SQL*Plus has a PASSWORD command (PASSW) that can be used to change the password of a user
when the user is logged in. This command is not available in SQL Developer.
Object Privileges
An object privilege is a privilege or right to perform a particular action on a specific table, view, sequence, or
procedure. Each object has a particular set of grantable privileges. The table in the example lists the
privileges for various objects. Note that the only privileges that apply to a sequence are SELECT and ALTER.
UPDATE, REFERENCES, and INSERT can be restricted by specifying a subset of updatable columns.
Object privileges vary from object to object.
An owner has all the privileges on the object.
An owner can give specific privileges on that owner's object.
Syntax
GRANT object_priv [(columns)] ON object TO {user|role|PUBLIC} [WITH GRANT OPTION];
A SELECT privilege can be restricted by creating a view with a subset of columns and granting the SELECT
privilege only on the view. A privilege granted on a synonym is converted to a privilege on the base table
referenced by the synonym.
Note: With the REFERENCES privilege, you can ensure that other users can create FOREIGN KEY constraints
that reference your table.
Few Examples
Grant query privileges on the EMPLOYEES table:
GRANT select ON employees TO demo;
Grant privileges to update specific columns to users and roles:
GRANT update (department_name, location_id) ON departments TO demo, manager;
Passing On Your Privileges
Give a user authority to pass along privileges:
GRANT select, insert ON departments TO demo WITH GRANT OPTION;
Allow all users on the system to query data from Alice's DEPARTMENTS table:
GRANT select ON alice.departments TO PUBLIC;
Confirming Granted Privileges
If you attempt to perform an unauthorized operation, such as deleting a row from a table for which you do
not have the DELETE privilege, the Oracle server does not permit the operation to take place. If you receive
the Oracle server error message "Table or view does not exist," then you have done either of the following:
• Named a table or view that does not exist.
• Attempted to perform an operation on a table or view for which you do not have the appropriate
privilege.
The data dictionary is organized in tables and views and contains information about the database. You can
access the data dictionary to view the privileges that you have. The table in the example describes various
data dictionary views.
Data Dictionary View Description
ROLE_SYS_PRIVS System privileges granted to roles
ROLE_TAB_PRIVS Table privileges granted to roles
USER_ROLE_PRIVS Roles accessible by the user
USER_SYS_PRIVS System privileges granted to the user
USER_TAB_PRIVS_MADE Object privileges granted on the user's
© [email protected] RDBMS Oracle / Page 68 of 125
RDBMS using Oracle
objects
Note: The ALL_TAB_PRIVS_MADE dictionary view describes all the object grants made by the user or made
on the objects owned by the user.
Revoking Object Privileges
You use the REVOKE statement to revoke privileges granted to other users. Privileges granted to others
through the WITH GRANT OPTION clause are also revoked.
Syntax:
REVOKE {privilege [, privilege...]|ALL}
ON object
FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];
Revoke the SELECT and INSERT privileges given to the demo user on the DEPARTMENTS table.
REVOKE select, insert ON departments FROM demo;
If a user is granted a privilege with the WITH GRANT OPTION clause, that user can also grant the privilege
with the WITH GRANT OPTION clause, so that a long chain of grantees is possible, but no circular grants
(granting to a grant ancestor) are permitted. If the owner revokes a privilege from a user who granted the
privilege to other users, then the revoking cascades to all the privileges granted.
For example, if user A grants a SELECT privilege on a table to user B including the WITH GRANT OPTION
clause, user B can grant to user C the SELECT privilege with the WITH GRANT OPTION clause as well, and user
C can then grant to user D the SELECT privilege. If user A revokes privileges from user B, then the privileges
granted to users C and D are also revoked.
Database Objects
There are several other objects in a database in addition to tables such as views, sequences, indexes, and
synonyms.
• With views, you can present and hide data from the tables.
• Many applications require the use of unique numbers as primary key values. You can either build
code into the application to handle this requirement or use a sequence to generate unique numbers.
• If you want to improve the performance of data retrieval queries, you should consider creating an
index. You can also use indexes to enforce uniqueness on a column or a collection of columns.
• You can provide alternative names for objects by using synonyms.
What Is a View?
You can present logical subsets or combinations of data by creating views of tables. A view is a logical table
based on a table or another view. A view contains no data of its own, but is like a window through which
data from tables can be viewed or changed. The tables on which a view is based are called base tables. The
view is stored as a SELECT statement in the data dictionary.
Advantages of Views
• Views restrict access to the data because it displays selected columns from the table.
• Views can be used to make simple queries to retrieve the results of complicated queries. For
example, views can be used to query information from multiple tables without the user knowing
how to write a Join statement.
• Views provide data independence for ad hoc users and application programs. One view can be used
to retrieve data from several tables.
• Views provide groups of users access to data according to their particular criteria.
© [email protected] RDBMS Oracle / Page 69 of 125
RDBMS using Oracle
There are two classifications for views:
• Simple Views
• Complex Views
The basic difference is related to the DML (INSERT, UPDATE, and DELETE) operations.
A simple view is one that
• Derives data from only one table
• Contains no functions or groups of data
• Can perform DML operations through the view
A complex view is one that:
• Derives data from many tables
• Contains functions or groups of data
• Does not always allow DML operations through the view
Syntax
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
Create the EMPVU80 view, which contains details of the employees in department 80:
CREATE VIEW empvu80 AS
SELECT employee_id, last_name, salary FROM employees
WHERE department_id = 80;
Describe the structure of the view by using the SQL*Plus DESCRIBE command:
DESCRIBE empvu80;
You can control the column names by including column aliases in the subquery.
The example below creates a view containing the employee number (EMPLOYEE_ID) with the alias
ID_NUMBER, name (LAST_NAME) with the alias NAME, and annual salary (SALARY) with the alias
ANN_SALARY for every employee in department 50.
CREATE VIEW salvu50 AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY FROM employees WHERE department_id = 50;
Alternatively, you can use an alias after the CREATE statement and before the SELECT subquery. The number
of aliases listed must match the number of expressions selected in the subquery.
CREATE OR REPLACE VIEW salvu50 (ID_NUMBER, NAME, ANN_SALARY)
AS SELECT employee_id, last_name, salary*12 FROM employees
WHERE department_id = 50;
Retrieving Data from a View
You can retrieve data from a view as you would from any table. You can display either the contents of the
entire view or just specific rows and columns.
SELECT * FROM salvu50;
Modifying a View
With the OR REPLACE option, a view can be created even if one exists with this name already, thus replacing
the old version of the view for its owner. This means that the view can be altered without dropping,
re-creating, and regranting object privileges. When assigning column aliases in the CREATE OR REPLACE
VIEW clause, remember that the aliases are listed in the same order as the columns in the subquery.
CREATE OR REPLACE VIEW empvu80 (id_number, name, sal, department_id) AS
SELECT employee_id, first_name || ' ' || last_name, salary, department_id
FROM employees
WHERE department_id = 80;
Synonyms
Synonyms are database objects that enable you to call a table by another name. You can create synonyms to
give an alternative name to a table. To refer to a table that is owned by another user, you need to prefix the
table name with the name of the user who created it, followed by a period. Creating a synonym eliminates
the need to qualify the object name with the schema and provides you with an alternative name for a table,
view, sequence, procedure, or other objects. This method can be especially useful with lengthy object
names, such as views.
Syntax:
CREATE [PUBLIC] SYNONYM synonym FOR object;
Example:
CREATE SYNONYM d_sum FOR dept_sum_vu;
Drop a Synonym
DROP SYNONYM d_sum;
The above diagram shows the PL/SQL execution environment in the Oracle database server. A PL/SQL block
contains procedural statements and SQL statements. When you submit the PL/SQL block to the server, the
PL/SQL engine first parses the block. The PL/SQL engine identifies the procedural statements and the SQL
statements. It passes the procedural
procedural statements to the procedural statement executor and the SQL
statements to the SQL statement executor individually.
The diagram shows the PL/SQL engine within the database server. The Oracle application development tools
can also contain a PL/SQL engine.
engine. The tool passes the blocks to its local PL/SQL engine. Therefore, all
procedural statements are executed locally and only the SQL statements are executed in the database. The
engine used depends on where the PL/SQL block is being invoked from.
Benefits of PL/SQL
Integration of procedural constructs with SQL: The most important advantage of PL/SQL is the integration
of procedural constructs with SQL. SQL is a nonprocedural language. When you issue a SQL command, your
command tells the database server what to do. However, you cannot specify how to do it. PL/SQL integrates
control statements and conditional statements with SQL, giving you better control of your SQL statements
and their execution.
Improved performance: Without PL/SQL, you would not be able to logically combine SQL statements as one
unit. If you have designed an application containing forms, you may have many different forms with fields in
each form. When a form submits the data, you
may have to execute a number of SQL
statements. SQL statements nts are sent to the
database one at a time. This results in many
network trips and one call to the database for
each SQL statement, thereby increasing network
traffic and reducing performance (especially in a
client/server model).
With PL/SQL, you can combine
bine all these SQL
statements into a single program unit. The
© [email protected]
com DBMS Oracle / Page 75 of 125
RDBM
RDBMS using Oracle
application can send the entire block to the database instead of sending the SQL statements one at a time.
This significantly reduces the number of database calls. As the example illustrates, if the application is SQL
intensive, you can use PL/SQL blocks to group SQL statements before sending them to the Oracle database
server for execution.
Modularized program development: A basic unit in all PL/SQL programs is the block. Blocks can be in a
sequence or they can be nested in other blocks. Modularized program development has the following
advantages:
If you need you can store current PL/SQL block into a script file for future uses by issuing Save command.
Next time you can invoke it using Get command or Run it using @filename.
© [email protected] RDBMS Oracle / Page 78 of 125
RDBMS using Oracle
Lexical Units in a PL/SQL Block
Lexical units include letters, numerals, special characters, tabs, spaces, returns, and symbols.
Identifiers: Identifiers are the names given to PL/SQL objects. You have learned to identify valid and invalid
identifiers. Recall that keywords cannot be used as identifiers.
Quoted identifiers:
• Make identifiers case sensitive
• Include characters such as spaces
• Use reserved words
Examples:
"begin date" DATE;
"end date" DATE;
"exception thrown" BOOLEAN DEFAULT TRUE;
All subsequent usage of these variables should have double quotation marks. However, use of quoted
identifiers is not recommended.
Delimiters: Delimiters are symbols that have special meaning. You have already learned that the semicolon
(;) is used to terminate a SQL or PL/SQL statement. Therefore, ; is an example of a delimiter.
Literals: Any value that is assigned to a variable is a literal. Any character, numeral, Boolean, or date value
that is not an identifier is a literal. Literals are classified as:
• Character literals: All string literals have the data type CHAR or VARCHAR2 and are, therefore, called
character literals (for example, John, and 12C).
• Numeric literals: A numeric literal represents an integer or real value (for example, 428 and 1.276).
• Boolean literals: Values that are assigned to Boolean variables are Boolean literals. TRUE, FALSE, and
NULL are Boolean literals or keywords.
Comments: It is good programming practice to explain what a piece of code is trying to achieve. When you
include the explanation in a PL/SQL block, the compiler cannot interpret these instructions. There should be
a way in which you can indicate that these instructions need not be compiled. Comments are mainly used for
this purpose. Any instruction that is commented is not interpreted by the compiler. There are two types of
comments are often used in PL/SQL.
• Declare and initialize them in the declaration section: You can declare variables in the declarative
part of any PL/SQL block, subprogram, or package. Declarations allocate storage space for a value,
specify its data type, and name the storage location so that you can reference it. Declarations can
also assign an initial value and impose the NOT NULL constraint on the variable. Forward references
are not allowed. You must declare a variable before referencing it in other statements, including
other declarative statements.
• Use them and assign new values to them in the executable section: In the executable section, the
existing value of the variable can be replaced with the new value.
• Pass them as parameters to PL/SQL subprograms: Subprograms can take parameters. You can pass
variables as parameters to subprograms.
• Use them to hold the output of a PL/SQL subprogram: Variables can be used to hold the value that is
returned by a function.
Syntax:
identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];
Examples:
DECLARE
v_hiredate DATE;
v_deptno NUMBER(2) NOT NULL := 10;
v_location VARCHAR2(13) := 'Atlanta';
c_comm CONSTANT NUMBER := 1400;
Some Simple PL/SQL Blocks
declare declare
pa number(10,2); rate number(10,2); qty number(4);
dr number(3); amt number(10,2); dis number(10,2);
disamt number(10,2); netamt number(10,2);
ri number(6,2);
begin
si number(12,2);
rate:=1200; qty:=4; dis:=10;
begin amt:=rate * qty; disamt:= amt * dis/100;
pa := 5000; netamt:= amt - disamt;
dr :=2; dbms_output.put_line('Rate : '|| rate||'
Quantity : '||qty);
ri :=2.5;
dbms_output.put_line('Discount Rate : ' ||dis||'
si := pa * dr * ri / 100 ; Discount Amount : '||disamt);
dbms_output.put_line('Simple Interest : ' || si); dbms_output.put_line('Amount : '||amt||' Net
end; Amount : '||netamt);
/ end;
/
Operator Operation
** Exponentiation
+, - Identity, negation
*, / Multiplication, division
+, -, || Addition, subtraction, concatenation
=, <, >, <=, >=, <>, !=, ~=, ^=,
Comparison
IS NULL, LIKE, BETWEEN, IN
NOT Logical negation
AND Conjunction
OR Inclusion
When working with nulls, you can avoid some common mistakes by keeping in mind the following rules:
The MERGE statement inserts or updates rows in one table by using data from another table. Each row is
inserted or updated in the target table depending on an equijoin condition. The example shown matches
the employee_id in the copy_emp table to the employee_id in the employees table. If a match is found, the
row is updated to match the row in the employees table. If the row is not found, it is inserted into the
copy_emp table.
CASE Statement
Recall the use of the IF statement. You may include n number of PL/SQL statements in the THEN clause and
also in the ELSE clause. Similarly, you can include statements in the CASE statement. The CASE statement is
more readable compared to multiple IF and ELSIF statements.
How a CASE Expression Differs from a CASE Statement
A CASE expression evaluates the condition and returns a value, whereas a CASE statement evaluates the
condition and performs an action. A CASE statement can be a complete PL/SQL block.
• CASE statements end with END CASE;
• CASE expressions end with END;
Example :
DECLARE
v_deptid NUMBER;
v_deptname VARCHAR2(20);
v_emps NUMBER;
v_mngid NUMBER:= 108;
BEGIN
CASE v_mngid
WHEN 108 THEN
SELECT department_id, department_name INTO v_deptid, v_deptname
FROM departments WHERE manager_id=108;
SELECT count(*) INTO v_emps FROM employees WHERE department_id=v_deptid;
WHEN 200 THEN
...
END CASE;
DBMS_OUTPUT.PUT_LINE ('You are working in the '|| deptname||' department.
There are '||v_emps ||' employees in this department');
END;
/
Iterative Control: LOOP Statements
PL/SQL provides several facilities to structure loops to repeat a statement or sequence of statements
multiple times. Loops are mainly used to execute statements repeatedly until an exit condition is reached. It
is mandatory to have an exit condition in a loop; otherwise, the loop is infinite.
Looping constructs are the second type of control structure. PL/SQL provides the following types of loops:
© [email protected] RDBMS Oracle / Page 91 of 125
RDBMS using Oracle
• Basic loop that performs repetitive actions without overall conditions
• FOR loops that perform iterative actions based on a count
• WHILE loops that perform iterative actions based on a condition
An EXIT statement can be used to terminate loops. A basic loop must have an EXIT.
SRNO Syntax Example
1. LOOP BEGIN
statement1; Loop
... DBMS_OUTPUT.PUT_LINE('India');
END LOOP; End Loop;
End;
NOTE : The above loop statement will be an infinite loop because there is no limitation is given for execution
of iterations. There must be a condition to control the execution of a loop control statements as shown
below.
2. LOOP DECLARE
statement1; cnt number(3):=1;
... BEGIN
EXIT ; LOOP
END LOOP; DBMS_OUTPUT.PUT_LINE('India');
cnt := cnt + 1;
IF cnt >10 THEN
EXIT;
END IF;
END LOOP;
END;
/
3. LOOP DECLARE
statement1; cnt number(3):=1;
... BEGIN
EXIT [WHEN condition]; LOOP
END LOOP; DBMS_OUTPUT.PUT_LINE('India');
cnt := cnt + 1;
EXIT WHEN cnt >10 ;
END LOOP;
END;
/
Another Example
DECLARE
v_countryid locations.country_id%TYPE := 'CA';
v_loc_id locations.location_id%TYPE;
v_counter NUMBER(2) := 1;
v_new_city locations.city%TYPE := 'Montreal';
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = v_countryid;
LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + v_counter), v_new_city, v_countryid);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 3;
END LOOP;
END;
/
4. WHILE condition LOOP DECLARE
statement1; i NUMBER(3):=1;
statement2; BEGIN
... WHILE i<=10 LOOP
© [email protected] RDBMS Oracle / Page 92 of 125
RDBMS using Oracle
END LOOP; dbms_output.put_line(i);
i:=i+1;
END LOOP;
END;
/
Another Example :
DECLARE
v_countryid locations.country_id%TYPE := 'CA';
v_loc_id locations.location_id%TYPE;
v_new_city locations.city%TYPE := 'Montreal';
v_counter NUMBER := 1;
BEGIN
SELECT MAX(location_id) INTO v_loc_id FROM locations WHERE country_id = v_countryid;
WHILE v_counter <= 3 LOOP
INSERT INTO locations(location_id, city, country_id)
VALUES((v_loc_id + v_counter), v_new_city, v_countryid);
v_counter := v_counter + 1;
END LOOP;
END;
/
5. FOR counter IN [REVERSE] BEGIN
lower_bound..upper_bound LOOP FOR i IN 1..10 LOOP
statement1; dbms_output.put_line(i);
statement2; END LOOP;
... END;
END LOOP; /
Notes:
• No Need to declare loop counter/index variable. It is declared implicitly as an integer.
• No need to specify the condition. Maintained implicitly using Lower and Upper bounds.
• No need to do increment.
• The .. is a range operator.
• Reference the counter within the loop only; it is undefined outside the loop.
• Do not reference the counter as the target of an assignment.
• Neither loop bound should be NULL.
DECLARE Reverse for loop
v_lower NUMBER := 1; BEGIN
v_upper NUMBER := 100; FOR i IN REVERSE 1..10 LOOP
BEGIN dbms_output.put (i);
FOR i IN v_lower..v_upper LOOP END LOOP;
dbms_output.put_line(i); dbms_output.put _line(' ');
END LOOP; END;
END; /
/ Output : 10 9 8 7 6 5 4 3 2 1
• Implicit: An implicit cursor is created and managed by the Oracle server. You do not have access to
it. The Oracle server creates such a cursor when it has to execute a SQL statement.
• Explicit: As a programmer, you may want to retrieve multiple rows from a database table, have a
pointer to each row that is retrieved, and work on the rows one at a time. In such cases, you can
declare cursors explicitly depending on your business requirements. A cursor that is declared by
programmers is called an explicit cursor. You declare such a cursor in the declarative section of a
PL/SQL block.
SQL Cursor Attributes for Implicit Cursors
SQL cursor attributes enable you to evaluate what happened when an implicit cursor was last used. Use
these attributes in PL/SQL statements but not in SQL statements. You can test following attributes
SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement returned at
least one row
SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement did not
return even one row
SQL%ROWCOUNT An integer value that represents the number of rows affected by the most recent SQL
statement
These attributes can be checked in the executable section of a block to gather information after the
appropriate DML command executes. These cursor attributes are used with implicit cursors that are
automatically created by PL/SQL and for which you do not know the names. Therefore, you use SQL instead
of the cursor name.
Example:
DECLARE DECLARE
v_rows_deleted VARCHAR2(30) nr number(4);
v_empno employees.employee_id%TYPE := 176; BEGIN
BEGIN UPDATE emp2 SET sal=sal*1.15 WHERE sal>1500;
DELETE FROM employees nr := sql%rowcount;
WHERE employee_id = v_empno; IF sql%rowcount>0 THEN
v_rows_deleted := (SQL%ROWCOUNT || dbms_output.put_line(nr|| ' rows affected');
' row deleted.'); ELSE
DBMS_OUTPUT.PUT_LINE (v_rows_deleted); dbms_output.put_line('No Such Record');
END; END IF;
END;
by the query are called the active set and are now available
for fetching.
Fetch a row.
3. Fetch data from the cursor. after each fetch you test the Cursor
pointer
cursor for any existing row. If there are no more rows to
process, you must close the cursor.
Cursor
Close the cursor.
4. Close thee cursor. The CLOSE statement releases the active pointer
© [email protected]
com BMS Oracle / Page 105 of 125
RDBM
RDBMS using Oracle
%ROWCOUNT and %NOTFOUND Example Using %ISOPEN Attribute Example
DECLARE …
CURSOR c_emp_cursor IS SELECT employee_id, IF NOT c_emp_cursor%ISOPEN THEN
last_name FROM employees; OPEN c_emp_cursor;
v_emp_record c_emp_cursor%ROWTYPE; END IF;
BEGIN LOOP
OPEN c_emp_cursor; FETCH c_emp_cursor
LOOP ...
FETCH c_emp_cursor INTO v_emp_record; Cursor FOR Loops Using Subqueries Example
EXIT WHEN c_emp_cursor%ROWCOUNT > 10 OR BEGIN
c_emp_cursor%NOTFOUND; FOR emp_record IN (SELECT employee_id,
DBMS_OUTPUT.PUT_LINE( last_name
FROM employees WHERE department_id =30)
v_emp_record.employee_id
||' '||v_emp_record.last_name); LOOP
• Declarative section: Subprograms can have an optional declarative section. However, unlike
anonymous blocks, the declarative section of a subprogram does not start with the DECLARE
keyword. The optional declarative section follows the IS or AS keyword in the subprogram
declaration.
• Executable section: This is the mandatory section of the subprogram, which contains the
implementation of the business
business logic. Looking at the code in this section, you can easily determine
the business functionality of the subprogram. This section begins and ends with the BEGIN and END
keywords, respectively.
• Exception section: This is an optional section that is included
included to handle exceptions.
Differences Between Anonymous Blocks and Subprograms
© [email protected]
com BMS Oracle / Page 107 of 125
RDBM
RDBMS using Oracle
Note: When you create any object (such as a table, procedure, function, and so on), the entries are made to
the user_objects table. When the code in the example is executed successfully, you can check the
user_objects table by issuing the following command:
SELECT object_name,object_type FROM user_objects;
Procedure Syntax :
CREATE [OR REPLACE] PROCEDURE procedure_name
[(argument1 [mode1] datatype1,
argument2 [mode2] datatype2,
. . .)]
IS|AS
procedure_body;
Example :
...
CREATE PROCEDURE add_dept IS
v_dept_id dept.department_id%TYPE;
v_dept_name dept.department_name%TYPE;
BEGIN
v_dept_id:=280;
v_dept_name:='ST-Curriculum';
INSERT INTO dept(department_id,department_name) VALUES(v_dept_id,v_dept_name);
DBMS_OUTPUT.PUT_LINE(' Inserted '|| SQL%ROWCOUNT ||' row ');
END;
Examine the code in the example. The add_dept procedure inserts a new department with department ID
280 and department name ST-Curriculum. The procedure declares two variables, dept_id and dept_name, in
the declarative section. The declarative section of a procedure starts immediately after the procedure
declaration and does not begin with the DECLARE keyword. The procedure uses the implicit cursor attribute
or the SQL%ROWCOUNT SQL attribute to verify whether the row was successfully inserted.
SQL%ROWCOUNT should return 1 in this case.
The source of the procedure is stored in the user_source table. You can check the source for the procedure
by issuing the following command:
SELECT * FROM user_source WHERE name='ADD_DEPT';
Invoking the Procedure
You have to include the call to the procedure in the executable section of the anonymous block. Similarly,
you can invoke the procedure from any application, such as a Forms application, a Java application, and so
on. The SELECT statement in the code checks to see whether the row was successfully inserted. You can also
invoke a procedure with the SQL statement CALL <procedure_name>.
BEGIN
add_dept;
END;
/
SELECT department_id, department_name FROM dept WHERE department_id=280;
Example:
CREATE PROCEDURE add_department(name VARCHAR2, mgr NUMBER, loc NUMBER) IS
BEGIN
INSERT INTO DEPARTMENTS (department_id, department_name, manager_id, location_id)
VALUES (DEPARTMENTS_SEQ.NEXTVAL, name, mgr, loc);
DBMS_OUTPUT.PUT_LINE('Added Dept: '||name);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Err: adding dept: '||name);
END;
/
CREATE PROCEDURE create_departments IS
BEGIN
add_department('Media', 100, 1800);
add_department('Editing', 99, 1800);
add_department('Advertising', 101, 1800);
END;
/
The Editing department with manager_id of 99 is not inserted because of a foreign key integrity constraint
violation on the manager_id.
Removing Procedures
When a stored procedure is no longer required, you can use the DROP PROCEDURE SQL statement to
remove it.
DROP PROCEDURE procedurename;
A procedure containing a single OUT parameter would be better rewritten as a function returning the value.
You create a function when you want to compute a value that must be returned to the calling environment.
A function can contain zero or more parameters that are transferred from the calling environment.
Functions typically return only a single value, and the value is returned through a RETURN statement. The
functions used in SQL statements should not use OUT or IN OUT mode parameters. Although a function
using output parameters can be used in a PL/SQL procedure or block, it cannot be used in SQL statements.
• A specification
• A body (optional)
The package itself cannot be called, parameterized, or nested. After writing and compiling, the contents can
be shared with many applications. When a PL/SQL-packaged construct is referenced for the first time, the
whole package is loaded into memory. Subsequent access to constructs in the same package do not require
disk input/output (I/O).
Components of a PL/SQL Package
You create a package in two parts:
The package specification is the interface to your applications. It declares the public types, variables,
constants, exceptions, cursors, and subprograms available for use. The package specification may also
include PRAGMAs, which are directives to the compiler.
The package body defines its own subprograms and must fully implement subprograms declared in the
specification part. The package body may also define PL/SQL constructs, such as types, variables, constants,
exceptions, and cursors.
Public components are declared in the package specification. The specification defines a public application
programming interface (API) for users of package features and functionality—that is, public components can
be referenced from any Oracle server environment that is external to the package.
Private components are placed in the package body and can be referenced only by other constructs within
the same package body. Private components can reference the package public components.
Note: If a package specification does not contain subprogram declarations, then there is no requirement for
a package body.
Developing PL/SQL Packages
To develop a package, perform the following steps:
1. Edit the text for the specification by using the CREATE PACKAGE statement within a SQL script file.
Edit the text for the body by using the CREATE PACKAGE BODY statement within a SQL script file.
2. Load the script files into a tool such as SQL*Plus.
3. Execute the script files to create (that is, to compile and store) the package and package body in the
database.
4. Execute any public construct within the package specification from an Oracle server environment.
The Oracle server stores the specification and body of a package separately. This enables you to change the
implementation of a program construct in the package body without invalidating other schema objects that
call or reference the program construct.
Creating the Package Specification
To create packages, you declare all public constructs within the package specification. Specify the OR
REPLACE option, if overwriting an existing package specification. Initialize a variable with a constant value or
formula within the declaration, if required; otherwise, the variable is initialized implicitly to NULL.
• package_name specifies a name for the package that must be unique among objects within the
owning schema. Including the package name after the END keyword is optional.
• public type and variable declarations declares public variables, constants, cursors, exceptions, user-
defined types, and subtypes.
• subprogram specification specifies the public procedure or function declarations.
Example:
CREATE OR REPLACE PACKAGE comm_pkg IS
std_comm NUMBER := 0.10;
PROCEDURE reset_comm(new_comm NUMBER);
END comm_pkg;
/
The example above creates a package called comm_pkg used to manage business processing rules for
commission calculations.
The std_comm public (global) variable is declared to hold a maximum allowable percentage commission for
the user session, and it is initialized to 0.10 (that is, 10%).
The reset_comm public procedure is declared to accept a new commission percentage that updates the
standard commission percentage if the commission validation rules are accepted. The validation rules for
resetting the commission are not made public and do not appear in the package specification. The validation
rules are managed by using a private function in the package body.
Creating the Package Body
Create a package body to define and implement all public subprograms and supporting private constructs.
When creating a package body, perform the following steps:
• Specify the OR REPLACE option to overwrite an existing package body.
• Define the subprograms in an appropriate order. The basic principle is that you must declare a
variable or subprogram before it can be referenced by other components in the same package body.
It is common to see all private variables and subprograms defined first and the public subprograms
defined last in the package body.
• Complete the implementation for all procedures or functions declared in the package specification
within the package body.
Syntax:
CREATE [OR REPLACE] PACKAGE BODY package_name IS|AS
private type and variable declarations
subprogram bodies
[BEGIN initialization statements]
END [package_name];
The following are definitions of items in the package body syntax:
• package_name specifies a name for the package that must be the same as its package specification.
Using the package name after the END keyword is optional.
When the triggering DML statement affects many rows, the statement trigger fires exactly once, and the row
trigger fires once for every row affected by the statement.
UPDATE employees SET salary = salary * 1.1 WHERE department_id = 30;
The SQL statement in the example causes a row-levellevel trigger to fire a number of times equal to the number
numbe
of rows that satisfy the WHERE clause (that is, the number of employees reporting to department 30).
© [email protected]
com BMS Oracle / Page 121 of 125
RDBM
RDBMS using Oracle
Triggering Event Types
The triggering event or statement can be an INSERT, UPDATE, or DELETE statement on a table. When the
triggering event is an UPDATE statement, you can include a column list to identify which columns must be
changed to fire the trigger. You cannot specify a column list for an INSERT or for a DELETE statement because
it always affects entire rows.
. . . UPDATE OF salary . . .
The triggering event can contain one, two, or all three of these DML operations.
. . . INSERT or UPDATE or DELETE
. . . INSERT or UPDATE OF job_id . . .
The trigger body defines the action—that is, what needs to be done when the triggering event is issued. The
PL/SQL block can contain SQL and PL/SQL statements, and can define PL/SQL constructs such as variables,
cursors, exceptions, and so on. You can also call a PL/SQL procedure or a Java procedure. The size of a trigger
cannot be greater than 32 KB.
Creating a DML Statement Trigger
In the example below, the SECURE_EMP database trigger is a BEFORE statement trigger that prevents the
INSERT operation from succeeding if the business condition is violated. In this case, the trigger restricts
inserts into the EMPLOYEES table during certain business hours, Monday through Friday.
If a user attempts to insert a row into the EMPLOYEES table on Saturday, then the user sees an error
message, the trigger fails, and the triggering statement is rolled back. Remember that the
RAISE_APPLICATION_ERROR is a server-side built-in procedure that returns an error to the user and causes
the PL/SQL block to fail. When a database trigger fails, the triggering statement is automatically rolled back
by the Oracle server.
CREATE OR REPLACE TRIGGER secure_emp
BEFORE INSERT ON employees BEGIN
IF (TO_CHAR(SYSDATE,'DY') IN ('SAT','SUN')) OR (TO_CHAR(SYSDATE,'HH24:MI')
NOT BETWEEN '08:00' AND '18:00') THEN
RAISE_APPLICATION_ERROR(-20500, 'You may insert into EMPLOYEES table only during '
||' business hours.');
END IF;
END;
/
Combining Triggering Events
You can combine several triggering events into one by taking advantage of the special conditional predicates
INSERTING, UPDATING, and DELETING within the trigger body.
Example
Create one trigger to restrict all data manipulation events on the EMPLOYEES table to certain business hours,
Monday through Friday.
CREATE OR REPLACE TRIGGER secure_emp
BEFORE INSERT OR UPDATE OR DELETE
ON employees
BEGIN
IF (TO_CHAR(SYSDATE,'DY') IN ('SAT','SUN')) OR (TO_CHAR(SYSDATE,'HH24')
NOT BETWEEN '08' AND '18') THEN
IF DELETING THEN
RAISE_APPLICATION_ERROR(-20502,'You may delete from EMPLOYEES'
© [email protected] RDBMS Oracle / Page 122 of 125
RDBMS using Oracle
|| ' table only during business hours.');
ELSIF INSERTING THEN
RAISE_APPLICATION_ERROR(-20500,'You may insert into EMPLOYEES table'
|| ' only during business hours.');
ELSIF UPDATING('SALARY') THEN
RAISE_APPLICATION_ERROR(-20503, 'You may '
|| 'update SALARY only during business hours.');
ELSE
RAISE_APPLICATION_ERROR(-20504,'You may'
|| ' update EMPLOYEES table only during normal hours.');
END IF;
END IF;
END;
/
Creating a DML Row Trigger
You can create a BEFORE row trigger in order to prevent the triggering operation from succeeding if a certain
condition is violated. In the example below, a trigger is created to allow certain employees to be able to earn
a salary of more than 15,000.
CREATE OR REPLACE TRIGGER restrict_salary
BEFORE INSERT OR UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
IF NOT (:NEW.job_id IN ('AD_PRES', 'AD_VP')) AND :NEW.salary > 15000 THEN
RAISE_APPLICATION_ERROR (-20202, 'Employee cannot earn more than $15,000.');
END IF;
END;
/
Using OLD and NEW Qualifiers
Within a ROW trigger, reference the value of a column before and after the data change by prefixing it with
the OLD and NEW qualifiers.