You are on page 1of 42

TABLE OF CONTENTS

1. BASIC SQL STATEMENT..................................................................................................................4
Demo Tables (EMP & DEPT)...........................................................................................................4
Basic SQL statement.........................................................................................................................4
Simple rules of SQL statements.........................................................................................................4
Eliminating Duplicate Rows.............................................................................................................5
SQL versus SQL*Plus........................................................................................................................5

2. WHERE, ORDER BY CLAUSES...........................................................................................................5
IS NULL Operator.............................................................................................................................5
BETWEEN Operator.........................................................................................................................6
IN Operator.......................................................................................................................................6
LIKE Operator...................................................................................................................................6
NOT Operator....................................................................................................................................6
SORT by Multiple Columns...............................................................................................................7

3. SQL FUNCTIONS..............................................................................................................................7
Single Row Functions........................................................................................................................7
Date Functions..................................................................................................................................8
TO_CHAR Function with Dates........................................................................................................8
TO_CHAR Function with Numbers...................................................................................................9
NVL Function..................................................................................................................................10
DECODE Function.........................................................................................................................11
Nesting Functions............................................................................................................................11

4. JOIN TABLES..................................................................................................................................11
Equijoins..........................................................................................................................................11
Non-Equijoins..................................................................................................................................12
Outer Joins.......................................................................................................................................12
Self Joins..........................................................................................................................................12
Using Table Aliases.........................................................................................................................13

5. GROUP FUNCTIONS.........................................................................................................................13
Types of Group Functions...............................................................................................................13
GROUP BY Clause..........................................................................................................................13
Illegal Queries Using Group Functions..........................................................................................14
HAVING Clause..............................................................................................................................14

6. SUBQUERIES...................................................................................................................................15
Guidelines for Using Subqueries.....................................................................................................15
Single-Row Comparison Operators................................................................................................15
Multiple-Row Comparison Operators.............................................................................................16

7. SQL*PLUS...................................................................................................................................17
Substitution Variable.......................................................................................................................17
ACCEPT Command.........................................................................................................................17
Customizing the SQL*Plus Environment........................................................................................17

8. DATA MANIPULATION LANGUAGE (DML)....................................................................................18
INSERT Statement...........................................................................................................................18
UPDATE Statement.........................................................................................................................18
DELETE Statement..........................................................................................................................19
Transactions....................................................................................................................................19
Before COMMIT or ROLLBACK....................................................................................................19
After COMMIT................................................................................................................................20
After ROLLBACK............................................................................................................................20
SAVEPOINT....................................................................................................................................20

9. MANAGING TABLES.......................................................................................................................20

Naming Rules Of Database Tables And Columns..........................................................................20
CREATE TABLE Statement.............................................................................................................20
Datatypes.........................................................................................................................................21
Create Table by Subquery...............................................................................................................21
Add Column.....................................................................................................................................22
Modify Column................................................................................................................................22
Drop Table.......................................................................................................................................22
Rename Table..................................................................................................................................22
Truncate Table.................................................................................................................................23

10. CONSTRAINTS...............................................................................................................................23
NOT NULL Constraint....................................................................................................................23
UNIQUE Constraint........................................................................................................................23
PRIMARY KEY Constraint..............................................................................................................23
FOREIGN KEY Constraint.............................................................................................................24
CHECK Constraint..........................................................................................................................24
Add Constraint.................................................................................................................................24
Drop Constraint...............................................................................................................................24
Disable and Enable Constraints.....................................................................................................24
Viewing Constraints by USER_CONSTRAINTS.............................................................................25

11. VIEWS......................................................................................................................................25
Advantages of Views........................................................................................................................25
Simple Views and Complex Views..................................................................................................25
WITH CHECK OPTION & WITH READ ONLY............................................................................26

12. SEQUENCE....................................................................................................................................27
13. INDEX......................................................................................................................................27
Guidelines of Creating an Index.....................................................................................................28

14. SYNONYMS...................................................................................................................................28
15. USER ACCESS..............................................................................................................................28
System Privileges.............................................................................................................................28
Object Privileges.............................................................................................................................29

16. PL/SQL FUNDAMENTAL.............................................................................................................30
What is PL/SQL...............................................................................................................................30
Benefits of PL/SQL..........................................................................................................................30

17. DECLARING VARIABLES IN PL/SQL...........................................................................................30
The %TYPE Attribute......................................................................................................................31

18. EXECUTABLE SECTION IN PL/SQL.............................................................................................31
SELECT Statements in PL/SQL.......................................................................................................31
DML Statements in PL/SQL............................................................................................................31
SQL Cursor......................................................................................................................................32

19. CONDITIONAL TESTING AND LOOPING IN PL/SQL......................................................................32
IF Statements...................................................................................................................................32
Basic Loop.......................................................................................................................................33
FOR Loop........................................................................................................................................33
WHILE Loop....................................................................................................................................34

20. COMPOSITE DATATYPES...............................................................................................................34
PL/SQL Table..................................................................................................................................34
PL/SQL Records..............................................................................................................................35
The %ROWTYPE Attribute.............................................................................................................35

21. EXPLICIT CURSORS......................................................................................................................36
Cursor FOR Loops..........................................................................................................................36
Cursors with Parameters.................................................................................................................37
The SELECT ..... FOR UPDATE Clause........................................................................................37
The WHERE CURRENT OF Clause...............................................................................................38

22. HANDLING EXCEPTIONS...............................................................................................................38
Trapping Exceptions........................................................................................................................38
Predefined Oracle Server Errors....................................................................................................39
Non-Predefined Oracle Server Errors............................................................................................39
User-Defined Exception..................................................................................................................40

FREQUENTLY ASKED QUESTIONS IN SQL AND PL/SQL...................................................................41

1. Basic SQL Statement
Demo Tables (EMP & DEPT)
All the SQL statements in this tutorial notes will base on the following two tables

EMP TABLE (14 records)
EMPNO
7369
7499
7521
7566
7654
7698
7782
7788
7839
7844
7876
7900
7902
7934

ENAME
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER

JOB
CLERK
SALESMAN
SALESMAN
MANAGER
SALESMAN
MANAGER
MANAGER
ANALYST
PRESIDENT
SALESMAN
CLERK
CLERK
ANALYST
CLERK

MGR
7902
7698
7698
7839
7698
7839
7839
7566
7698
7788
7698
7566
7782

HIREDATE
17-Dec-80
20-Feb-81
22-Feb-81
02-Apr-81
28-Sep-81
01-May-81
09-Jun-81
09-Dec-82
17-Nov-81
08-Sep-81
12-Jan-83
03-Dec-81
03-Dec-81
23-Jan-82

SAL
1000
1800
1450
3175
1450
3050
2650
3200
5200
1700
1300
1150
3200
1500

COMM DEPTNO
20
300
30
500
30
20
1400
30
30
10
20
10
0
30
20
30
20
10

DEPT TABLE (4 records)
DEPTNO
10
20
30
40

DNAME
ACCOUNTING
RESEARCH
SALES
OPERATIONS

LOC
NEW YORK
DALLAS
CHICAGO
BOSTON

Basic SQL statement
SQL>
2
3
4
5
6

SELECT job, SUM(sal) PAYROLL
FROM emp
WHERE job NOT LIKE 'SALES%'
GROUP BY job
HAVING SUM(sal)>5000
ORDER BY SUM(sal);

Simple rules of SQL statements





SQL statements are not case sensitive, unless indicated.
SQL statements can be entered on one or many lines.
Keywords cannot be split across lines or abbreviated.
Clauses are usually placed on separate lines for readability and ease of editing.
Tabs and indents can be used to make code more readable.
Keywords typically are entered in uppercase; all other words, such as table names and columns, are
entered in lowercase.


Within SQL*Plus, a SQL statement is entered at the SQL prompt, and the subsequent lines are
numbered. This is called the SQL buffer. Only one statement can be current at any time within the
buffer.
Place a semicolon (;) at the end of last clause.

Eliminating Duplicate Rows
SQL> SELECT DISTINCT deptno, job
2 FROM emp;
DEPTNO
JOB
-------------10
CLERK
10
MANAGER
10
PRESIDENT
20
ANALYST
...
9 rows selected.

SQL versus SQL*Plus
SQL

SQL*Plus

Is a language for communicating with the Oracle
Server to access data
Is based on American National Standards Institute
(ANSI) standard SQL
Manipulates data and table definitions in the
database
Is entered into the SQL buffer on one or more lines

Recognizes SQL statements and sends them to the
Server
Is the Oracle proprietary interface for executing SQL
statements
Does not allow manipulation of values in the
database
Is entered one line at a time; not stored in the SQL
buffer
Has a dash (-) as a continuation character if the
command is longer than one line
Can be abbreviated
Does not require termination characters; commands
are executed immediately
Uses commands to format data

Does not have a continuation character
Cannot be abbreviated
Uses a termination character to execute command
immediately
Uses functions to perform some formatting

2. Where, Order by Clauses
IS NULL Operator
SQL> SELECT ename, mgr
2 FROM
emp
3 WHERE
mgr IS NULL;
ENAME
MGR
-----------------KING

BETWEEN Operator
SQL> SELECT ename, sal
2 FROM
emp
3 WHERE sal BETWEEN 1000 AND 1500;
ENAME
SAL
---------- --------MARTIN
1250
TURNER
1500
WARD
1250
ADAMS
1100
MILLER
1300

IN Operator
SQL> SELECT empno, ename, sal, mgr
2 FROM
emp
3 WHERE mgr IN (7902, 7566, 7788);
EMPNO
ENAME
SAL
MGR
---------------- -------- -------7902
FORD
3000
7566
7369
SMITH
800
7902
7788
SCOTT
3000
7566
7876
ADAMS
1100
7788

LIKE Operator
SQL> SELECT ename
2 FROM
emp
3 WHERE ename LIKE '_A%';
ENAME
---------JAMES
WARD

NOT Operator
SQL> SELECT ename, job
2 FROM
emp
3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');
ENAME
JOB
---------- --------KING
PRESIDENT
MARTIN
SALESMAN
ALLEN
SALESMAN
TURNER
SALESMAN
WARD
SALESMAN

SORT by Multiple Columns
SQL> SELECT ename, deptno, sal
2 FROM
emp
3 ORDER BY
deptno, sal DESC;
ENAME
DEPTNO
SAL
---------- --------- --------KING
10
5000
CLARK
10
2450
MILLER
10
1300
FORD
20
3000
...
14 rows selected.

3. SQL Functions
Single Row Functions





Manipulate data items
Accept arguments and return one value
Act on each row returned
Return one result per row
May modify the datatype
Can be nested

Function
LOWER(‘Oracle Education’)
UPPER(‘Oracle Education’)
INITCAP(‘ORACLE
education’)
CONCAT(‘Certified’,
‘DBA’)
SUBSTR(‘Administrator’, 1,
5)
LENGTH(‘Administrator’)
INSTR(‘Oracle’, ‘c’)
LPAD(sal, 10, ‘*’)
ROUND(78.926, 2)
TRUNC(78.926, 2)
MOD(2100, 500)
SQL>
2
3

SELECT

Result
oracle education
ORACLE
EDUCATION
Oracle Education
CertifiedDBA
Admin
13
4
******5000
78.93
78.92
100

'The job title for '||INITCAP(ename)||' is '
||LOWER(job) AS "EMPLOYEE DETAILS"

FROM emp;
EMPLOYEE DETAILS
---------------------------------------The job title for King is president
The job title for Blake is manager
The job title for Clark is manager
...
14 rows selected.

Date Functions
Function
MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')

Result
19.6774194

ADD_MONTHS ('11-JAN-94',6)
NEXT_DAY ('01-SEP-95','FRIDAY')
LAST_DAY('01-SEP-95')
ROUND('25-JUL-95','MONTH')
ROUND('25-JUL-95','YEAR')
TRUNC('25-JUL-95','MONTH')
TRUNC('25-JUL-95','YEAR')

'11-JUL-94'
'08-SEP-95'
'30-SEP-95'
01-AUG-95
01-JAN-96
01-JUL-95
01-JAN-95

SQL>
2
3
4
5
6

Description
Number of months between two
dates
Add calendar months to date
Next day of the date specified
Last day of the month
Round date
Truncate date

SELECT
empno, hiredate,
MONTHS_BETWEEN(SYSDATE, hiredate) TENURE,
ADD_MONTHS(hiredate, 6) REVIEW,
NEXT_DAY(hiredate, 'FRIDAY'), LAST_DAY(hiredate)
FROM emp
WHERE MONTHS_BETWEEN (SYSDATE, hiredate)<200;
EMPNO
HIREDATE
TENURE REVIEW
NEXT_DAY( LAST_DAY(
--------- --------- --------- --------- ----------------7839 17-NOV-81 192.24794 17-MAY-82 20-NOV-81 30-NOV81
7698 01-MAY-81 198.76407 01-NOV-81 08-MAY-81 31-MAY81
...
11 rows selected.

TO_CHAR Function with Dates
Element
SCC or CC
Years in dates YYYY or SYYYY
YYY or YY or Y
Y,YYY
IYYY, IYY, IY, I
SYEAR or YEAR
BC or AD
B.C. or A.D.
Q
MM
MONTH
MON
RM
WW or W
DDD or DD or D
DAY
DY
J
AM or PM
A.M. or P.M.

Description
Century; S prefixes BC date with Year; S prefixes BC date with Last 3, 2, or 1 digit(s) of year
Year with comma in this position
4, 3, 2, or 1 digit year based on the ISO standard
Year spelled out; S prefixes BC date with BC/AD indicator
BC/AD indicator with periods
Quarter of year
Month, two-digit value
Name of month padded with blanks to length of 9 characters
Name of month, three-letter abbreviation
Roman numeral month
Week of year or month
Day of year, month, or week
Name of day padded with blanks to length of 9 characters
Name of day; 3-letter abbreviation
Julian day; the number of days since 31 December 4713 BC
Meridian indicator
Meridian indicator with periods

HH or HH12 or HH24
MI
SS
SSSSS
TH
SP
SPTH or THSP
fm

Hour of day or hour (1–12) or hour (0–23)
Minute (0–59)
Second (0–59)
Seconds past midnight (0–86399)
Ordinal number (for example, DDTH for 4TH)
Spelled-out number (for example, DDSP for FOUR)
Spelled-out ordinal numbers (for example, DDSPTH for
FOURTH)
remove padded blanks or suppress leading zeros

SQL> SELECT ename,
2
TO_CHAR(hiredate, 'fmDD Month YYYY') HIREDATE
3 FROM
emp;
ENAME
HIREDATE
---------- ----------------KING
17 November 1981
BLAKE
1 May 1981
CLARK
9 June 1981
JONES
2 April 1981
MARTIN
28 September 1981
ALLEN
20 February 1981
...
14 rows selected.
SQL> SELECT ename,
2
TO_CHAR(hiredate, 'fmDdspth "of" Month YYYY fmHH:MI:SS AM')
3
HIREDATE
4 FROM
emp;
ENAME
HIREDATE
--------------------------------------------------------KING
Seventeenth of November 1981 12:00:00 AM
BLAKE
First of May 1981 12:00:00 AM
...
14 rows selected.

TO_CHAR Function with Numbers
Element
9
0
$
L
.
,
MI
PR
EEEE
V
B

Description
Numeric position (number of 9s determine display width)
Display leading zeros
Floating dollar sign
Floating local currency symbol
Decimal point in position specified
Comma in position specified
Minus signs to right (negative values)
Parenthesize negative numbers
Scientific notation (format must specify four Es)
Multiply by 10 n times (n = no. of 9s after V)
Display zero values as blank, not 0

Example
999999
099999
$999999
L999999
999999.99
999,999
999999MI
999999PR
99.999EEEE
9999V99
B9999.99

Result
1234
001234
$1234
FF1234
1234.00
1,234
1234<1234>
1.234E+03
123400
1234.00

SQL> SELECT TO_CHAR(sal,'$99,999') SALARY
2 FROM
emp
3 WHERE ename = 'SCOTT';
SALARY
-------$3,000

NVL Function


Converts null to an actual value
Datatypes that can be used are date, character, and number.
Datatypes must match
• NVL(comm,0)
• NVL(hiredate,'01-JAN-97')
• NVL(job,'No Job Yet')

SQL> SELECT ename, sal, comm, (sal*12)+comm
2 FROM
emp;
ENAME
JOB
(SAL*12)+COMM
---------- --------- ------------KING
PRESIDENT
BLAKE
MANAGER
CLARK
MANAGER
JONES
MANAGER
MARTIN
SALESMAN
16400
...
14 rows selected.
SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0)
2 FROM
emp;
ENAME
SAL
COMM (SAL*12)+NVL(COMM,0)
---------- --------- --------- -------------------KING
5000
60000
BLAKE
2850
34200
CLARK
2450
29400
JONES
2975
35700
MARTIN
1250
1400
16400
ALLEN
1600
300
19500
...
14 rows selected.

DECODE Function
SQL> SELECT job, sal,
2
DECODE(job, 'ANALYST', SAL*1.1,
3
'CLERK',
SAL*1.15,
4
'MANAGER', SAL*1.20,
5
SAL)
6
REVISED_SALARY
7 FROM
emp;
JOB
SAL REVISED_SALARY
--------- --------- -------------PRESIDENT
5000
5000
MANAGER
2850
3420
MANAGER
2450
2940
...
14 rows selected.

Nesting Functions
SQL> SELECT ename,
2
NVL(TO_CHAR(mgr),'No Manager')
3 FROM
emp
4 WHERE mgr IS NULL;
ENAME
NVL(TO_CHAR(MGR),'NOMANAGER')
---------- ----------------------------KING
No Manager

4. Join Tables
Equijoins
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2
dept.deptno, dept.loc
3 FROM
emp, dept
4 WHERE emp.deptno=dept.deptno;
EMPNO ENAME
DEPTNO DEPTNO LOC
----- ------ -------- ------ --------7839 KING
10
10 NEW YORK
7698 BLAKE
30
30 CHICAGO
7782 CLARK
10
10 NEW YORK
7566 JONES
20
20 DALLAS
...
14 rows selected.

Non-Equijoins
SALGRADE TABLE
GRADE LOSAL HISAL
----- ----- ------1
700
1200
2
1201
1400
3
1401
2000
4
2001
3000
5
3001
9999
SQL>
2
3
4

SELECT
e.ename, e.sal, s.grade
FROM
emp e, salgrade s
WHERE
e.sal
BETWEEN
s.losal AND s.hisal;
ENAME
SAL
GRADE
---------- --------- --------JAMES
950
1
SMITH
800
1
ADAMS
1100
1
...
14 rows selected.

Outer Joins
SQL>
2
3
4

SELECT e.ename, d.deptno, d.dname
FROM
emp e, dept d
WHERE e.deptno(+) = d.deptno
ORDER BY
e.deptno;
ENAME
DEPTNO DNAME
---------- --------- ------------KING
10 ACCOUNTING
CLARK
10 ACCOUNTING
...
40 OPERATIONS
15 rows selected.

Self Joins
SQL> SELECT worker.ename||' works for '||manager.ename
2 FROM
emp worker, emp manager
3 WHERE worker.mgr = manager.empno;
WORKER.ENAME||'WORKSFOR'||MANAG
------------------------------BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...
13 rows selected.

Using Table Aliases
SQL> SELECT e.empno, e.ename, e.deptno,
2
d.deptno, d.loc
3 FROM
emp e, dept d
4 WHERE e.deptno=d.deptno;

5. Group Functions
Types of Group Functions
Function

Description

AVG([DISTINCT|ALL]n)
COUNTCOUNT({*|[DISTINCT|ALL]expr})
MAXMAX([DISTINCT|ALL]expr)

Average value of n, ignoring null values
Number of rows, where expr evaluates to something
other than null. Count all selected rows using *,
including duplicates and rows with nulls
Maximum value of expr, ignoring null values

MIN([DISTINCT|ALL]expr)
STDDEV([DISTINCT|ALL]x)
SUM([DISTINCT|ALL]n)
VARIANCE([DISTINCT|ALL]x)

Minimum value of expr, ignoring null values
Standard deviation of n, ignoring null values
Sum values of n, ignoring null values
Variance of n, ignoring null values

SQL> SELECT AVG(sal), MAX(sal),
2
MIN(sal), SUM(sal)
3
FROM emp
4
WHERE job LIKE 'SALES%';
AVG(SAL) MAX(SAL) MIN(SAL)
SUM(SAL)
-------- --------- ----------------1400
1600
1250
5600
SQL> SELECT COUNT(*)
2 FROM
emp
3 WHERE deptno = 30;
COUNT(*)
--------6

GROUP BY Clause
SQL> SELECT
2 FROM
3 GROUP BY
DEPTNO
-----10
20
30

deptno, AVG(sal)
emp
deptno;
AVG(SAL)
--------2916.6667
2175
1566.6667

SQL> SELECT
deptno, job, sum(sal)
2 FROM
emp
3 GROUP BY deptno, job;
DEPTNO JOB
SUM(SAL)
------- --------- --------10 CLERK
1300
10 MANAGER
2450
10 PRESIDENT
5000
20 ANALYST
6000
20 CLERK
1900
...
9 rows selected.

Illegal Queries Using Group Functions
SQL> SELECT deptno, COUNT(ename)
2 FROM
emp;
SELECT deptno, COUNT(ename)
*
ERROR at line 1:
ORA-00937: not a single-group group function
SQL>
2
3
4

SELECT deptno, AVG(sal)
FROM
emp
WHERE
AVG(sal) > 2000
GROUP BY
deptno;
WHERE AVG(sal) > 2000
*
ERROR at line 3:
ORA-00934: group function is not allowed
here

HAVING Clause
SQL>
2
3
4

SELECT
deptno, max(sal)
FROM
emp
GROUP BY deptno
HAVING
max(sal)>2900;
DEPTNO MAX(SAL)
------ --------10
5000
20
3000

6. Subqueries
Guidelines for Using Subqueries
SQL> SELECT ename
2 FROM
emp
3 WHERE sal >
4
(SELECT sal
5
FROM
emp
6
WHERE empno=7566);
ENAME
---------KING
FORD
SCOTT






The subquery (inner query) executes once before the main query.
The result of the subquery is used by the main query (outer query).
Enclose subqueries in parentheses.
Place subqueries on the right side of the comparison operator.
Do not add an ORDER BY clause to a subquery.
Use single-row operators with single-row subqueries.
Use multiple-row operators with multiple-row subqueries.

Single-Row Comparison Operators
Operator
=
>
>=
<
<=
<>
SQL>
2
3
4
5
6
7
8
9
10

Meaning
Equal to
Greater than
Greater than or equal to
Less than
Less than or equal to
Not equal to

SELECT
FROM
WHERE

ename, job
emp
job =
(SELECT
FROM
WHERE
AND
sal >
(SELECT
FROM emp
WHERE empno
ENAME
JOB
---------- --------MILLER
CLERK

job
emp
empno = 7369)
sal
= 7876);

Multiple-Row Comparison Operators
Operator
IN
ANY
ALL
SQL>
2
3
4
5
6
7

Meaning
Equal to any member in the list
Compare value to each value returned by the subquery
Compare value to every value returned by the subquery

SELECT
FROM
WHERE

AND
EMPNO
----7654
7521

empno, ename, job
emp
sal < ANY
(SELECT sal
FROM emp
WHERE job = 'CLERK')
job <> 'CLERK';
ENAME
JOB
------ -------MARTIN SALESMAN
WARD
SALESMAN

SQL> SELECT
2 FROM
3 WHERE
4
5
6
EMPNO
----7839
7566
7902
7788

empno, ename, job
emp
sal > ALL
(SELECT
avg(sal)
FROM
emp
GROUP BY deptno);
ENAME
JOB
------ --------KING
PRESIDENT
JONES
MANAGER
FORD
ANALYST
SCOTT
ANALYST

SQL> SELECT ename, deptno, sal, comm
2 FROM
emp
3 WHERE
(sal, NVL(comm,-1)) IN
4
(SELECT sal, NVL(comm,-1)
5
FROM
emp
6
WHERE deptno = 30);
ENAME
DEPTNO
SAL
COMM
---------- --------- --------- --------JAMES
30
950
WARD
30
1250
500
MARTIN
30
1250
1400
TURNER
30
1500
0
ALLEN
30
1600
300
BLAKE
30
2850
6 rows selected.

7. SQL*Plus
Substitution Variable

Use a variable prefixed with an ampersand (&) to prompt the user for a value.

SQL> SELECT empno, ename, sal, deptno
2 FROM
emp
3 WHERE empno = &employee_num;
Enter value for employee_num: 7369
EMPNO ENAME
SAL
DEPTNO
--------- ---------- --------- --------7369 SMITH
800
20

Use single quotation marks for date and character values.

SQL> SELECT ename, deptno, sal*12
2 FROM
emp
3 WHERE job='&job_title';
Enter value for job_title: ANALYST
ENAME
DEPTNO
SAL*12
---------- --------- --------SCOTT
20
36000
FORD
20
36000

ACCEPT Command
ACCEPT
dept PROMPT 'Provide the department name: '
SELECT
*
FROM
dept
WHERE
dname = UPPER('&dept')
/
Provide the department name: Sales
DEPTNO DNAME
LOC
--------- -------------- ------------30 SALES
CHICAGO

Customizing the SQL*Plus Environment
SET Variable and Values

Description

ARRAY[SIZE] {20| n}
COLSEP {_|text}
FEED[BACK] {6|n|OFF|ON}

Sets the database data fetch size
Sets text to be printed between columns. Default is single space
Displays the number of records returned by a query when the query
selects at least n records
Determine whether column headings are displayed in reports
Sets the number of characters per line to n for reports
Sets the maximum width for displaying LONG values
Specifies the number of lines per page of output
Allows you to control scrolling of your terminal (You must press
[Return] after seeing each pause.)

HEA[DING] {OFF|ON}
LIN[ESIZE] {80|n}
LONG {80|n}
PAGES[IZE] {24|n}
PAU[SE] {OFF|ON|text}

TERM[OUT] {OFF|ON}
COL[UMN] [column option]
TTI[TLE] [text|OFF|ON]
BTI[TLE] [text|OFF|ON]
BRE[AK] [ON report_element]

Determines whether output is displayed on screen
Controls column formats
Specifies a header to appear at the top of each page
Specifies a footer to appear at the bottom of each page of the report
Suppresses duplicate values and sections rows of data with line feeds

8. Data Manipulation Language (DML)
INSERT Statement
INSERT INTO table [(column [, column...])]
VALUES
(value [, value...]);



Only one row is inserted at a time with this syntax.
Insert a new row containing values for each column.
List values in the default order of the columns in the table.
Optionally list the columns in the INSERT clause.
Enclose character and date values within single quotation marks.

SQL> INSERT INTO
2 VALUES
1 row created.


dept (deptno, dname, loc)
(50, 'DEVELOPMENT', 'DETROIT');

Inserting Rows with Null Values
Implicit method: Omit the column from the column list.
Explicit method: Specify the NULL keyword.

SQL> INSERT INTO
2 VALUES
1 row created.

dept (deptno, dname )
(60, 'MIS');

SQL> INSERT INTO
2 VALUES
1 row created.

dept
(70, 'FINANCE', NULL);

UPDATE Statement
UPDATE
SET
[WHERE

table
column = value [, column = value]
condition];

Update more than one row at a time, if required.
Specific row or rows are modified when you specify the WHERE clause.

SQL> UPDATE
2 SET
3 WHERE
1 row updated.

emp
deptno = 20
empno = 7782;

All rows in the table are modified if you omit the WHERE clause.

SQL> UPDATE
2 SET
14 rows updated.

employee
deptno = 20;

DELETE Statement
DELETE [FROM]
table
[WHERE
condition];

You can remove existing rows from a table by using the DELETE statement.
Specific row or rows are deleted when you specify the WHERE clause.

SQL> DELETE FROM
2 WHERE
1 row deleted.

department
dname = 'DEVELOPMENT';

All rows in the table are deleted if you omit the WHERE clause.

SQL> DELETE FROM
4 rows deleted.

department;

Transactions


Consist of one of the following statements:
− DML statements that make up one consistent change to the data
− One DDL statement
− One DCL statement
Begin when the first executable SQL statement is executed
End with one of the following events:
− COMMIT or ROLLBACK
− DDL or DCL statement executes (automatic commit)
− User exits
− System crashes
An automatic commit occurs under the following circumstances:
− A DDL statement is issued
− A DCL statement is issued
− A normal exit from SQL*Plus, without explicitly issuing COMMIT or ROLLBACK
An automatic rollback occurs under an abnormal termination of SQL*Plus or a system failure

Before COMMIT or ROLLBACK



The previous state of the data can be recovered.
The current user can review the results of the DML operations by using the SELECT statement.
Other users cannot view the results of the DML statements by the current user.
The affected rows are locked; other users cannot change the data within the affected rows.

After COMMIT
SQL> COMMIT;
Commit complete.




Data changes are made permanent in the database.
The previous state of the data is permanently lost.
All users can view the results.
Locks on the affected rows are released; those rows are available for other users to manipulate.
All savepoints are erased.

After ROLLBACK
SQL> ROLLBACK;
Rollback complete.


Data changes are undone.
Previous state of the data is restored.
Locks on the affected rows are released.

SAVEPOINT

Create a marker within a current transaction by using the SAVEPOINT statement.
Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.

SQL> UPDATE...
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT...
SQL> ROLLBACK TO update_done;
Rollback complete.

9. Managing Tables
Naming Rules Of Database Tables And Columns




Must begin with a letter
Can be 1–30 characters long
Must contain only A–Z, a–z, 0–9, _, $, and #
Must not duplicate the name of another object owned by the same user
Must not be an Oracle Server reserved word

CREATE TABLE Statement
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr], ..., ...);

schema
is the same as the owner’s name.

table
is the name of the table.

DEFAULT expr
specifies a default value if a value is omitted in the INSERT
statement.

column
is the name of the column.

datatype
is the column's datatype and length.

SQL> CREATE TABLE dept
2
(deptno
3
dname
4
loc
Table created.

NUMBER(2),
VARCHAR2(14),
VARCHAR2(13));

SQL> DESCRIBE dept
Name
Null?
--------------------------- -------DEPTNO
DNAME
LOC

Type
--------NUMBER(2)
VARCHAR2(14)
VARCHAR2(13)

Datatypes
Datatype
VARCHAR2(size)
CHAR(size)
NUMBER(p,s)

DATE
LONG
CLOB
RAW(size)
LONG RAW
BLOB
BFILE

Description
Variable-length character data (A maximum size must be specified. Default
and minimum size is 1, maximum size is 4000.)
Fixed-length character data of length size bytes (Default and minimum size
is 1, maximum size is 2000.)
Number having precision p and scale s; the precision is the total number of
decimal digits, and the scale is the number of digits to the right of the
decimal point (The precision can range from 1 to 38 and the scale can range
from -84 to 127.)
Date and time values between January 1, 4712 B.C., and December 31, 9999
A.D.
Variable-length character data up to 2 gigabytes
Single-byte character data up to 4 gigabytes
Raw binary data of length size. Maximum size is 2000 (A maximum size
must be specified.)
Raw binary data of variable length up to 2 gigabytes
Binary data up to 4 gigabytes
Binary data stored in an external file; up to 4 gigabytes

Create Table by Subquery
SQL> CREATE TABLE dept30
2 AS
3
SELECT empno, ename, sal*12 ANNSAL, hiredate
4
FROM emp
5
WHERE deptno = 30;
Table created.
SQL> DESCRIBE dept30
Name
Null?
----------- -------EMPNO
NOT NULL
ENAME
ANNSAL
HIREDATE

Type
----NUMBER(4)
VARCHAR2(10)
NUMBER
DATE

Add Column
SQL> ALTER TABLE dept30
2 ADD
(job VARCHAR2(9));
Table altered.

The new column becomes the last column.
EMPNO
ENAME
ANNSAL
--------- ---------- --------7698
BLAKE
34200
7654
MARTIN
15000
7499
ALLEN
19200
7844
TURNER
18000
...
6 rows selected.

HIREDATE JOB
--------- ---01-MAY-81
28-SEP-81
20-FEB-81
08-SEP-81

Modify Column
SQL> ALTER TABLE dept30
2> MODIFY (ename VARCHAR2(15));
Table altered.




Increase the width or precision of a numeric column.
Decrease the width of a column if the column contains only null values or if the table has no rows.
Change the datatype if the column contains null values.
Convert a CHAR column to the VARCHAR2 datatype or convert a VARCHAR2 column to the
CHAR datatype if the column contains null values or if you do not change the size.
A change to the default value of a column affects only subsequent insertions to the table.

Drop Table
SQL> DROP TABLE dept30;
Table dropped.



All data and structure in the table is deleted.
Any pending transactions are committed.
All indexes are dropped.
You cannot roll back this statement.

Rename Table
SQL> RENAME dept TO department;
Table renamed.

To change the name of a table, view, sequence, or synonym, you execute the RENAME statement.
You must be the owner of the object.

Truncate Table
SQL> TRUNCATE TABLE department;
Table truncated.


Removes all rows from a table
Releases the storage space used by that table
Cannot roll back row removal when using TRUNCATE

10. Constraints

Column level constraint

column [CONSTRAINT constraint_name] constraint_type,

Table level constraint

column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),

NOT NULL Constraint
SQL> CREATE TABLE
2
empno
3
ename
4
job
5
mgr
6
hiredate
7
sal
8
comm
9
deptno

emp(
NUMBER(4),
VARCHAR2(10) NOT NULL,
VARCHAR2(9),
NUMBER(4),
DATE,
NUMBER(7,2),
NUMBER(7,2),
NUMBER(7,2) NOT NULL);

UNIQUE Constraint
SQL> CREATE TABLE
dept(
2
deptno NUMBER(2),
3
dname
VARCHAR2(14),
4
loc
VARCHAR2(13),
5
CONSTRAINT dept_dname_uk UNIQUE(dname));

PRIMARY KEY Constraint
SQL> CREATE TABLE
dept(
2
deptno
NUMBER(2),
3
dname
VARCHAR2(14),
4
loc
VARCHAR2(13),
5
CONSTRAINT dept_dname_uk UNIQUE (dname),
6
CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));

FOREIGN KEY Constraint
SQL> CREATE TABLE emp(
2
empno
NUMBER(4),
3
ename
VARCHAR2(10) NOT NULL,
4
job
VARCHAR2(9),
5
mgr
NUMBER(4),
6
hiredate
DATE,
7
sal
NUMBER(7,2),
8
comm
NUMBER(7,2),
9
deptno
NUMBER(7,2) NOT NULL,
10
CONSTRAINT emp_deptno_fk FOREIGN KEY
(deptno)
11
REFERENCES dept (deptno));

CHECK Constraint
..., deptno NUMBER(2),
CONSTRAINT emp_deptno_ck
CHECK (DEPTNO BETWEEN 10 AND 99),...

Add Constraint
SQL> ALTER TABLE
emp
2 ADD CONSTRAINT emp_mgr_fk
3
FOREIGN KEY(mgr) REFERENCES
emp(empno);
Table altered.

Drop Constraint
SQL> ALTER TABLE
emp
2 DROP CONSTRAINT emp_mgr_fk;
Table altered.

Remove the PRIMARY KEY constraint on the DEPT table and drop the associated FOREIGN
KEY constraint on the EMP.DEPTNO column.

SQL> ALTER TABLE dept
2 DROP PRIMARY KEY CASCADE;
Table altered.

Disable and Enable Constraints

Execute the DISABLE clause of the ALTER TABLE statement to deactivate an integrity constraint.
Apply the CASCADE option to disable dependent integrity constraints.

SQL> ALTER TABLE
emp
2 DISABLE CONSTRAINT emp_empno_pk CASCADE;
Table altered.

SQL> ALTER TABLE
2 ENABLE CONSTRAINT
Table altered.

emp
emp_empno_pk;

A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE key or
PRIMARY KEY constraint.

Viewing Constraints by USER_CONSTRAINTS
SQL>
2
3
4

SELECT constraint_name, constraint_type,
search_condition
FROM
user_constraints
WHERE table_name = 'EMP';
CONSTRAINT_NAME
C SEARCH_CONDITION
------------------------ - ------------------------SYS_C00674
C EMPNO IS NOT NULL
SYS_C00675
C DEPTNO IS NOT NULL
EMP_EMPNO_PK
P
...

11. VIEWS
Advantages of Views



Restrict access to the database because the view can display a selective portion of the database.
Allow users to make simple queries to retrieve the results from complicated queries. For example,
views allow users to query information from multiple tables without knowing how to write a join
statement.
Provide data independence for ad hoc users and application programs. One view can be used to
retrieve data from several tables.
Provide groups of users access to data according to their particular criteria.

Simple Views and Complex Views
Feature
Number of tables
Contain functions
Contain groups of data
DML through view

Simple Views
One
No
No
Yes

Complex Views
One or more
Yes
Yes
Not always

Example 1 : Create a simple view.
SQL>
2
3
4
View

CREATE VIEW
AS SELECT
FROM
WHERE
created.

salvu30
empno EMPLOYEE_NUMBER, ename NAME, sal SALARY
emp
deptno = 30;

SQL>
2

SELECT *
FROM salvu30;
EMPLOYEE_NUMBER NAME
SALARY
--------------- ---------- --------7698 BLAKE
2850
7654 MARTIN
1250
7499 ALLEN
1600
7844 TURNER
1500
7900 JAMES
950
7521 WARD
1250
6 rows selected.

Example 2 : Create a complex view.
SQL>
2
3
4
5
6
View

CREATE VIEW
AS SELECT
FROM
WHERE
GROUP BY
created.

dept_sum_vu
(name, minsal, maxsal, avgsal)
d.dname, MIN(e.sal), MAX(e.sal), AVG(e.sal)
emp e, dept d
e.deptno = d.deptno
d.dname;

SQL> SELECT *
2 FROM
dept_sum_vu;
NAME
MINSAL
MAXSAL
AVGSAL
-------------- --------- --------- --------ACCOUNTING
1300
5000 2916.6667
RESEARCH
800
3000
2175
SALES
950
2850 1566.6667

WITH CHECK OPTION & WITH READ ONLY
SQL>
2
3
4
5
View

CREATE OR REPLACE VIEW empvu20
AS SELECT
*
FROM
emp
WHERE
deptno = 20
WITH CHECK OPTION CONSTRAINT empvu20_ck;
created.
You can ensure that DML on the view stays
within the domain of the view by using the WITH CHECK OPTION.
Any attempt to change the department number for any row in the view will fail because it violates
the WITH CHECK OPTION constraint.

SQL>
2
3
4
5
6
View

CREATE OR REPLACE VIEW empvu10
(employee_number, employee_name, job_title)
AS SELECT
empno, ename, job
FROM
emp
WHERE
deptno = 10
WITH READ ONLY;
created.
You can ensure that no DML operations occur by adding the WITH READ ONLY option to your
view definition.
Any attempt to perform a DML on any row in the view will result in Oracle Server error ORA01752.

12. Sequence

Define a sequence to generate sequential numbers automatically

CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
Example 1 : Create a sequence named DEPT_DEPTNO to be used for the primary key of the
DEPT table and use it for insert.
SQL> CREATE SEQUENCE dept_deptno
2
INCREMENT BY 1
3
START WITH 91
4
MAXVALUE 100
5
NOCACHE
6
NOCYCLE;
Sequence created.
SQL> INSERT INTO
2 VALUES
3
1 row created.

dept(deptno, dname, loc)
(dept_deptno.NEXTVAL,
'MARKETING', 'SAN DIEGO');

13. INDEX






Schema object
Used by the Oracle Server to speed up the retrieval of rows by using a pointer
Reduces disk I/O by using rapid path access method to locate the data quickly
Independent of the table it indexes
Automatically used and maintained by the Oracle Server
A unique index is created automatically when you define a PRIMARY KEY or UNIQUE key
constraint in a table definition.
Users can create non unique indexes on columns to speed up access time to the rows.

Example 1 : Improve the speed of query access on the ENAME column in the EMP table
SQL> CREATE INDEX
2 ON
Index created.

emp_ename_idx
emp(ename);

Guidelines of Creating an Index





The column is used frequently in the WHERE clause or in a join condition.
The column contains a wide range of values.
The column contains a large number of null values.
Two or more columns are frequently used together in a WHERE clause or a join condition.
The table is large and most queries are expected to retrieve less than 2–4% of the rows.
The table is not updated frequently

14. Synonyms

Refer to a table owned by another user.
Shorten lengthy object names.

SQL> CREATE SYNONYM
2 FOR
Synonym Created.

d_sum
dept_sum_vu;

15. User Access
System Privileges
System Privilege
CREATE SESSION
CREATE TABLE
CREATE SEQUENCE
CREATE VIEW
CREATE PROCEDURE

Operations Authorized
Connect to the database
Create tables in the user’s schema
Create a sequence in the user’s schema
Create a view in the user’s schema
Create a stored procedure, function, or package in the user’s schema

The DBA can grant a user specific system privileges.

SQL> GRANT create table, create sequence, create view
2 TO
scott;
Grant succeeded.

Object Privileges
Object Privilege
ALTER
DELETE
EXECUTE
INDEX
INSERT
REFERENCES
SELECT
UPDATE


Table

View





Sequence



Object privileges vary from object to object.
An owner has all the privileges on his own objects.
An owner can grant specific privileges on that owner’s object to other users.

Example 1 : Grant query privileges on the EMP table.
SQL> GRANT select
2 ON
emp
3 TO
sue, rich;
Grant succeeded.
Example 2 : Grant privileges to update specific columns to users and roles.
SQL> GRANT update (dname, loc)
2 ON
dept
3 TO
scott, manager;
Grant succeeded.
Example 3 : Give a user authority to pass along the privileges.
SQL> GRANT select, insert
2 ON
dept
3 TO
scott
4 WITH GRANT OPTION;
Grant succeeded.
Example 4 : Allow all users on the system to query data from Alice’s DEPT table.
SQL> GRANT select
2 ON
alice.dept
3 TO
PUBLIC;
Grant succeeded.

Procedure

Example 5 : revoke the SELECT and INSERT privileges given to user Scott on the DEPT table.
SQL> REVOKE select, insert
2 ON
dept
3 FROM
scott;
Revoke succeeded.

Privileges granted to others through the WITH GRANT OPTION will also be revoked.

16. PL/SQL Fundamental
What is PL/SQL

PL/SQL is an extension to SQL with design features of programming languages.
Data manipulation and query statements of SQL are included within procedural units of code.

Benefits of PL/SQL

Take Advantage of Portability
− Because PL/SQL is native to the Oracle Server, you can move programs to any host
environment (operating system or platform) that supports the Oracle Server and PL/SQL.
In other words, PL/SQL programs can run anywhere the Oracle Server can run; you do not
need to tailor them to each new environment.
− You can also move code between the Oracle Server and your application. You can write
portable program packages and create libraries that can be reused in different
environments.
Declare Identifiers
− Declare variables, cursors, constants, and exceptions and then use them in SQL and
procedural statements.
− Declare variables belonging to scalar, reference, composite, and large object (LOB)
datatypes.
− Declare variables dynamically based on the data structure of tables and
columns in the database.
Program with Procedural Language Control Structures
− Execute a sequence of statements conditionally.
− Execute a sequence of statements iteratively in a loop.
− Process individually the rows returned by a multiple-row query with an explicit cursor.
Handle Errors
− Process Oracle Server errors with exception-handling routines.
− Declare user-defined error conditions and process them with exception-handling routines.

17. Declaring Variables in PL/SQL
identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr];
Examples :
Declare
v_hiredate
v_deptno
v_location
c_comm

DATE;
NUMBER(2) NOT NULL := 10;
VARCHAR2(13) := 'Atlanta';
CONSTANT NUMBER := 1400;

Guildelines :
• Follow naming conventions.





Initialize variables designated as NOT NULL.
Initialize identifiers by using the assignment operator (:=) or by using the DEFAULT reserved word.
Declare at most one identifier per line.
Two variables can have the same name, provided they are in different blocks.
The variable name (identifier) should not be the same as the name of table columns used in the
block.

The %TYPE Attribute

Declare a variable according to:
− A database column definition
− Another previously declared variable
Prefix %TYPE with:
− The database table and column
− The previously declared variable name

Examples :
...
v_ename
v_balance
v_min_balance
10;
...

emp.ename%TYPE;
NUMBER(7,2);
v_balance%TYPE :=

18. Executable Section in PL/SQL
SELECT Statements in PL/SQL
Syntax
SELECT select_list
INTO
{variable_name[, variable_name]...
| record_name}
FROM
table
WHERE condition;
Example :
DECLARE
v_deptno
v_loc
BEGIN
SELECT
INTO
FROM
WHERE
...
END;

NUMBER(2);
VARCHAR2(15);
deptno, loc
v_deptno, v_loc
dept
dname = 'SALES';

DML Statements in PL/SQL
Example 1 : Insert statement in PL/SQL

DECLARE
v_empno
emp.empno%TYPE;
BEGIN
SELECT
empno_sequence.NEXTVAL
INTO
v_empno
FROM
dual;
INSERT INTO emp(empno, ename, job, deptno)
VALUES(v_empno, 'HARDING', 'CLERK', 10);
END;
Example 2 : Update statement in PL/SQL
DECLARE
v_sal_increase
emp.sal%TYPE := 2000;
BEGIN
UPDATE
emp
SET
sal = sal + v_sal_increase
WHERE
job = 'ANALYST';
END;
Example 3 : Delete statement in PL/SQL
DECLARE
v_deptno
BEGIN
DELETE
WHERE
END;

emp.deptno%TYPE := 10;
FROM emp
deptno = v_deptno;

SQL Cursor



A cursor is a private SQL work area.
There are two types of cursors:
− Implicit cursors
− Explicit cursors
The Oracle Server uses implicit cursors to parse and execute your SQL statements.
Explicit cursors are explicitly declared by the programmer.

Using SQL cursor attributes, you can test the outcome of your SQL statements.
SQL%ROWCOUNT
SQL%FOUND
SQL%NOTFOUND
SQL%ISOPEN

Number of rows affected by the most recent SQL statement (an integer value).
Boolean attribute that evaluates to TRUE if the most recent SQL statement affects
one or more rows.
Boolean attribute that evaluates to TRUE if the most recent SQL statement does
not affect any rows.
Always evaluates to FALSE because PL/SQL closes implicit cursors immediately
after they are xecuted.

19. Conditional Testing and Looping in PL/SQL
IF Statements
Syntax :

IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
Example :
. . .
IF v_start > 100 THEN
v_start := 2 * v_start;
ELSIF v_start >= 50 THEN
v_start := .5 * v_start;
ELSE
v_start := .1 * v_start;
END IF;
. . .

Basic Loop
Syntax
LOOP
statement1;
. . .
EXIT [WHEN condition];
END LOOP;
Example
DECLARE
v_ordid
item.ordid%TYPE := 101;
v_counter
NUMBER(2) := 1;
BEGIN
LOOP
INSERT INTO item(ordid, itemid)
VALUES(v_ordid, v_counter);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 10;
END LOOP;
END;

FOR Loop
Syntax
FOR counter in [REVERSE]
lower_bound..upper_bound LOOP
statement1;

statement2;
. . .
END LOOP;
Example
DECLARE
v_ordid
item.ordid%TYPE := 101;
BEGIN
FOR i IN 1..10 LOOP
INSERT INTO item(ordid, itemid)
VALUES(v_ordid, i);
END LOOP;
END;

WHILE Loop
Syntax
WHILE condition LOOP
statement1;
statement2;
. . .
END LOOP;
Example
ACCEPT p_price PROMPT 'Enter the price of the item: '
ACCEPT p_itemtot PROMPT 'Enter the maximum total for purchase of item:
'
DECLARE
...
v_qty
NUMBER(8) := 1;
v_running_total
NUMBER(7,2) := 0;
BEGIN
...
WHILE v_running_total < &p_itemtot LOOP
...
v_qty := v_qty + 1;
v_running_total := v_qty * &p_price;
END LOOP;
...

20. Composite Datatypes
PL/SQL Table

Are composed of two components:
− Primary key of datatype BINARY_INTEGER
− Column of scalar or record datatype
Increase dynamically because they are unconstrained

Primary Key

Column

...
1
2
3
...
BINARY_INTEGER

...
Jones
Smith
Maduro
...
Scalar

Example
...
TYPE ename_table_type IS TABLE OF emp.ename%TYPE
INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
...

PL/SQL Records




Must contain one or more components of any scalar, RECORD, or PL/SQL TABLE datatype-called
fields
Are similar in structure to records in a 3GL
Are not the same as rows in a database table
Treat a collection of fields as a logical unit
Are convenient for fetching a row of data from a table for processing
Example

...
TYPE emp_record_type IS RECORD
(ename
VARCHAR2(10),
job
VARCHAR2(9),
sal
NUMBER(7,2));
emp_record
emp_record_type;
...

The %ROWTYPE Attribute





Declare a variable according to a collection of columns in a database table or view.
Prefix %ROWTYPE with the database table.
Fields in the record take their names and datatypes from the columns of the table or view.
The number and datatypes of the underlying database columns may not be known.
The number and datatypes of the underlying database column may change at runtime.
Useful when retrieving a row with the SELECT statement.

Example 1 : Declare a variable to store the same information about a department as it is stored in
the DEPT table.
dept_record

dept%ROWTYPE;

Example 2 : Declare a variable to store the same information about a employee as it is stored in the
EMP table.
emp_record

emp%ROWTYPE;

21. Explicit Cursors
No
Yes
DECLARE

1.
2.

3.

4.

OPEN
OPEN

FETCH

CLOSE
CLOSE

Declare the cursor by naming it and defining the structure of the query to be performed within it.
Open the cursor. The OPEN statement executes the query and binds any variables that are
referenced. Rows identified by the query are called the active set and are now available for
fetching.
Fetch data from the cursor. The FETCH statement loads the current row from the cursor into
variables. Each fetch causes the cursor to move its pointer to the next row in the active set.
Therefore each fetch accesses a different row returned by the query. In the flow diagram shown
in the slide, each fetch tests the cursor for any existing rows. If rows are found, it loads the
current row into variables; otherwise it closes the cursor.
Close the cursor. The CLOSE statement releases the active set of rows. It is now possible to
reopen the cursor to establish a fresh active set.

Cursor FOR Loops
Syntax
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;


EMPTY?

Shortcut to process explicit cursors.
Implicit open, fetch, and close occur.
Do not declare the record; it is implicitly declared.

Example : Retrieve employees one by one until there are no more left.
DECLARE
CURSOR c1 IS
SELECT empno, ename
FROM
emp;
BEGIN
FOR emp_record IN c1 LOOP
-- implicit open and implicit fetch occur
IF emp_record.empno = 7839 THEN
...
END LOOP; -- implicit close occurs
END;

Cursors with Parameters
Syntax
CURSOR cursor_name
[(parameter_name datatype, ...)]
IS
select_statement;

Pass parameter values to a cursor when the cursor is opened and the query is executed.
Open an explicit cursor several times with a different active set each time.

Example
DECLARE
CURSOR c1
(v_deptno NUMBER, v_job VARCHAR2) IS
SELECT empno, ename
FROM
emp
WHERE
deptno = v_deptno
AND
job = v_job;
BEGIN
OPEN c1(10, 'CLERK');
...

The SELECT ..... FOR UPDATE Clause
Syntax
SELECT
...
FROM
...
FOR UPDATE [NOWAIT]

Explicit locking lets you deny access for the duration of a transaction.
Lock the rows before the update or delete.

Example
DECLARE
CURSOR c1 IS
SELECT empno, ename
FROM
emp
FOR UPDATE NOWAIT;

The WHERE CURRENT OF Clause
Syntax
WHERE CURRENT OF cursor


Use cursors to update or delete the current row.
Include the FOR UPDATE clause in the cursor query to lock the rows first.
Use the WHERE CURRENT OF clause to reference the current row from an explicit cursor.
Example

DECLARE
CURSOR c1 IS
SELECT ...
FOR UPDATE NOWAIT;
BEGIN
...
FOR emp_record IN c1 LOOP
UPDATE ...
WHERE CURRENT OF c1;
...
END LOOP;
COMMIT;
END;

22. Handling Exceptions
Trapping Exceptions
Syntax
EXCEPTION
WHEN exception1 [OR exception2 . . .] THEN
statement1;
. . .
[WHEN exception3 [OR exception4 . . .] THEN
statement1;
. . .]
[WHEN OTHERS THEN
statement1;
. . .]
• WHEN OTHERS is the last clause.
• EXCEPTION keyword starts exception-handling section.


Several exception handlers are allowed.
Only one handler is processed before leaving the block.

Predefined Oracle Server Errors
Exception Name
DUP_VAL_ON_INDEX
INVALID_CURSOR
NO_DATA_FOUND
TOO_MANY_ROWS
ZERO_DIVIDE

Oracle Server
Error Number
ORA-00001
ORA-01001
ORA-01403
ORA-01422
ORA-01476

Description
Attempted to insert a duplicate value.
Illegal cursor operation occurred.
Single row SELECT returned no data.
Single row SELECT returned more than one row.
Attempted to divide by zero.

Example : Trapping Predefined Oracle Server Errors
BEGIN SELECT ... COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
statement1;
statement2;
WHEN TOO_MANY_ROWS THEN
statement1;
WHEN OTHERS THEN
statement1;
statement2;
statement3;
END;

Non-Predefined Oracle Server Errors

Declare

Associate

Declarative Section

Reference
Exception-Handling
Section

Example : Trapping Non-Predefined Oracle Server Errors
DECLARE
e_products_invalid
EXCEPTION;
PRAGMA EXCEPTION_INIT (
e_products_invalid, -2292);
v_message VARCHAR2(50);
BEGIN
. . .
EXCEPTION
WHEN e_products_invalid THEN
:g_message := 'Product code
specified is not valid.';
. . .
END;

User-Defined Exception

Declare

Raise

Reference

Declarative
Section

Executable
Section

Exception-Handling
Section

Example : Trapping User-Defined Exceptions
[DECLARE]
e_amount_remaining EXCEPTION;
. . .
BEGIN
. . .
RAISE e_amount_remaining;
. . .
EXCEPTION
WHEN e_amount_remaining THEN
:g_message := 'There is still an amount
in stock.';
. . .
END;

Frequently Asked Questions in SQL and PL/SQL
Q1 : Can one drop a column from a table?
Oracle does not provide a way to DROP a column before Oracle 8i
Other workarounds:
1. update t1 set column_to_drop = NULL;
rename t1 to t1_base;
create view t1 as select <specific columns> from t1_base;
2. create table t2 as select <specific columns> from t1;
drop table t1;
rename t2 to t1;

Q2 : How can I eliminate duplicates values in a table?
SQL> create table table_name2 as select distinct * from table_name1;
SQL> drop table_name1;
SQL> rename table_name2 to table_name1;

Q3 : How does one count different data values in a column?
select dept_no, sum( decode(sex,'M',1,0)) MALE,
sum( decode(sex,'F',1,0)) FEMALE,
count(decode(sex,'M',1,'F',1)) TOTAL
from
emp
group by dept_no;

Q4 : Can one rename a column in a table?
No!
Other Workarounds:
1. rename t1 to t1_base;
create view t1 <column list with new name> as select * from t1_base;
2. create table t2 <column list with new name> as select * from t1;
drop table t1;
rename t2 to t1;

Q5 : How can I change my Oracle password?
Issue the following SQL command: ALTER USER <username> IDENTIFIED BY
<new_password>
/
From Oracle8 you can just type "password" from SQL*Plus, or if you need
to change
another user's password, type "password user_name".

Q6 : Can I update through a view ?
You can do this iff
1.Your view is a simple subset of a single table.
2.All "not null" columns for the table must be in the view.
3.The primary key is in the view.

Q7 : Are views updated when I update base tables ?
Yes, that is the whole idea of views. The only thing Oracle stores for
a view is the text of the definition. When you select from a view,
Oracle looks up the text used to define the view and then executes that
query.