You are on page 1of 89

PL/SQL Revision - Introduction to Oracle: SQL and PL/SQL

SELECT Data retrieval Retrieves data from the database

INSERT Data manipulation Enters new rows, changes existing rows, and removes unwanted rows from tables in the
UPDATE language database, respectively.
DELETE (DML)

CREATE
ALTER
DROP Data definition language Set up, changes, and removes data structures from tables.
RENAME (DDL)
TRUNCATE

COMMIT Manages the changes made by DML statements. Changes to the data can be grouped
ROLLBACK Transaction control into logical transactions. A database transaction consists of a collection of DML
SAVEPOINT statements that form a logical unit of work, one DDL, or one DCL statement.

GRANT Data control language Gives or removes access rights to both the Oracle database and the structures within it.
REVOKE (DCL)
SQL / SQL*Plus: (Notation these notes: [ ] optional, { } must contain something)

Notation Syntax Description


(Keywords U-Case)
SELECT SELECT [DISTINCT] {*, column [alias],} Select and identify which columns
FROM FROM table Identifies which table ( ; - runs the statement)
WHERE [WHERE condition (s)] Restrict selection
ORDER BY [ORDER BY {column, expr, alias} [ASC|DESC]]; Order ascending or descending

; runs the SQL statement

/ runs the SQL statement or PL/SQL block


(also a mathematical operator)
* SELECT * Select all (*) columns
FROM Dept; from table called dept

SELECT deptno, loc Select deptno and location columns


FROM Dept; (displayed in order of declaration)

AS SELECT deptno AS department_number, loc AS location Gives columns alias (AS) names (default of upper case - no
FROM Dept; spaces allowed)

SELECT deptno department_number, loc location AS can be omitted


FROM Dept;

"" SELECT deptno AS "Department Number", loc AS Gives alias case format and spaces allowed
"Location"
FROM Dept;

+ SELECT ename, sal, sal+300 Add 300 to salary figure and display as sal+300 with other
FROM emp; columns
- SELECT ename, sal, sal-300 subtract 300 from salary figure and display as sal-300 with
Notation Syntax Description
(Keywords U-Case)
FROM emp; other columns
* SELECT ename, sal, sal*12 AS "Annual Salary" multiply salary figure by 12 and display as Annual Salary
FROM emp; with the other columns ename and sal.
/ SELECT ename, sal, sal/1.15 divide salary figure by 1.15 and display as sal/1.15 with
FROM emp; other columns
Operator Precedence * / + - (then left to right)
() SELECT ename, sal, 12*(sal+100) Adds 100 to salary and then multiplies by 12 displayed as
FROM emp; 12*(sal+100)
Parentheses override rules of Operator Precedence (* / + -
[then left to right])
|| SELECT ename||job AS "Employees" Concatenates (joins together) ename and job in a column
FROM emp; called Employees

SELECT ename||' is a '||job AS "Employee Details" Displays ename is a job in a column called Employee
FROM emp; Details

DISTINCT SELECT deptno Displays all occurrences of deptno in emp table


FROM emp;

SELECT DISTINCT deptno Displays each deptno in emp table (eliminating


FROM emp; duplicates)

DESC[RIBE] DESCRIBE tablename tablename = any existing table, view, or synonym


(SQL*Plus) accessible to the user. Can be abbreviated to DESC

DESCRIBE emp Displays column name, whether can be null, and data type
of table emp (Doesnt require semi-colon)

A[PPEND] A[PPEND] text Adds text to the end of the current line
Notation Syntax Description
(Keywords U-Case)
(SQL*Plus Editing)
C[HANGE] C[HANGE] / old / new Changes old text to new in the current line
(SQL*Plus Editing)
C[HANGE] / text / Deletes text from the current line

CL[EAR] BUFF[ER] CL BUFF Deletes all lines from the SQL buffer (like a clipboard)
(SQL*Plus Editing)

CL[EAR] SCR[EEN] CL SCR Clears screen


(SQL*Plus Editing)

DEL DEL Deletes current line


(SQL*Plus Editing) DEL n Deletes line n
DEL m n Deletes line m to n

I[NPUT] I[NPUT] Inserts an indefinite number of lines


(SQL*Plus Editing) I[NPUT] text Inserts a line consisting of text.

L[IST] L[IST] Lists all lines in the SQL buffer


(SQL*Plus Editing) L[IST] DEL n Lists line n
L[IST] DEL m n Lists line m to n

R[UN] R Displays and runs the current SQL statement in the buffer
(SQL*Plus Editing) Displays and runs a SQL statement from file
R filename
n Specifies the line to make the current line
(SQL*Plus Editing)
Notation Syntax Description
(Keywords U-Case)
n text Replaces line n with text
(SQL*Plus Editing)

0 text Inserts a line before line 1


(SQL*Plus Editing)
SAV[E] SAV filename [.ext] Saves buffer contents to a file (default extension .sql)
(SQL*Plus File) SAV filename [.ext] REP[LACE] Overwrites an existing file with buffer contents
SAV filename [.ext] App[end] Adds buffer contents on to the contents of an existing file
GET GET filename [.ext] Writes the contents of a file to buffer
(SQL*Plus File)
STA[RT] STA filename [.ext] Runs a file
(SQL*Plus File)
@ @ filename [.ext] Runs a file (as START)
(SQL*Plus File)
ED[IT] ED Invokes editor and saves buffer to a file afiedt.buf
(SQL*Plus File) ED [filename] [.ext] Invokes the editor and gets a saved file

SPO[OL] SPO [filename] [.ext] Stores query results in a file.


(SQL*Plus File) SPO [filename] [.ext] OFF OFF closes the spool file.
SPO [filename] [.ext] OUT OUT closes the spool file and sends the file results to the
system printer.
EXIT Leaves SQL*Plus
(SQL*Plus File)
Notation Syntax Description
(Keywords U-Case)
WHERE SELECT [DISTINCT] {*, Column [Alias],} WHERE restricts the query to rows that meet a condition
FROM Table; composed of column names, expressions, constants, and a
WHERE Condition (S); comparison operator
(column name / comparison operator / column name,
WHERE expr operator value constant, or list of values)

= SELECT ename, job, deptno Selection restricted to where job is eqaul to clerk (character
FROM emp strings are case sensitive)
WHERE job='CLERK';

> WHERE sal>1500 Greater than


>= WHERE sal>=1500 Greater than or equal to
< WHERE sal<1500 Less than
<= WHERE sal<=1500 Less than or equal to
<> WHERE sal<>1500 Not equal to
BETWEEN AND WHERE sal BETWEEN 1000 AND 1500 Within a range
IN WHERE ename IN ('FORD', 'ALLEN') Values in a specified list
LIKE WHERE ename LIKE 'S%' Where ename starts with S (% any sequence of zero or
more characters)
WHERE hiredate LIKE '%1981' Employees started during 1981
WHERE ename LIKE '_A%' Where ename has second letter A (_ is any one character,
__ is any two etc)
IS NULL WHERE mgr IS NULL
Where value unassigned, unavailable, unknown, or
inapplicable
AND WHERE sal>=1100
AND job='CLERK' Returns TRUE if both component conditions are TRUE
Notation Syntax Description
(Keywords U-Case)
OR WHERE sal>=1100 Returns TRUE if one component condition is TRUE
OR job='CLERK'

NOT WHERE job NOT IN ('CLERK', 'MANAGER') Excludes clerks and managers from the selection.
(Precedence: All comparison operators/NOT/AND/OR

ORDER BY SELECT ename, job, deptno, hiredate ORDER BY comes last in the SELECT statement
FROM emp Default is ascending (ASC)
ORDER BY hiredate; (can use column alias to order by if applicable)

DESC SELECT ename, job, deptno, hiredate Order descending


FROM emp
ORDER BY hiredate DESC;

SELECT ename, deptno, sal Orders by deptno ascending (default) and then salary
FROM emp descending
ORDER BY deptno, sal DESC;
Notation Syntax Description
(Keywords U-Case)
LOWER LOWER(column|expression) Converts alpha character values to lowercase

SELECT 'The job title for ' || INITCAP(ename) || ' is ' || Gives column EMPLOYEE DETAILS with string
LOWER(job) AS "EMPLOYEE DETAILS" including ename with first letter uppercase and job in lower
FROM emp; case

UPPER UPPER(column|expression) Converts alpha character values to uppercase

SELECT empno, ename, deptno Without UPPER the SELECT would fail - looking for a
FROM emp lowercase entry. Also useful for stopping entry of names in
WHERE ename = UPPER ('blake'); non-standard case.
INITCAP INITCAP(column|expression) Converts alpha character values to uppercase for the first
letter of each word, all other letters in lowercase

INITCAP('SQL COURSE') Result = Sql Course


(see also LOWER example)

CONCAT CONCAT(column1|expression1, column2|expression2) Concatenates the first character value to the second
character value; equivalent to concatenation operator (||)

SELECT CONCAT(ename, ' is an employee.') AS Lists ename with comments


employees XXXXXOnly used to connect two character values?XXX
FROM emp;
Notation Syntax Description
(Keywords U-Case)
SUBSTR SUBSTR(column|expression, m [n]) Returns specified characters from character value starting
at character position m, n characters long. (If m is -ve, the
count starts from the end of the character value. If n is
omitted, all characters to the end of the string are returned.)

SELECT SUBSTR(ename, 1, 4) AS abbreviated Lists first 4 characters of ename


FROM emp;

SELECT ename, job Lists enames where first 5 characters of job are SALES
FROM emp
WHERE SUBSTR (job, 1, 5) = 'SALES';

LENGTH LENGTH(column|expression) Returns the number of characters in a value

SELECT ename, LENGTH(ename) AS "How long?" Lists ename and number of characters
FROM emp;

INSTR INSTR(column|expression, m) Returns the numeric position of a named character

SELECT ename, INSTR(ename, 'N') AS "Where's N?" Lists ename and position of N in enames (0 = no N)
FROM emp;
Notation Syntax Description
(Keywords U-Case)
LPAD LPAD(column|expression, n, 'string') Pads the character value right-justified to a total width of
n character positions

LPAD(sal, 10, '*') Result = ******5000


(see TRIM examples) RPAD = 5000******

TRIM TRIM(leading|trailing|both, trim_character FROM Enables you to trim heading or trailing characters (or both)
trim_source) from a character string. If trim_character or trim_source is
a character literal, you must enclose it in single quotes.
(feature on 8i onwards only)
SELECT TRIM ('S' FROM ename) AS name Trims S from either side of ename where it occurs
FROM emp;

SELECT RTRIM(LPAD(ename, 10, '*'),'S') AS name Trims S from right side of ename where it occurs after
FROM emp; LPAD. NOTE: This syntax for LTRIM & RTRIM not
TRIM
SELECT LPAD (TRIM('S' FROM ename), 10, '*') AS Trims before LPAD
name
FROM emp;
Notation Syntax Description
(Keywords U-Case)
ROUND ROUND (column|expression, n) Rounds the column, expression, or value to n decimal
places or if n is omitted, no decimal places. If n is
negative, numbers to left of the decimal point are rounded.

SELECT ROUND (45.923, 2), ROUND (45.923, 0), Gives 45.92, 46, 50
ROUND (45.923, -1)
FROM dual;

SELECT empno, hiredate, ROUND(hiredate, 'MONTH'), Selects by hiredate (82) and gives hiredate as is, rounded
TRUNC(hiredate, 'MONTH') (up/down), and truncated (down)
FROM emp
WHERE hiredate LIKE '%82';

TRUNC TRUNC (column|expression, n) Truncates the column, expression, or value to n decimal


places or if n is omitted, no decimal places. If n is
negative, numbers to left of the decimal point are truncated

SELECT TRUNC (45.923, 2), TRUNC (45.923, 0), Gives 45.92, 45, 40
TRUNC (45.923, -1)
FROM dual;

(see also ROUND example - dates)


MOD MOD (m, n) Returns the remainder of m divided by n.

SELECT MOD (16, 5) Returns 1 (16/5 = 3 and 1 left over)


FROM dual;
Notation Syntax Description
(Keywords U-Case)
SYSDATE SELECT SYSDATE Returns today's date as DD-MMM-YY
FROM dual;
MONTHS_BETWEEN MONTHS_BETWEEN(date 1, date 2) Number of months between two dates

SELECT ROUND(MONTHS_BETWEEN('20-MAY-2005' Rounds to the nearest month time till I'm 50


, SYSDATE)) AS "Months till I'm 50"
FROM dual;

ADD_MONTHS ADD_MONTHS(date, n) Add n calendar months to date

SELECT 'In 6 months the date will be '|| Returns the date in 6 months time within a sentence
ADD_MONTHS(sysdate, 6)||' wont it?'
FROM dual;

NEXT_DAY NEXT_DAY(date, 'char') Finds the date of the next specified day

SELECT 'Next weekend starts on Friday the '|| Returns the date of next Friday in a sentence
NEXT_DAY(SYSDATE, 'FRIDAY')
FROM dual;
LAST_DAY LAST_DAY(date) Finds the date of the last day of the month within the date

SELECT LAST_DAY(SYSDATE) Gives the date of the last day of this month
FROM dual;
Notation Syntax Description
(Keywords U-Case)
TO_DATE TO_DATE (char [, fmt]) Convert a character string to a date format

SELECT ROUND(TO_DATE('20-MAY-2005') - A frightening number!


SYSDATE) AS "Days till I'm 50"
FROM dual;

TO_CHAR TO_CHAR(date, 'fmt') Valid fmt's = YYYY (number), YEAR (text),


(With Dates) MM (2 digit), MONTH (full name), DY (three letter), DAY
(full name) - [see Date Format Table for fuller list]
fm = fill mode - makes it look better
SELECT TO_CHAR(SYSDATE, 'day') Returns today's day
FROM dual;

SELECT TO_CHAR(SYSDATE + 45, 'month') Returns month in 45 days time


FROM dual;

SELECT ename, TO_CHAR(hiredate, 'fmDDspth "of" (see Date Format Table)


Month YYYY fmHH:MI:SS AM') AS hiredate
FROM emp;

SELECT 'On the ' || TO_CHAR((TO_DATE('19-JAN-01')- Sentence saying reminder due 6 weeks before date.
(7*6)), 'fmDDSPTH "day of" fmMONTH "in the year"
YYYY') || ' I should check that Peter has booked my SQL
exam.' AS " "
FROM dual;
Notation Syntax Description
(Keywords U-Case)
TO_CHAR TO_CHAR(number, 'fmt') Set format of display for a number
(With Numbers)
SELECT ename AS "Name", Displays name and salary as dollars
TO_CHAR (sal,'$99,999') AS "Salary"
FROM emp;
TO_NUMBER TO_NUMBER (char[, 'fmt']) Convert a character string to a number format

SELECT TO_NUMBER ('1000') Converts character string '1000' to number 1000


FROM emp;
NVL NVL (expr1, expr2) Converts null to an actual value. Datatypes must remain
same
NVL (number_column, number) Number datatype
SELECT NVL(comm, 0) Converts null values in comm to zero
FROM emp; (NVL(comm, 100) changes them to 100)

NVL (date_column, date) Date datatype


SELECT NVL (hiredate, '01-JAN-95') Converts null to a date
FROM emp; Would convert any null values in hiredate to 01-JAN-95

NVL (character_column, 'text') Character data


SELECT NVL(job, ' No Job') Converts null to characters
FROM emp; Would convert any null values in job to "No Job"

SELECT AVG(comm), AVG(NVL(comm, 0)) NVL forces a group function to count null values as 0
FROM emp;
Notation Syntax Description
(Keywords U-Case)
DECODE DECODE (col/expression, search1, result1[, search2, Facilitates conditional inquiries by doing the work of a
result2, ,] [, default]) CASE or IF-THEN-ELSE statements

SELECT job, sal, As for an IF-THEN-ELSE statement:


DECODE (job, 'ANALYST', SAL*1.1, IF job = 'ANALYST' THEN sal = sal*1.1
'CLERK', SAL*1.15, IF job = 'CLERK' THEN sal = sal*1.15
'MANAGER', SAL*1.20, IF job = 'MANAGER' THEN sal = sal*1.20
SAL) ELSE sal = sal
AS revised_salary
FROM emp; (see also p05q11)

Equijoin WHERE table1.column = table2.column Joins table where two columns are the same. Often
Primary and Foreign Keys
SELECT emp.empno, emp.ename, emp.deptno, dept.loc Adds location from dept to info retrieved from emp.
FROM emp, dept Prefixing column with table name identifies ambiguous
WHERE emp.deptno = dept.deptno; column names (e.g. emp.deptno vs dept.deptno) also
improves performance. For more than 2 tables use
WHEREAND table2.column = table3.column etc.

SELECT emp.empno, emp.ename, emp.deptno, dept.loc AND additional search conditions where required.
FROM emp, dept
WHERE emp.deptno = dept.deptno
AND INITCAP(ename) = 'King';

SELECT e.empno, e.ename, e.deptno, d.loc Saves long prefixes but must be used throughout the select
Table aliases FROM emp e, dept d statement (alias valid for select statement only).
WHERE e.deptno = d.deptno; Alias up to 30 chars, but short as pos, make meaningful.
Notation Syntax Description
(Keywords U-Case)
Non-equijoin WHERE table1.column Where the join is conditional
CONDITION table2.column/s

SELECT e.ename, e.sal, s.grade Selects name, salary, and grade identifying grade by
FROM emp e, salgrade s checking where the salary is between the grade high & low
WHERE e.sal BETWEEN s.losal AND s.hisal; salary columns

Outer join SELECT table1.column, table2.column (+) returns missing rows where there is no direct match
FROM table1, table2
WHERE table1.column = table2.column (+);

SELECT e.ename, e.deptno, d.dname Does not display d.dname - OPERATIONS (there is no-one
FROM emp e, dept d in that dept.)
WHERE e.deptno = d.deptno;

SELECT e.ename, e.deptno, d.dname Displays d.dname - OPERATIONS once (no ename/deptno
FROM emp e, dept d next to it) - adding that which is not included in emp.
WHERE e.deptno (+) = d.deptno; Placing the (+) after d.deptno does not display
OPERATIONS
SELECT e.ename, d.deptno, d.dname Switching e.deptno to d.deptno displays 40 &
FROM emp e, dept d OPERATIONS
WHERE e.deptno (+) = d.deptno;
Notation Syntax Description
(Keywords U-Case)
Self join SELECT table1alias1.column1, table1alias2.column1 An equijoin where a table relationship is to the same table,
FROM table1 alias1, table1 alias2 see example below.
WHERE table1alias1.column2 = table1alias2.column3

SELECT worker.ename || ' works for ' || manager.ename Does not show King as he has no manager
FROM emp worker, emp manager
WHERE worker.mgr = manager.empno;

SELECT worker.ename || ' works for ' || (+) ensures King is listed
NVL(manager.ename, 'the shareholders') NVL inserts 'the shareholders' where no manager exists
FROM emp worker, emp manager
WHERE worker.mgr = manager.empno(+);

Set operators XXXXXXXX??????????????????

AVG AVG ([DISTINCT|ALL]n) Average value of n ignoring null values. ALL is default on
all group functions.

SELECT ROUND(AVG(sal), 2), Average of salaries rounded to 2 decimal places


MAX(sal), Maximum value of salaries paid
MIN(sal), Minimum value of salaries paid
SUM(sal), Sum of salaries paid
COUNT(comm), Count of commissions paid
COUNT(DISTINCT sal), Count of different salaries
COUNT(*), Count of all rows in table
ROUND(VARIANCE (sal) , 2), Variance of salaries paid
ROUND(STDDEV (sal), 2) Standard deviation of salaries paid
FROM emp;
Notation Syntax Description
(Keywords U-Case)
COUNT COUNT ({*|[DISTINCT|ALL]expr}) Number of rows, where expr evaluates to something other
than null (Count all selected rows using *, including
duplicates and rows with nulls) expr means CHAR,
VARCHAR2, NUMBER, or DATE

MAX MAX ([DISTINCT|ALL]expr) Maximum value of expr, ignoring null values (Char - last
in alphabetical order)
MIN MIN ([DISTINCT|ALL]expr) Minimum value of expr, ignoring null values(Char - first in
alphabetical order)
STDDEV STDDEV ([DISTINCT|ALL]x) Standard deviation of n, ignoring null values

SUM SUM ([DISTINCT|ALL]n) Sum values of n, ignoring null values

VARIANCE VARIANCE ([DISTINCT|ALL]x) Variance of n, ignoring null values


Notation Syntax Description
(Keywords U-Case)
GROUP BY GROUP BY column Returns group functions by group specified

SELECT deptno, SUM(sal), Sum of sal by deptno


COUNT(sal), Count of sal by deptno
ROUND(AVG(sal), 2), Average of sal by deptno to two decimal places
SUM(comm), Sum of comm by deptno to two decimal places
COUNT(comm), Count of comm by deptno to two decimal places
ROUND(AVG(comm) , 2) Average of comm by deptno to two decimal places
FROM emp (null returns on comm for deptno 10 & 20)
GROUP BY deptno;

SELECT deptno, job, sum (sal) Returns sum of salary by deptno and job
FROM emp
GROUP BY deptno, job;

HAVING HAVING group_condition Used to restrict groups because WHERE does not work
with groups, WHERE has to be used prior to the group
clause
SELECT deptno, MAX (sal), TRUNC(AVG (sal),) Returns maximum salary and truncated average salary for
FROM emp departments that have a maximum salary of more than
GROUP BY deptno 2900.
HAVING MAX (sal)>2900;
Notation Syntax Description
(Keywords U-Case)
Subqueries SELECT select_list Used to select a condition on which a SELECT statement is
FROM table based.
WHERE expr operator Do not add an ORDER BY clause to a subquery
(SELECT select_list
FROM table);

single-row subquery SELECT ename, job Two single-row subqueries.


FROM emp
WHERE job =
(SELECT job
FROM emp
WHERE empno = 7369)
AND sal >
(SELECT sal
FROM emp
WHERE empno = 7876);

SELECT ename, job, sal Subquery using a group function


FROM emp
WHERE sal =
(SELECT MIN(sal)
FROM emp);
Notation Syntax Description
(Keywords U-Case)
Multiple-row subquery SELECT empno, ename, job Use of ANY
FROM emp If a null value is expected to be returned in a suquery NOT
WHERE sal < ANY
(SELECT sal
IN will return a null value. SELECT statement should be
FROM emp structured to use an IN, it will then return the other values
WHERE job = 'CLERK') selected
AND job <> 'CLERK';

SELECT empno, ename, job


Use of ALL
FROM emp
WHERE sal > ALL
(SELECT AVG(sal)
FROM emp
GROUP BY deptno

Multiple-column SELECT column, column,. Pairwise comparison


subquery FROM table
WHERE(column, column, .) IN
(SELECT (column, column, .
FROM table
WHEREcondition);

SELECT column, column,. Nonpairwise comparison


FROM table
WHEREcolumn IN
(SELECT column
FROM table
WHEREcondition)
AND column IN
(SELECT column
FROM table
WHEREcondition)
[AND..];
Notation Syntax Description
(Keywords U-Case)
ANY WHERE column operator ANY condition Used in subqueries.
(see subqueries for an example)

ALL WHERE column operator ALL condition Used in subqueries.


(see subqueries for an example)

& SELECT empno, ename, sal, deptno & Calls the variable or prompts for a value if the variable
FROM emp does not already exist
WHERE empno = &employee_num; Value discarded once used

SELECT ename, deptno, sal *12 Single quotes for dates and character values
FROM emp Can use UPPER, LOWER, & INITCAP with character
WHERE job = '&job_title'; values, e.g. WHERE job = UPPER('&job_title');

SELECT ename, &column_name Can be used for names, conditions, expressions, and text
FROM emp e.g. WHERE &condition, ORDER BY &clause. Even
WHERE &condition; whole select statement - SELECT &Select_statement
&& SELECT empno, ename, job, &&column_name Prompts for column_name once and reuses it as necessary.
FROM emp Has to be UNDEFINE'd to change or use DEFINE or
ORDER BY &column_name; ACCEPT to redefine i.e. repeating &&column_name gives
an error message. Value also lost when SQL exited
Notation Syntax Description
(Keywords U-Case)
DEFINE DEFINE Lists all variable values

DEFINE variable Returns specific variable value

DEFINE variable = value Defines a varable as a CHAR datatype

DEFINE column_name = 'deptno' Defines column name and uses it when the & calls it
SELECT empno, ename, job, &column_name
FROM emp
ORDER BY &column_name;

UNDEFINE UNDEFINE variable Undefines the named variable

UNDEFINE column_name Undefines column name. Next & or &&


(&&column_name) gives a prompt for a value
Notation Syntax Description
(Keywords U-Case)
ACCEPT ACCEPT variable [datatype] [FORMAT format] Reads a line of user input and stores it in a variable - if the
[PROMPT text] [HIDE] variable does not exist SQL*Plus creates it

datatype NUMBER, CHAR (max 240 bytes), or DATE. DATE


checks against a format model, and the datatype is CHAR

FOR[MAT] Specifies the format model, e.g. A10 or 9.999

PROMPT text Displays the text before the user can enter the value

HIDE Suppresses user input, e.g. use for passwords

ACCEPT dept PROMPT 'Provide the department XXXXXXXXXXNot working - takes the SELECT * as the
name: ' variable value!!!!!!!!!!!!!!!!!!!!!!!!!!XXXXXXX
SELECT *
FROM dept
WHERE dname = UPPER ('&dept');
Notation Syntax Description
(Keywords U-Case)
SET SET system_variable value SET commands customise the SQL*Plus Environment

VERIFY SET VERIFY ON SQL*Plus command which toggles display of text before
SET VERIFY OFF and after variables substituted by a value
(demonstrate with & example)
ECHO SET ECHO ON Controls whether the START command lists each
SET ECHO OFF command in a command file as the command is executed.
ON lists the commands; OFF suppresses the listing.
ARRAYSIZE ARRAY[SIZE] {20 | n} Sets the database data fetch size
(Underlined value represents default)
COLSEP COLSEP {_ | text} Sets text to be printed between columns (default single
space)
FEEDBACK FEED[BACK] {6 | n | OFF | ON} Displays the number of records returned by a query when
the query selects at least n records
HEADING HEA[DING] {OFF | ON} Determines whether column headings are displayed in
reports
LINESIZE LIN[ESIZE] {80 | n} Sets the number of characters per line to n for reports

LONG LOG {80 | n} Sets the maximum width for displaying LONG values

PAGESIZE PAGES[IZE] {24 | n} Specifies the number of lines per page of output

PAUSE PAU[SE] {OFF | ON} Controls scrolling of the terminal (press [RETURN] after
seeing each paused screen)
TERMOUT TERM[OUT] {OFF | ON} Determines whether output is displayed on screen

login.sql Contains std SET and other SQL*Plus commands. Can use to add permanent changes to set up for each set up,
otherwise all the above make alts for session only
Notation Syntax Description
(Keywords U-Case)
COLUMN COL[UMN] [column option] Formats column display

Controls: CLE[AR] - clears any column formats


FOR[MAT] format - changes the display of the
column using a format model
HEA[DING] text - sets the column heading. (A
vertical line | will force a line feed in the
heading if you do not use justification.)
JUS[TIFY] - {align}
NOPRI[NT] hides the column
NUL[L] text - specifies the text for null values
PRI[NT] - shows the column
TRU[NCATED] - Truncates the string at the end
of the first line of display
WRA[PPED] - Wraps the end of the string to the
next line

Format Models:
An Sets a display width of n
9 Single zero-suppression digit 999999 1234
0 Enforces leading zero 099999 001234
$ Floating dollar sign $9999 $1234
L Local currency L9999 1234
. position of decimal point 9999.99 1234.00
, Thousand separator 9,999 1,234

COLUMN ename HEADING 'Employee|Name' FORMAT e.g. formatting columns ename, sal, and mgr
A15
COLUMN sal JUSTIFY LEFT FORMAT $99,990.00
COLUMN mgr FORMAT 999999999 NULL 'No manager'
Notation Syntax Description
(Keywords U-Case)

COL[UMN] Displays all column formats


COL[UMN] ename Displays ename column formats

COL[UMN] ename CLE[AR] Clears all formatting for ename


CL[EAR] COL[UMN] Clears all column settings

TTITLE TTITLE [text | OFF | ON] Specifies header to appear at the top of each page

BTITLE BTITLE [text | OFF | ON] Specifies a footer to appear at the bottom of each page of
the report
BREAK BRE[AK] [ON report_element] Suppresses duplicate values and sections rows of data with
line feeds. Use ORDER BY on columns using break on.
Notation Syntax Description
(Keywords U-Case)
Sample Report SET PAGESIZE 37 Page Size
SET LINESIZE 60 Line Length
SET FEEDBACK OFF
TTITLE 'Employee|Report' Page Title
BTITLE 'Confidential' Page Footer
BREAK ON job Print job tile once (ORDERed BY job)
COL job HEADING 'Job|Category' FORMAT A15 Formatting required columns including a calculated field
COL ename HEADING 'Employee' FORMAT A15
COL sal HEADING 'Salary' FORMAT $99,999.99
COL sal*12 HEADING 'Annual Salary' FORMAT
$99,999.99
SELECT job, ename, sal, sal*12 The select statement
FROM emp
WHERE sal < 3000
ORDER BY job, ename
/
SET FEEDBACK ON
COL job CLE Clear column formats set above
COL ename CLE
COL sal CLE
COL sal*12 CLE
Notation Syntax Description
(Keywords U-Case)
INSERT INTO INSERT INTO table [(column [, column])] Adds a new row. (One row at a time).
FROM (value [, value]);

INSERT INTO dept (deptno, dname, loc) Puts values into each field in the row
VALUES (50, 'DEVELOPMENT', 'DETROIT');

INSERT INTO dept (deptno, dname) Implicit method of inserting a null value (into loc) -
VALUES (60, 'MIS'); omitting column name

INSERT INTO dept Explicit method of inserting a null value


VALUES (70, 'FINANCE', NULL); Columns filled in order of appearance in table rather than
in order stated in 1st example

INSERT INTO emp (empno, ename, job, mgr, hiredate, Inserting special values - current user name and current
sal, comm, deptno) date
VALUES (7196, USER, 'SALESMAN', 7782,
SYSDATE, 2000, NULL, 10);

INSERT INTO emp Inserting a date


VALUES (2296, 'AROMANO', 'SALESMAN', 7782,
TO_DATE('FEB 3, 1997', 'MON DD, YYYY'),
1300, NULL, 10);

INSERT INTO dept (deptno, dname, loc) Using substitution variables. Customise prompts by using
VALUES ('&department_ID', '&department_name', ACCEPT command.
'&location'); (UPPER('&department_ID'),
UPPER('&department_name'), UPPER('&location'));
eliminates uppercase entry requirement
Notation Syntax Description
(Keywords U-Case)
INSERT (cont) INSERT INTO managers (id, name, salary, hiredate) Copies rows from another table using a subquery (For
SELECT empno, ename, sal, hiredate creation of managers table see CREATE TABLE example
FROM emp using a subquery)
WHERE job = 'MANAGER';

UPDATE UPDATE table Modify existing rows. Can update more than one row at a
SET column = value [ , column= value, time, if required.
[WHERE condition];

UPDATE emp Changes deptno for emp 7782. No WHERE clause would
SET deptno = 20 mean all employees changed to deptno 20
WHERE empno = 7782; Integrity Constraint would prevent deptno 21 being
entered (deptno is a foreign key)
UPDATE emp
SET (job, deptno) = Updates emp 7698 with same job and deptno as emp 7499
(SELECT job, deptno using a multi-column subquery
FROM emp
WHERE empno =7499)
WHERE empno = 7698;

UPDATE employee Changes the deptno in table employee for those employees
SET deptno = (SELECT deptno with a job like emp 7788 to the same dept (as in per the
FROM emp date in table emp).
WHERE empno = 7788)
WHERE job = (SELECT job
FROM emp
WHERE empno = 7788);
Notation Syntax Description
(Keywords U-Case)
DELETE DELETE [FROM] table Remove existing rows from a table
[WHERE condition];

DELETE FROM dept Deletes a specific row or rows. Omitting the WHERE
WHERE dname = 'DEVELOPMENT'; clause deletes all rows in the table. If row deleting has a
key used elsewhere as a foreign key Integrity Constraint
DELETE FROM emp prevents deletion
WHERE deptno =
(SELECT deptno Deletes using subquery
FROM dept
WHERE dname = 'SALES');
COMMIT COMMIT Ends the current transaction by making all pending data
changes permanent (Action can not be undone)
SAVEPOINT SAVEPOINT name Makes a savepoint within the current transaction

ROLLBACK ROLLBACK Undoes all pending (un-committed) data changes

ROLLBACK [savepoint_name] Rolls back only to savepoint named


Notation Syntax Description
(Keywords U-Case)
CREATE TABLE CREATE [GLOBAL TEMPORARY] TABLE [ schema.] table Must have CREATE TABLE privilege & a storage area
(column datatype [DEFAULT expr] [,]); You specify: - Table name
- Column name, column datatype, and
CREATE TABLE shallambeer
column size
(BeerID NUMBER (4),
BeerName VARCHAR2 (20),
GLOBAL TEMPORARY - Specifies that the table is
ABV NUMBER (3, 2),
temporary and definition is visible to all sessions
PriceGallon NUMBER (4,2);
Schema - Same as the owners name. To reference another
users table need to prefix the table with the users name.
(hiredate DATE DEFAULT SYSDATE, ) DEFAULT expr specifies default value if a value is omitted
in the INSERT statement

CREATE TABLE managers Creating a table from a subquery


AS
SELECT empno AS id, ename AS name, sal
AS salary, hiredate
FROM emp
WHERE job = 'MANAGER';
Notation Syntax Description
(Keywords U-Case)
ALTER TABLE ALTER TABLE table Adding a column
ADD ADD (column datatype [DEFAULT expr]
[,column datatype..]);

ALTER TABLE chicken_grill_pizza Adds column called comments


ADD (Comments VARCHAR2 (80)
DEFAULT 'Very tastey');

MODIFY ALTER TABLE table Modifies an existing column


MODIFY (column datatype [DEFAULT expr]
[,column datatype..]);

ALTER TABLE chicken_grill_pitza Modifies datatype length and default. Cannot change data
MODIFY (Comments VARCHAR2 (100) type unless column is empty.
DEFAULT 'Like vinegar');

DROP COLUMN ALTER TABLE table Remove a column (does not have to be empty).
DROP COLUMN column;

ALTER TABLE shallambeer


DROP COLUMN comments;

SET UNUSED ALTER TABLE table Removes column from use so that it can be deleted later
SET UNUSED (column); when demand on system resources is less. Column data no
longer available.
DROP UNUSED ALTER TABLE table Deletes all columns which have been previously marked
DROP UNUSED COLUMNS; unused.
Notation Syntax Description
(Keywords U-Case)
DROP TABLE DROP TABLE table; Deletes named table - definition, data, associated indexes

RENAME RENAME old_name TO new_name Change the name of an object - table, view, sequence, or
synonym. (you must be the owner of the table to rename it)
TRUNCATE TRUNCATE TABLE table; Releases all rows from a table to release storage space
(TRUNCATE cannot be rolled back, alternative is to use
DELETE but it does not release storage space.)
COMMENT COMMENT ON TABLE table | COLUMN table.column Adds a comment (up to 2000 bytes) about a table, column,
IS 'text'; view, or snapshot. Comment stored in the data dictionary.
View comments in: - ALL_COL_COMMENTS
- USER_COL_COMMENTS
COMMENT ON TABLE emp - ALL_TAB_COMMENTS
IS 'Employee information'; - USER_TAB_COMMENTS

SELECT comments Views comments on table emp


FROM ALL_TAB_COMMENTS
WHERE table_name = 'EMP';

COMMENT ON TABLE emp 'Drops' a comment by replacing with a space.


IS '';
Notation Syntax Description
(Keywords U-Case)
CONSTRAINT CREATE TABLE [schema] table Setting constraints when the table is created
Defining when creating (column datatype [DEFAULT expr] To view USER_CONSTRAINTS &
the table [column_constraint], USER_CONS_COLUMNS data dictionary
(See Glossary for more Naming convention for column constraints -
information) [table_constraint] [,]; table_column_pk - PRIMARY KEY
table_column_fk - FOREIGN KEY
CREATE TABLE shallamdelivery table_column_uk - UNIQUE
(DelvID NUMBER (6), table_column_nn - NOT NULL
CustID NUMBER (4) table_column_ck - CHECK
CONSTRAINT shallamdelivery_CustID_nn
NOT NULL, Setting a NOT NULL constraint
DelvDate DATE DEFAULT SYSDATE,
DutyRate NUMBER (5, 2)
CONSTRAINT shallamdelivery_DutyRate_nn
NOT NULL,
OrderNo NUMBER (6),
CONSTRAINT shallamdelivery_DelvID_pk
PRIMARY KEY (DelvID), Setting a PRIMARY KEY
CONSTRAINT shallamdelivery_CustID_fk
FOREIGN KEY (CustID) Setting a FOREIGN KEY
REFERENCES shallamcustomer (CustID));

CONSTRAINT shalamdelivery_CustDD_uk
UNIQUE (CustID, DelvDate) If this UNIQUE KEY were set it would prevent deliveries
on the same day to a particular customer being entered.
Notation Syntax Description
(Keywords U-Case)
ADD CONSTRAINT ALTER TABLE table ADD a CONSTRAINT to an existing table
to an existing table ADD CONSTRAINT constraint_name Ensures a value between 10 & 99 is used for DeptNo
type (column [constraint]); Cannot add NOT NULL by this method - see below

ALTER TABLE emp


ADD CONSTRAINT emp_DeptNo_ck
CHECK (DeptNo BETWEEN 10 AND 99);

ALTER TABLE emp Adding a NOT NULL constraint to an existing table


MODIFY (DeptNo NOT NULL); (Does not appear to be a way of naming the constraint by
this method - receives a SYS_C999999 code from Oracle)

DROP CONSTRAINT ALTER TABLE table Deleting a constraint


DROP CONSTRAINT constraint_name;

ALTER TABLE emp


DROP CONSTRAINT emp_DeptNo_ck;

ALTER TABLE emp Dropping a primary key and cascading to remove


DROP PRIMARY KEY CASCADE; dependant constraints (will not delete if there are foreign
keys using it)
DISABLE ALTER TABLE table Can also DISABLE in CREATE TABLE.
DISABLE CONSTRAINT constraint_name [CASCADE]; CASCADE clause disables dependent integrity constraints

ENABLE ALTER TABLE table Activates an integrity constraint currently disabled. All
DISABLE CONSTRAINT constraint_name; data in the table must currently fit the CONSTRAINT
Can also ENABLE in CREATE TABLE.
Notation Syntax Description
(Keywords U-Case)
USER_CONSTRAINTS SELECT constraint_name, constraint_type, Viewing constraints in data dictionary table
search_condition user_constraints by table
FROM user_constraints
WHERE table_name = 'EMP';

USER_CONS_COLUMNS SELECT constraint_name, column_name Viewing constraints in user_cons_columns


FROM user_cons_columns
WHERE table_name = 'EMP';
Notation Syntax Description
(Keywords U-Case)
VIEW CREATE [OR REPLACE] [FORCE | NOFORCE] VIEW view The subquery cannot contain an ORDER BY clause
[(alias[, alias])] OR REPLACE recreates the view if it already exists
AS subquery FORCE creates the view even if tables dont exist
[WITH CHECK OPTION [CONSTRAINT constraint] ] NOFORCE creates the view only if tables dont exist (default)
[WITH READ ONLY]; view view name (if nt named Oracle defines with SYS_Cn
alias specifies names for the expressions selected by the
views query (number aliases must match number of
expressions)
subquery complete subquery (can use aliases for columns in
SELECT list)
WITH CHECK OPTION specifies that only rows accessible to the
view can be inserted or updated
constraint name of CHECK option constraint
WITH READ ONLY ensures that no DML operations can be
performed

CREATE VIEW empvu10 Creating a simple view


AS SELECT empno AS EMPLOYEE_NUMBER, ename AS name, DESC view Describes view structure
sal AS SALARY
FROM emp
WHERE deptno = 30;

SELECT * Retrieving data from a view (ORDER BY alias not original column
FROM empvu10 name)
ORDER BY NAME;

DROP VIEW empvu10; Deletes view

Modify a VIEW CREATE OR REPLACE VIEW empvu10 Recreates the view created above but defining aliases in CREATE
(EMPLOYEE_NUMBER, NAME, SALARY) VIEW clause instead of the SELECT statement
AS SELECT empno, ename, sal
FROM emp
WHERE deptno = 30;
Notation Syntax Description
(Keywords U-Case)
VIEW CREATE [OR REPLACE] [FORCE | NOFORCE] VIEW view The subquery cannot contain an ORDER BY clause
[(alias[, alias])] OR REPLACE recreates the view if it already exists
AS subquery FORCE creates the view even if tables dont exist
[WITH CHECK OPTION [CONSTRAINT constraint] ] NOFORCE creates the view only if tables dont exist (default)
[WITH READ ONLY]; view view name (if nt named Oracle defines with SYS_Cn
alias specifies names for the expressions selected by the
views query (number aliases must match number of
expressions)
subquery complete subquery (can use aliases for columns in
SELECT list)
WITH CHECK OPTION specifies that only rows accessible to the
view can be inserted or updated
constraint name of CHECK option constraint
WITH READ ONLY ensures that no DML operations can be
performed

CREATE VIEW empvu10 Creating a simple view


AS SELECT empno AS EMPLOYEE_NUMBER, ename AS name, DESC view Describes view structure
sal AS SALARY
FROM emp
WHERE deptno = 30;

SELECT * Retrieving data from a view (ORDER BY alias not original column
FROM empvu10 name)
ORDER BY NAME;

DROP VIEW empvu10; Deletes view

A complex VIEW CREATE VIEW dept_sum_vu Complex view containing group functions
(name, minsal, maxsal, avgsal)
AS SELECT d.dname, MIN(e.sal), MAX(e.sal),
AVG (e.sal)
FROM emp e, dept d
WHERE e.deptno = d.deptno
Notation Syntax Description
(Keywords U-Case)
VIEW CREATE [OR REPLACE] [FORCE | NOFORCE] VIEW view The subquery cannot contain an ORDER BY clause
[(alias[, alias])] OR REPLACE recreates the view if it already exists
AS subquery FORCE creates the view even if tables dont exist
[WITH CHECK OPTION [CONSTRAINT constraint] ] NOFORCE creates the view only if tables dont exist (default)
[WITH READ ONLY]; view view name (if nt named Oracle defines with SYS_Cn
alias specifies names for the expressions selected by the
views query (number aliases must match number of
expressions)
subquery complete subquery (can use aliases for columns in
SELECT list)
WITH CHECK OPTION specifies that only rows accessible to the
view can be inserted or updated
constraint name of CHECK option constraint
WITH READ ONLY ensures that no DML operations can be
performed

CREATE VIEW empvu10 Creating a simple view


AS SELECT empno AS EMPLOYEE_NUMBER, ename AS name, DESC view Describes view structure
sal AS SALARY
FROM emp
WHERE deptno = 30;

SELECT * Retrieving data from a view (ORDER BY alias not original column
FROM empvu10 name)
ORDER BY NAME;

DROP VIEW empvu10; Deletes view

GROUP BY d.dname;

CHECK OPTION CREATE OR REPLACE VIEW empvu20 ensures that DML operations remain within the domain of
AS SELECT * the view
FROM emp Stops deptno being changed and so taking the line out of
WHERE deptno = 20 the view (allows other fields to be updated)
Notation Syntax Description
(Keywords U-Case)
VIEW CREATE [OR REPLACE] [FORCE | NOFORCE] VIEW view The subquery cannot contain an ORDER BY clause
[(alias[, alias])] OR REPLACE recreates the view if it already exists
AS subquery FORCE creates the view even if tables dont exist
[WITH CHECK OPTION [CONSTRAINT constraint] ] NOFORCE creates the view only if tables dont exist (default)
[WITH READ ONLY]; view view name (if nt named Oracle defines with SYS_Cn
alias specifies names for the expressions selected by the
views query (number aliases must match number of
expressions)
subquery complete subquery (can use aliases for columns in
SELECT list)
WITH CHECK OPTION specifies that only rows accessible to the
view can be inserted or updated
constraint name of CHECK option constraint
WITH READ ONLY ensures that no DML operations can be
performed

CREATE VIEW empvu10 Creating a simple view


AS SELECT empno AS EMPLOYEE_NUMBER, ename AS name, DESC view Describes view structure
sal AS SALARY
FROM emp
WHERE deptno = 30;

SELECT * Retrieving data from a view (ORDER BY alias not original column
FROM empvu10 name)
ORDER BY NAME;

DROP VIEW empvu10; Deletes view

WITH CHECK OPTION CONSTRAINT empvu20_ck;

READ ONLY CREATE OR REPLACE VIEW empvu20 READ ONLY stops any DML changes
AS SELECT *
FROM emp
WHERE deptno = 20
Notation Syntax Description
(Keywords U-Case)
VIEW CREATE [OR REPLACE] [FORCE | NOFORCE] VIEW view The subquery cannot contain an ORDER BY clause
[(alias[, alias])] OR REPLACE recreates the view if it already exists
AS subquery FORCE creates the view even if tables dont exist
[WITH CHECK OPTION [CONSTRAINT constraint] ] NOFORCE creates the view only if tables dont exist (default)
[WITH READ ONLY]; view view name (if nt named Oracle defines with SYS_Cn
alias specifies names for the expressions selected by the
views query (number aliases must match number of
expressions)
subquery complete subquery (can use aliases for columns in
SELECT list)
WITH CHECK OPTION specifies that only rows accessible to the
view can be inserted or updated
constraint name of CHECK option constraint
WITH READ ONLY ensures that no DML operations can be
performed

CREATE VIEW empvu10 Creating a simple view


AS SELECT empno AS EMPLOYEE_NUMBER, ename AS name, DESC view Describes view structure
sal AS SALARY
FROM emp
WHERE deptno = 30;

SELECT * Retrieving data from a view (ORDER BY alias not original column
FROM empvu10 name)
ORDER BY NAME;

DROP VIEW empvu10; Deletes view

WITH READ ONLY;


Notation Syntax Description
(Keywords U-Case)
Inline views SELECT a.ename, a.ename, a.sal, a.deptno, b.maxsal Subquery with the alias b
FROM emp a, (SELECT deptno, max(sal) maxsal
FROM emp
GROUP BY deptno) b
WHERE a.deptno = b.deptno
AND a.sal < b.maxsal;

Top-N SELECT [column_list], ROWNUM Asks for the n largest or smallest values
FROM (SELECT [column_list] FROM table WHERE clause must contain < or <= operators
ORDER BY Top-N_column)
WHERE ROWNUM <= N

SELECT ROWNUM AS rank, ename, sal Ranks employees by sal and shows top 6
FROM (SELECT ename, sal FROM emp
ORDER BY sal DESC)
WHERE ROWNUM <= 6;

SELECT ROWNUM AS rank, ename, sal+NVL(comm, 0) Ranks employees by sal + comm and shows top 6
FROM (SELECT ename, sal, comm FROM emp
ORDER BY sal+NVL(comm, 0) DESC)
WHERE ROWNUM <= 6;
Notation Syntax Description
(Keywords U-Case)
SEQUENCE CREATE SEQUENCE sequence Creating a sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];

CREATE SEQUENCE dept_deptno


INCREMENT BY 1
START WITH 91
MAXVALUE 100
NOCYCLE Do not cycle if the sequence is to be used as a primary key
NOCACHE; unless you have a reliable mechanism that purges old rows
faster than the sequence cylcles

SELECT sequence_name, min_value, max_value, Confirming a sequence. Last number displays the next
increment_by, last_number available number (if cache size 0)
FROM user_sequences;
Notation Syntax Description
(Keywords U-Case)
NEXTVAL INSERT INTO dept(deptno, dname, loc) NEXT VALUE returns the next available sequence number
VALUES (dept_deptno.NEXTVAL, (A unique value even for different users)
'MARKETING', 'SAN DIEGO');

CURRVAL SELECT dept_deptno.CURRVAL CURRVAL obtains the current sequence value


FROM dual;
NEXT VALUE & CURRVAL can be used in:
the SELECT list of a SELECT statement that is
not part of a subquery
Modifying a sequence ALTER SEQUENCE dept_deptno the SELECT list of a subquery in an INSERT
INCREMENT BY 1 statement
MAXVALUE 999999 the VALUES clause of an INSERT statement
NOCACHE the SET clause of an UPDATE statement
NOCYCLE;
NEXT VALUE & CURRVAL cannot be used in:
Deleting a sequence DROP SEQUENCE dept_deptno; a SELECT list of a view
a SELECT statement with the DISTINCT
keyword
a SELECT statement with the GROUP BY,
HAVING, or ORDER BY clauses
a subquery in a SELECT, DELETE, or
UPDATE statement
a DEFAULT expression in a CREATE TABLE
or ALTER TABLE statement
Notation Syntax Description
(Keywords U-Case)
INDEX CREATE INDEX index When to create an index:
ON table (column[, column]); a column is used frequently in a WHERE clause
a column contains a wide range of values
CREATE INDEX emp_ename_idx a column contains a large number of null values
ON emp(ename); two or more columns are frequently used in a WHERE
clause or a join
the table is large and most queries are expected to
Confirming Indexes SELECT ic.index_name, ic.column_name, retrieve less than 2-4% of the rows
ic.column_position col_pos, ix.uniqueness
FROM user_indexes ix, user_ind_columns ic More is not always better - the more indexes the more
WHERE ic.index_name = ix.index_name effort the Oracle Server must take to update them. When to
AND ic.table_name = 'EMP'; create an index:
the table is small
the columns are not often used as a condition in the
Remove an index DROP INDEX index;
query
most queries are expected to retrieve more than 2-4%
DROP INDEX emp_ename_idx;
of the rows
the table is updated frequently

Function-Based Indexes CREATE INDEX index ON table (function/column); Facilitates queries like:
SELECT * FROM emp
CREATE INDEX uppercase_idx WHERE UPPER(ename) = 'KING' ;
ON emp (UPPER(ename)); To force Oracle to use the index be sure the value of a
function is not NULL, e.g.
SELECT * FROM emp
WHERE UPPER(ename) IS NOT NULL
ORDER BY UPPER(ename);
Notation Syntax Description
(Keywords U-Case)
SYNONYM CREATE [PUBLIC] SYNONYM synonym Used to: Refer to a table owned by another user
FOR object; Shorten lengthy object names

CREATE SYNONYM d_sum


FOR dept_sum_vu;

DROP SYNONYM d_sum;

USER CREATE USER user Note: does not work 'insufficient privileges' (scott's
IDENTIFIED BY password; privileges) - user and privilege notes copied and left as it is
very basic coverage and should therefore be covered more
CREATE USER pete fully in later modules
IDENTIFIED BY abcde;

GRANT Privileges GRANT privilege [,privilege] E.g. privileges:


TO user [, user]; CREATE SESSION connect to the database
CREATE TABLE create tables in user's schema
GRANT create session, create table, create sequence, CREATE SEQUENCE create sequence in user's schema
create view, create procedure CREATE VIEW create view in user's schema
TO pete; CREATE PROCEDURE create a stored procedure,
function, or package in user's
schema
(see note under user)
ROLE CREATE ROLE role; Role can then be allocated privileges. Makes allocating
privileges to a lot of users simpler and standardised
CREATE ROLE manager;
(see note under user)
Changing passwords ALTER USER scott scott privileges allow this operation
IDENTIFIED BY lion;
Notation Syntax Description
(Keywords U-Case)
Object Privileges GRANT object_priv [(columns)] See list of object privileges in glossary
ON object ALL specifies all object privileges
TO {user | role | PUBLIC } PUBLIC grants object privileges to all users
[WITH GRANT OPTION]; WITH GRANT OPTION allows grantee to grant the
privileges to others
GRANT select
ON emp
TO sue, rich;

Confirming Privileges SELECT * Data Dictionary


FROM data_dictionary ROLE_SYSTEM_PRIVS
[WHERE USER = 'name']; ROLE_TAB_PRIVS
USER_SYSTEM_PRIVS
SELECT * USER_ROLE_PRIVS
FROM USER_SYS_PRIVS USER_TAB_PRIVS_MADE
WHERE USER = scott; USER_TAB_PRIVS_RECD
USER_COL_PRIVS_MADE
USER_COL_PRIVS_RECD

REVOKE privilege REVOKE { privilege [,privilege] | ALL}


ON object
FROM {user[, user] | role | PUBLIC} CSACADE CONSTRAINTS necessary where
[CASCADE CONSTRAINTS]; REFERENCES privilege has been used

REVOKE select, insert If a WITH GRANT OPTION is revoked the revoke


ON dept cascades to all users who have been granted by that user
FROM scott; including any new WITH GRANT OPTION's
PL/SQL: (Notation these notes: [ ] optional, { } must contain something)

Notation Syntax Description


(Keywords U-Case)
PL/SQL block types Every unit of PL/SQL comprises one or more blocks.
Anonymous: [DECLARE] Anonymous: Unnamed blocks declared at the point in an
application where they are to be executed. Can be
BEGIN embedded within a pre-compiler program and within
--statements SQL*Plus or Server manager. Triggers in Oracle
Developer components consist of such blocks.
[EXEPTION]

END;
Procedure: PROCEDURE name Subprograms: Named PL/SQL blocks (procedures or
(subprogram) IS functions) that can take parameters and can be invoked.
Generally procedures perform an action and functions
BEGIN return a value.
--statements Can store at server or application level. Can be called from
[EXEPTION] other procedures, functions, and triggers within the same
END; application.
Function: FUNCTION name
(subprogram) RETURN datatype
IS

BEGIN
--statements
RETURN value;
[EXEPTION]
END;
Notation Syntax Description
(Keywords U-Case)
Variables DECLARE DECLARE Naming convention v_variable and c_constant
identifier [CONSTANT] datatype [NOT NULL] Two variables can have the same name, provided they
[:= | DEFAULT expr]; are in different blocks
Identifier should not be the same as the name of
DECLARE columns used in the same block
v_hiredate DATE; Initialise using the assignment operator (:=) or the
v_deptno NUMBER (2) NOT NULL := 10; DEFAULT reserved word
v_location VARCHAR2 (13) := 'Atlanta'; Must initialise variables designated as NOT NULL and
c_comm CONSTANT NUMBER := 1400; CONSTANT
Declare only one identifier per line
%TYPE DECLARE
v_ename emp.ename%TYPE; Variables are initialised every time a block or subprogram
is entered - default to null unless initialised
Assigning Values identifier := expr;

v_hiredate := '31-DEC-98'
v_hiredate DEFAULT '31-DEC-98'
Note: No TO_DATE function required in 8i

SELECT sal * 0.10


INTO v_bonus
FROM emp
WHERE empno = 7369;

BOOLEAN v_sal1 := 50000


(Initialising with an v_sal2 := 60000
expression)
v_comm_sal := (v_sal1 < v_sal2); This case sets the variable to TRUE
Notation Syntax Description
(Keywords U-Case)
Declaring a bind VARIABLE identifier TYPE Can be referenced by SQL and SQL*Plus.
variable (in SQL*Plus) SQL*Plus can display its value.

Display value PRINT identifier

Referencing Non- VARIABLE g_monthly_sal NUMBER


PL/SQL Variables ACCEPT p_annual_sal PROMPT 'Please enter the
annual salary: '

DECLARE
v_sal NUMBER(9,2) := &p_annual_sal;
BEGIN
:g_monthly_sal := v_sal/12; Note: Must prefix non-PL/SQL variables with a colon
END;
/

PRINT g_monthly_sal

DBMS_OUTPUT.PUT_ SET SERVEROUTPUT ON An Oracle-supplied packaged procedure as an alternative to


LINE ACCEPT p_annual_sal PROMPT 'Please enter the display data from a PL/SQL block.
annual salary: ' Must be enabled in SQL*Plus with:
DECLARE SET SERVEROUTPUT ON
v_sal NUMBER(9,2) := &p_annual_sal;
BEGIN
v_sal := v_sal/12;
DBMS_OUTPUT.PUT_LINE
('The monthly salary is ' || TO_CHAR (v_sal));
END;
/
Notation Syntax Description
(Keywords U-Case)
Datatype conversion TO_CHAR (value, fmt)
TO_CHAR DECLARE TO_DATE (value, fmt)
v_date VARCHAR2 (15) TO_NUMBER (value, fmt)
BEGIN
SELECT TO_CHAR (hiredate, 'MON, DD, YYYY') PL/SQL will automatically try to convert data but it does
INTO v_date not always work and can slow processing down - it is good
FROM emp practise to explicitly perform datatype conversions.
WHERE empno = 7839;

TO_DATE v_date := TO_DATE ('January 13, 1998',


'Month DD, YYYY);

Nested Blocks and A block can look up into the enclosing block
Variable Scope x BINARY_INTEGER; A block cannot look down to enclosed blocks
BEGIN
i.e. the nested block, shown left, can reference the external
DECLARE variable x, but y can only be referenced by the nested block
y NUMBER; scope of x (see also Introduction to Oracle: SQL & PL/SQL 17-20)
BEGIN scope
of y
END;

END;
Notation Syntax Description
(Keywords U-Case)
PL/SQL Operator Operator Operation

**, NOT Exponentiation, logical negation


+, - Identity, negation
*, / Multiplication, division
+, -, || Addition, subtraction, concatenation
=, !=, <, >, <=, >=, IS NULL, LIKE, BETWEEN, IN Comparison
AND Conjunction
OR Inclusion

examples v_count := v_count + 1; Increment the counter for a loop

v_equal := (v_n1 = v_n2); Set the value of a Boolean flag

v_valid := (v_empno IS NOT NULL); Validate an employee number if it contains a value


Notation Syntax Description
(Keywords U-Case)
SELECT in PL/SQL SELECT select_list select_list at least one column and can include SQL
INTO {variable_name[, variable_name] expressions, row functions, or group
| record_name} functons
FROM table varriable_name the scalar variable to hold the retrieved
WHERE condition; values
record_name PL/SQL RECORD to hold the retrieved
values

e.g. The INTO clause is mandatory to specify variables to


hold the selected values (PL/SQL or host variables). One
DECLARE variable per value - order corresponding to selection order.
v_deptno NUMBER(2); Select statements within PL/SQL fall into the ANSI
v_loc VARCHAR2(15); classification of Embedded SQL - queries must only
BEGIN return one row, more than one row returns an error.
SELECT deptno, loc (exceptions NO_DATA_FOUND and
INTO v_deptno, v_loc TOO_MANY_ROWS)
FROM dept
WHERE dname = 'SALES'; To retrieve data in PL/SQL:
END; terminate each SQL statement with ;
/ use INTO
WHERE optional
columns in SELECT = variables in INTO
datatypes of columns must = identifiers (variables)
group functions e.g. SUM, must be in SQL statement
(because they apply to groups of rows but return a
single row)
Notation Syntax Description
(Keywords U-Case)
INSERT in PL/SQL BEGIN Use SQL Functions, Such As USER And SYSDATE
INSERT INTO emp(empno, ename, job, deptno) Generate primary key values using database sequences
VALUES (empno_sequence.NEXTVAL, Derive values in the PL/SQL block
'HARDING', 'CLERK', 10); Add column default values
END;

UPDATE in PL/SQL DECLARE If no rows are modified no error occurs.


v_sal_increase emp.sal%TYPE := 2000 PL/SQL variable assignments always use :=
BEGIN SQL variable assignments always use =
UPDATE emp
SET sal = sal + v_sal_increase
WHERE job = 'ANALYST';
END;

DELETE in PL/SQL DECLARE


v_deptno emp.deptno%TYPE := 10;
BEGIN
DELETE FROM emp
WHERE deptno = v_deptno;
END;

Naming Conventions Use a naming convention to avoid ambiguity in the e.g. deptno and v_deptno - meaningful variable name with
for identifiers WHERE clause a meaningful prefix
Database columns and identifiers should have distinct
names
Syntax errors can arise because PL/SQL checks the
database first for a column in the table
Notation Syntax Description
(Keywords U-Case)
COMMIT COMMIT [WORK]; Commits work and ends transaction

Note: WORK is for compliance to ANSI standards

SAVEPOINT SAVEPOINT savepoint_name; Inserts a point to where work can be rolled back to

ROLLBACK ROLLBACK [WORK]; Rolls back work to the beginning of the transaction

ROLLBACK [WORK] TO [SAVEPOINT] Rolls back work to the savepoint named


savepoint_name;

SQL%ROWCOUNT VARIABLE rows_deleted VARCHAR2(30) SQL%ROWCOUNT being used to check how many rows
DECLARE have been deleted.
v_name VARCHAR2(30) := 'MELLOR'; Procedure returned successful even though nothing deleted
BEGIN (no manager named MELLOR)
DELETE FROM MANAGERS
WHERE name = v_name; See also SQL Cursor Attributes - Glossary
:rows_deleted := (SQL%ROWCOUNT ||' rows
deleted.');
END;
/
PRINT rows_deleted

This PL/SQL block returns:

PL/SQL procedure successfully completed.


SQL> PRINT rows_deleted [RETURN]
ROWS_DELETED
--------------------------------
0 rows deleted.
Notation Syntax Description
(Keywords U-Case)
IF statements condition - a boolean variable or expression (TRUE,
IF condition THEN FALSE, or NULL)
statements; THEN - associates the preceding boolean expression with
[ELSIF condition THEN the sequence that follows.
statements;] statements - one or more PL/SQL or SQL statements
[ELSE ELSIF - introduces further boolean expression which is
statements;] used if the first is FALSE or NULL .
END IF; ELSE - statements following are executed if control
reaches it, i.e. previous boolean expressions were FALSE
or NULL

IF - THEN - END IF IF v_name = 'MILLER' THEN For Boolean conditions see Glossary " Building Logical
V_name := 'SALESMAN'; Conditions"
v_deptno := 35;
v_new_comm := sal * 0.20;
END IF;

IF - THEN - ELSE - IF v_shipdate - v_orderdate < 5 THEN


END IF v_ship_flag := 'Acceptable';
ELSE
v_ship_flag := 'Unacceptable';
END IF;

IF - THEN - ELSIF IF v_deptno = 10 THEN


v_comm := 7500;
ELSIF v_deptno = 20 THEN
v_comm := 7500;
ELSE
v_comm := 2000;
END IF;
Notation Syntax Description
(Keywords U-Case)
LOOP LOOP -- delimiter Where the condition is a Boolean variable or expression
Statement1; -- statements (TRUE, FALSE, or NULL)

EXIT [WHEN condition]; -- EXIT statement EXIT can be used within an IF statement or as a standalone
END LOOP; -- delimiter statement. A basic loop can contain multiple EXIT
statements.
DECLARE
v_ordid item.ordid%TYPE := 601;
v_counter NUMBER (2) := 1; If v_counter not set it is NULL and so v_counter + 1 would
BEGIN never get to 10 and so never satisfy the EXIT condition.
LOOP (i.e. null + 1 = null)
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 FOR counter in [REVERSE] Counter does not need to be declared (implicitly declared
lower_bound..upper_bound LOOP as an integer) and can be named anything you like, e.g.
statement1; FOR i in [REVERSE]

END LOOP; REVERSE causes the counter to decrement from the
upper_bound to the lower_bound (lower_bound still
DECLARE referenced first)
v_ordid item.ordid%TYPE := 601;
BEGIN
FOR i IN 1..10 LOOP
lower_bound specifies the lower bound for the range of
INSERT INTO item(ordid, itemid) counter values. upper_bound specifies the upper bound
VALUES(v_ordid, i); for the range of counter values. Can be literals, variables,
END LOOP; or expressions.
END;
Notation Syntax Description
(Keywords U-Case)
WHILE - LOOP WHILE condition LOOP Condition (Boolean variable or expression) is evaluated at
statement1; the beginning of each iteration. If the condition yields null
statement2; the loop is bypassed and control passes to next statement.

END LOOP;

ACCEPT p_new_order PROMPT


'Enter the order number: '
ACCEPT p_items PROMPT
'Enter the number of items in this order: '
DECLARE
v-count NUMBER(2) := 1;
BEGIN
WHILE v_count <= &p_items LOOP
INSERT INTO item(ordid, itemid)
VALUES (&p_new_order, v_count);
v_count := v_count +1;
END LOOP;
COMMIT;
END;
/
Notation Syntax Description
(Keywords U-Case)
Nested Loops and
Labels BEGIN
<<Outer_loop>>
LOOP
v_counter := v_counter + 1;
EXIT WHEN v_counter >10;
<<Inner_loop>>
LOOP

EXIT Outer_loop WHEN total_done = 'YES';
-- Leave both loops
EXIT WHEN inner_done = 'YES';
-- Leave inner loop only

END LOOP Inner_loop; Inner_loop and Outer_loop andded after END LOOP
END LOOP Outer_loop; statements for clarity.
END;
Notation Syntax Description
(Keywords U-Case)
Creating a PL/SQL TYPE type_name IS RECORD type_name the name of the RECORD type (this
Record (field_declaration [, field_declaration]); identifier is used to declare records)
identifier type_name; field_name the name of a field within the record
field_type the datatype of the field (any PL/SQL
Where field_declaration is: datatype except REFCURSOR. Can use
field_name {field_type | variable%TYPE %TYPE and %ROWTYPE attribitutes)
| table.column%TYPE | table&ROWTYPE} expr the field_type or an initial value
[[NOT NULL] {:= | DEFAULT} expr]
Note: NOT NULL fields must be initialised

TYPE emp_record_type IS RECORD
(ename VARCHAR2(10), Have to declare the datatype before declaring the identifier.
job VARCHAR2(9),
sal NUMBER(7, 2));
emp_record emp_record_type;
User defined records are instantiated when you enter the
block or subprogram and cease to exist when you exit.
Referencing a field emp_record.job Can assign values by SELECT or FETCH statements -
within a record selection must be in same order as record fields. Can also
assign one record to another.
Assigning values to emp_record.job := 'CLERK'; A user-defined record and a %ROWTYPE record never
record fields have the same datatype.
Notation Syntax Description
(Keywords U-Case)
%ROWTYPE DECLARE Gives the record fields names and datatypes = table row.
identifier reference.%ROWTYPE; identifier - name of record, reference - name of table, view,
cursor, or cursor variable
DECLARE Adv: number and datatypes of the underlying database may
emp_rec emp.%ROWTYPE; not be known, number and datatypes may change, useful
BEGIN when retrieving a row in a SELECT statement.
SELECT * INTO emp_rec
FROM emp Code left declares identifier and reference
WHERE empno = &employee_number; Selects a row from the emp table by user input and then
INSERT INTO retired_emps(empno, ename, job, identifies table and fields to insert the values into.
mgr, hiredate, leavedate, sal, comm,
deptno)
VALUES (emp_rec.empno, emp_rec.ename,
emp_rec.job, emp_rec.mgr,
emp_rec.hiredate, SYSDATE,
emp_rec.sal, emp_rec.comm,
emp_rec.deeptno);
COMMIT;
END;
Notation Syntax Description
(Keywords U-Case)
Creating PL/SQL TYPE type_name IS TABLE OF 1. Declare a TABLE datatype
Tables {column_type | variable%TYPE
| table.column%TYPE} [NOT NULL]
[INDEX BY BINARY_INTEGER];
identifier type_name; 2. Declare a variable of that datatype

DECLARE
TYPE date_table_type IS TABLE OF DATE
INDEX BY BINARY_INTEGER;
date_table date_table_type;

DECLARE
TYPE ename_table_type IS TABLE OF
emp.ename%TYPE BINARY_INTEGER range is -21474836472147483647
INDEX BY BINARY_INTEGER; so the primary key value can be negative and indexing need
TYPE hiredate_table_type IS TABLE OF not start with 1.
emp.ename%TYPE
INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
hiredate_table hiredate_table_type;
BEGIN
ename_table(1) := 'CAMERON'; (1) references row 1
hiredate_table(8) := SYSDATE + 7; (8) references row 8
IF ename_table.EXISTS(1) THEN EXISTS see Glossary - PL/SQL Table Methods
INSERT INTO

END;
Notation Syntax Description
(Keywords U-Case)
PL/SQL Table of DECLARE
Records TYPE dept_table_type IS TABLE OF
dept%ROWTYPE
INDEX BY BINARY_INTEGER;
dept_table dept_table_type;

table(index).field Each element of dept_table is a record and fields within the


records can be accessed
dept_table(15).loc := 'Atlanta'

(Where loc represents a field in DEPT_TABLE. Using a


%ROWTYPE attribute holds the same information but as a
RECORD individual fields can be referenced)
Declaring Explicit CURSOR cursor_name IS cursor_name is a PL/SQL identifier, select_statement is a
Cursors select_statement; SELECT statement without an INTO clause.
Can include ORDER BY in query if required.
Opening Explicit OPEN cursor_name; Open the previously declared query to execute to query and
Cursors identify the active set. Positions the pointer just before the
first row of the active set. If the query returns no rows, no
exception is raised.
Fetching Data from a FETCH cursor_name [variable1, variable1, ] same number of variables as columns in the FETCH
Cursor | record_name]; match variable and column positions (or define a record
for the cursor and reference in the FETCH INTO
Examples 21-11 test if the cursor contains rows
The FETCH statement advances the pointer to the next
row in active set and reads the data of the current row
Notation Syntax Description
(Keywords U-Case)
Glossary

Null A null value is a value that is unavailable, unassigned, unknown, or inapplicable. A null is not the same as zero or a blank
space. Arithmetic expressions containing a null value evaluate to null. (1 + null = null, 1*null = null)
Columns of any data type can contain null unless the column was defined as a Primary Key or as NOT NULL.
!Unexpected End Command language for communication with the Oracle Server from any tool or application.
of FormulaSQL (see Introduction to Oracle: SQL and PL/SQL Volume 1 p 1-24 & 1-25)
SQL*Plus Oracle tool which accepts and submits SQL statements to the Oracle server. SQL*Plus keywords can be abbreviated
(see Introduction to Oracle: SQL and PL/SQL Volume 1 p 1-24 to 1-26)
You can enter only one SQL*Plus command per SQL prompt. Plus commands are not stored in the buffer. To continue a
SQL*Plus command on the next line, end the current line with a hyphen (-)

Datatypes NUMBER(p,s), VARCHAR2(s), DATE, CHAR(s), LONG, CLOB, RAW and LONG RAW, BLOB, BFILE

NUMBER(p,s) Number value having a maximum number of digits p, the number of digits to the right of the decimal point s.

VARCHAR2(s) Variable-length character value maximum size s (max possible 4000)

DATE Date and time value between January 1, 4712 BC and December 31, 9999 AD
Default format DD-MM-YY. (stored as a number)
CHAR(s) Fixed-length character value of size s (max possible 2000)

LONG Variable-length character data up to 2 gigabytes


CLOB Single-byte character data up to 4 gigabytes, e.g. book
RAW(s) and Raw binary data (max size 2000 and 2 gigabytes)
LONG RAW(s)
BLOB Binary data up to 4 gigabytes, e.g. photo
BFILE Binary data stored in an external file up to 4 gigabytes, e.g. film
SQL Functions perform calculations on data
modify individual data items
manipulate output for groups and rows
format dates and numbers for display
convert column data types
Functions may accept arguments and always return a value
Single-row SQL Operate on single rows only and return one result per row - character, number, date, conversion, general
functions (Can be nested)
Multiple-row Manipulate groups of rows and give one result per group
SQL functions
Character Case conversion functions LOWER
functions UPPER
INITCAP

Character manipulation functions CONCAT


SUBSTR
LENGTH
INSTR
LPAD (RPAD)
TRIM (LTRIM, RTRIM)

Number ROUND
functions TRUNC
MOD

DUAL DUAL is a dummy table that can be accessed by all users. It contains one column (Dummy) and one value (X). The DUAL
table is useful when you want to return a value once only - for instance, the value of a constant, pseudocolumn, or expression
that is not derived from a table with user data. The DUAL table is generally used for SELECT clause syntax completeness,
because both SELECT and FROM clauses are mandatory, and several calculations do not need to select from actual tables.
(see examples ROUND, TRUNC, and MOD)
Conversion Implicit datatype conversion From VARCHAR2 Or CHAR to NUMBER
Functions (automatically done by Oracle) From VARCHAR2 Or CHAR to DATE
From NUMBER to VARCHAR2
From DATE to VARCHAR2

Explicit datatype conversion TO_CHAR


TO_NUMBER
TO_DATE
Joins Two main types: Equijoin Where two columns the same in different tables (e.g. Primary/Foreign Keys)
Non-equijoin Where columns joined not the same (linked with a condition, e.g. BETWEEN)

Additional joins: Outer join


Self join
Set operators
Group functions AVG
COUNT
MAX
MIN
STDDEV
SUM
VARIANCE
GROUP BY
HAVING
CHR SQL function that converts an ASCII code to its corresponding character

Subqueries A SELECT statement embedded in a clause (WHERE, HAVING, or FROM)of another SELECT statement.
Also called nested SELECT, sub-SELECT, or inner SELECT.
Three types: Single-row - returns one line
Multiple-row - returns more than line
Multiple-column - returnsmore than one column [and line] - pairwise
- nonpairwise
Database Object Description Naming Conventions - all database objects
Objects
Table Basic unit of storage; composed of rows and Rules:
columns 1. Must begin with a letter
View Logically represents subsets of data from one 2. 1-30 characters long
or more tables. Contains no data of its own 3. Must contain only A-Z, a-z, 0-9, _, $, and #
Sequence Generates primary key values 4. Must not duplicate the name of another object
owned by the same user
Index Improves the performance of some queries 5. Must not be an Oracle Server reserved word

Synonym Gives alternative names to objects Guidelines:


1. Use descriptive names
2. Name the same entity consistently in different
tables

Note: Other database objects exist but not Note: Names are case insensitive
covered this course
PL/SQL an extension to SQL with design features of programming languages (offers data encapsulation, exception handling,
information hiding, and object orientation
SQL data manipulation and query statements are included within procedural units of code
Benefits of PL/SQL:
Integration - plays a central role to the Oracle Server (through stored procedures and functions, database
triggers, and packages) and Oracle development tools (through Oracle Developer component triggers).
Many Oracle tools have their own independent PL/SQL engines
Improved performance - can group SQL statements to save network traffic, can add processing power
tools.
Substitution & to prompt for and temporarily store values
variables && to prompt for and store values which can be reused until undefined (UNDEFINE)
DEFINE creates and assigns a value to a variable
ACCEPT reads a line of user input and stores it in a variable
SQL*Plus Report formatting commands: COLUMN, TTITLE, BTITLE, BREAK
Format
Commands
SQL*Plus ARRAYSIZE, COLSEP, FEEDBACK, HEADING, LINESIZE, LONG, PAGESIZE, PAUSE, TERMOUT, ECHO, VERIFY
Customization
Commands (full list in Oracle8I On-Line Generic Documentation CD)
Database A database transaction consists of a collection of DML statements that form a logical unit of work, one DDL, or one DCL
Transaction statement.
A database transaction: begins when the first executable SQL statement is executed.
ends with one of the following events
- COMMIT or ROLLBACK (advantages: ensure data consistency; preview data
changes before making them permanent; and group logically related operations)
- DDL or DCL statement executes (automatic commit)
- User exits
Until a transaction ends the affected rows are locked so that other users cannot access changes that may not be permanent.
(see read consistency)

Statement-level If DML statement fails during execution, only that statement is rolled back (an implicit savepoint implemented by Oracle
Rollback Server) and all other changes are retained.

Read Read consistency (automatic implementation) ensures that each user sees data as it existed at the last commit (or DDL/DCL
Consistency operation). Users making changes are the only users who can see their own changes pending.
Locking exclusive - Prevents a resource from being shared
The first transaction to lock a resource exclusively is the only transaction that can alter the resource until the
exclusive lock is released
share lock - Allows the resource to be shared
Multiple users reading data can share the data, holding share locks to prevent concurrent access by a writer
(who needs an exclusive lock)
Several transactions can acquire share locks on the same resource.

Oracle Locks fully automatic (lowest applicable level of restriction applied). Implicit locking occurs for all SQL statements
except SELECT. Oracle allows user to lock manually.

Oracle Table Tables can be created at any time even when users are accessing the database
Structures Size does not need to be specified. (ultimately restricted by the space allocated to the database but space required should be
considered)
Table structure can be modified online
User Tables Collection of tables created and maintained by the user
Contain user information
Data Dictionary Collection of tables created and maintained by the Oracle
Contain database information and usually accessed through views to make it easier to understand:

Prefix View Description

USER_ Contain information about objects owned by the user


ALL_ Contain information about all the tables (object tables and relational tables) accessible to the user
DBA_ These views are restricted views. These views can be accessed only by people who have been assigned the
role of DBA
V$_ Contain information about dynamic performance views, database server performance, and locking.

Querying the data dictionary:

SELECT *
FROM user_tables;

SELECT DISTINCT object_type


FROM user_objects;

SELECT *
FROM user_catalog; (FROM CAT; uses synonym instead of user_catalog)
Constraints Constraints are used to: - enforce rules at the table level whenever a row is inserted, updated, or deleted from that table
- prevent the deletion of a table if there are dependencies from the other tables
- provide rules for Oracle tools such as Oracle developer

NOT NULL - specifies that this column may not contain a NULL value (Can only be set at column level not table
level)
UNIQUE - specifies a column or combination of columns whose values must be unique for all rows in a table
(can be null if not also specified NOT NULL)
PRIMARY KEY - uniquely identifies each row of the table
FOREIGN KEY - establishes and enforces a foreign key relationship between the column and a column of the
referenced table
CHECK - specifies a condition that must be true

A UNIQUE or PRIMARY KEY that is composed of more than one column is called a composite unique/primary key. All the
constraints can be defined at column and table level except NOT NULL.
Views Logically represents subsets of data from one or more tables. Contains no data of its own. Tables on which a view is based
are called base tables. Views are stored as a SELECT statement in the data dictionary.
Views are used to : restrict data access
make complex queries easy
allow data independence for ad hoc users and application programs
present different views of the same data for different groups

Feature Simple Views Complex Views

Number of tables One One or more


Contains functions No Yes
Contain groups of data No Yes
DML through view Yes Not always

When data is accessed through a view the Oracle server retrieves the view definition from the data dictionary, checks access
privileges for the view base table, then performs the query as an operation

Rules for performing DML operations on a view:


Cannot modify data if the view contains the following:
Group functions e.g. AVG, MIN
A GROUP BY clause
The DISTINCT keyword
The ROWNUM pseudocolumn
Columns defined by expressions e.g. sal*12
Cannot add data if:
The above conditions apply
There are NOT NULL columns in the base tables that are not selected by the view

CHECK OPTION ensures DML on the view stays within the domain of the view
Inline Views Inline Views are new to 8i. An inline view is a subquery with an alias that you can use within a SQL statement (similar to
using a subquery in the FROM clause
Inline Views are not schema objects

Sequences Automatically generates unique numbers


Is a sharable object (sequence numbers are stored and generated independently to the tables and so can be used for
multiple tables)
Is typically used to create a primary key value
Replaces application code
Speeds up the efficiency of accessing sequence values when cached in memory
Caching sequence values in memory allows faster access to those values
Gaps in sequence values can occur when: - a rollback occurs
- the system crashes
- a sequence is used in another table

Modifying a You must be the owner or have the ALTER privilege for the sequence
Sequence Only future sequence numbers are affected
The sequence numbers must be dropped and re-created to restart the sequence at a different number
Some validation is performed

INDEX Is a schema object


Is used by the Oracle Server to speed up the retrieval of rows by using a pointer
Can reduce disk I/O by using rapid path access method to locate the data quickly
Is independent of the table it indexes
Is used and maintained automatically by the Oracle Server
Created: - automatically when you define a PRIMARY or UNIQUE key
- manually to create non-unique indexes
User Access Used to: - Control database access
- Give access to specific objects in the database
- Confirm given and received privileges with the Oracle data dictionary
- Create synonyms for database objects

Privileges Database security: - System security


- Data security
System privileges - access to the database. More than 80 privileges are available. Typical high level DBA privileges:
CREATE USER
DROP USER
DROP ANY TABLE
BACK UP ANY TABLE
Object privileges - manipulate the content of database objects
Schema - collection of objects, such as tables, views, and sequences

Object Privilege Table View Sequence Procedure


Privileges ALTER
DELETE
EXECUTE
INDEX
INSERT
REFERENCES
SELECT
UPDATE
Oracle Makes use of shared library and consists of Oracle Forms, Reports, and Graphics. Has its own independent PL/SQL engine.
Developer
PL/SQL engine Filters out SQL statements and send them individually to the SQL statement executor in the Oracle Server and processes the
procedural statement itself. Processes data that is local rather than in the database to save work sent to the Oracle Server and
the number of memory cursors required.
PL/SQL Construct Description Availability
Program Anonymous Unnamed block that is embedded within an application All PL/SQL environments
Constructs block or is issued interactively

Stored Procedure or Named block stored in the Oracle Server that can be Oracle Server
function invoked repeatedly by name

Application procedure Named block stored in an Oracle Developer application Oracle Developer components - for
or function or shared library that can accept parameters and can be example, Forms
invoked repeatedly by name

Package Named module that groups related procedures, functions, Oracle Server and Developer
and identifiers components - for example, Forms

Database trigger A block that is associated with a table and is fired Oracle Server
automatically when triggered by DML statements

Application trigger A block that is associated with an application event and is Oracle Developer components - for
fired automatically example, Forms
PL/SQL Use: Temporary storage of data
Variables Manipulation of stored values
Reusability
Ease of maintenance - using %TYPE and %ROWTYPE variables are defined as per the database. When the
underlying database is changed the variables are automatically updated

Declare and initialise in the declaration section


Assign new values in the executable section
Pass values into blocks through parameters
View results through output variables

Types of variables: - Scalar


- Composite
- Reference
- LOB (large objects)
PL/SQL does not have input/output capability of its own and relies on the environment it is executing in for passing values in
and out of a block, e.g. SQL*Plus

Non - PL/SQL Bind and host language variables such as those declared in pre-compiler programs, screen fields in Forms applications, and
Variables SQL*Plus host variables
Scalar datatypes Hold a single value and have no internal components. Four categories: number, character, date, and Boolean.
VARCHAR2 ()
NUMBER()
DATE
CHAR[()]
LONG
LONG RAW
BOOLEAN
BINARY_INTEGER
PLS_INTEGER
BOOLEAN Stores TRUE, FALSE, or NULL

BINARY_INTE Base type for integers between -2,147,483,647 and 2,147,483,647


GER

PLS_INTEGER Base type for integers between -2,147,483,647 and 2,147,483,647


PLS_INTEGER values require less storage and are faster than NUMBER and BINARY_INTEGER values

%TYPE Used to declare a variable according to a database column definition or another previously declared variable (prefix with
table and column or the previously declared variable name

Composite Can be TABLE, RECORD, NESTED TABLE, and VARRAY


datatypes
(collections)
LOB CLOB, BLOB, BFILE, NCLOB (national language character large object - used to store large blocks of single-byte or fixed-
width multibyte NCHAR data in the database, in line or out of line.
PL/SQL Block Statements can continue over several lines
Syntax and Lexical units can be separated by: - Spaces
guidelines - Delimiters
- Identifiers
- Literals
- Comments
Reserved words should be written in uppercase to promote readability

PL/SQL Delimiters Symbol Meaning Symbol Meaning


+ Addition operator <> Relational operator
- Subtraction/negation operator != Relational operator
* Multiplication operator || Concatenation operator
/ Division operator - Single line comment indicator
= Relational operator /* Beginning comment indicator
@ Remote access indicator */ Ending comment indicator
; Statement terminator := Assignment operator

PL/SQL Identifiers
Can contain up to 30 characters
Cannot contain reserved words unless enclosed in double quotation marks
Must begin with an alphabetical character
Should not have the same name as a database table column name

PL/SQL Literals
Character and date literals must be enclosed in single quotation marks
Numbers can be simple values or scientific notation

PL/SQL block is terminated by a slash (/) on a line by itself


SQL Functions Available in procedural statements:
in PL/SQL - Single-row number
- Single-row character Same as in SQL
- Datatype conversion
- Date
Not available in procedural statements:
- DECODE
- Group functions, e.g. AVG, MIN (Must be used within SQL statements within PL/SQL blocks)

PL/SQL Built in function categories:


Functions Error reporting
Number
Character
Conversion
Date
Miscellaneous
Programming Category Case Convention Examples
Guidelines
SQL statements Uppercase SELECT, INSERT
PL/SQL keywords Uppercase DECLARE, BEGIN, IF
Datatypes Uppercase VARCHAR2, BOOLEAN
Identifiers and parameters Lowercase v_sal, emp_cursor, g_sal, p_empno
Database tables and columns Lowercase emp, orderdate, deptno

Identifier Naming Convention

Variable v_name v_sal


Constant c_name c_company_name
Cursor name_cursor emp_cursor
Exception e_name e_too_many
Table type name_table_type amount_table_type
Table name_table order_total_table
Record type name_record_type emp_record_type
Record name_record customer_record
SQL*Plus substitution variable (also p_ name p_sal
referred to as substitution parameter)
SQL*Plus global variable (also referred g_ name g_year_sal
to as host or bind variable)

Indent each level of code for clarity


Manipulating INSERT adds new rows of data
Data using UPDATE modifies existing rows in the table
PL/SQL DELETE removes unwanted rows
Building Logical Handle null values with the IS NULL operator. Any arithmetic expression containing a null value evaluates to NULL.
Conditions Concatenated expressions with null values treat null values as an empty string.

Logic Tables: AND TRUE FALSE NULL OR TRUE FALSE NULL NOT
TRUE TRUE FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSE
FALSE FALSE FALSE FALSE FALSE TRUE FALSE NULL FALSE TRUE
NULL NULL FALSE NULL NULL TRUE NULL NULL NULL NULL*
* The negation of NULL(NOT NULL) results in a null value because null values are indeterminate
Composite Also known as collections, composite datatypes are:
Datatypes RECORD - to treat related but dissimilar data as a logical unit
TABLE - to reference and manipulate collections as a whole object.
Nested TABLE - not covered
VARRAY - not covered
PL/SQL A record is a group of related data items stored in fields, each with its own name and datatype.
Records must contain one or more components of any scalar, RECORD, or PL/SQL TABLE datatype, called fields
similar in structure to records in a 3GL
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
can be manipulated as a unit
PL/SQL Tables Modelled on but not the same as database tables and are similar to an array.
Composed of two components (two columns that cannot be named):
Primary key of datatype - BINARY_INTEGER
Column of scalar or record datatype
Increase dynamically because they are unconstrained.
PL/SQL Table Method Description
Methods EXISTS(n) Returns TRUE if the nth element in a PL/SQL table exists.
COUNT Returns the number of elements that a PL/SQL table currently contains.
FIRST Returns the first and last (smallest and largest) index numbers in a PL/SQL table. Returns NULL if the
LAST PL/SQL table is empty.
PRIOR(n) Returns the index number that precedes index n in a PL/SQL table.
NEXT(n) Returns the index number that succeeds index n in a PL/SQL table.
EXTEND* Increases the size of a PL/SQL table
EXTEND appends one null element to a PL/SQL table.
EXTEND(n) appends n null elements to a PL/SQL table.
EXTEND(n, i) appends n copies of the ith element to a PL/SQL table.
TRIM* TRIM removes all elements from the end of a PL/SQL table.
TRIM(n) removes n elements from the end of a PL/SQL table.
DELETE* DELETE removes all elements from a PL/SQL TABLE.
DELETE(n) removes the nth element from a PL/SQL TABLE.
DELETE(m, n) removes all elements within the range mn from a PL/SQL TABLE.
SQL Cursor To execute a multi-row query, Oracle opens an unnamed work area that stores processing information. A cursor lets
you name the work area, access the information, and process the rows individually.
(CUR
rent A cursor is a private SQL work area
S et There are two types of cursors:
Of
Rows) Implicit - declared by PL/SQL implicitly for all DML and PL/SQL SELECT statements including queries that only
return one row (unless there is an associated explicit cursor).

Explicit - for queries that return more than one row. Explicit cursors are declared and named by the programmer and
manipulated through specific statements in the block's executable actions. Use explicit cursors to
individually process each row returned by a multiple-row SELECT statement (the active set)
Functions:
Can process beyond the first row returned by the query, row by row.
Keep track of which row is currently being processed
Allow the programmer to manually control them in the PL/SQL
The Oracle Server uses implicit cursors to parse and execute your SQL statements
Explicit cursors are explicitly declared by the programmer.

Whenever a SQL statement is issued Oracle Server opens an area of memory in which the command is Parsed and executed -
called a cursor. When the executable part of a block issues a SQL statement, PL/SQL creates an implicit cursor.

Controlling Explicit Cursors

DECLARE OPEN FETCH EMPTY CLOSE


SQL Cursor SQL%ROWCOUNT Number of rows affected by the most recent SQL statement (an integer value)
Attributes
SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement affects one or more
rows
SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement does not affect any
rows
SQL%ISOPEN Always evaluates to FALSE because PL/SQL closes implicit cursors immediately after they are
executed
SQL cursor attributes allow you to evaluate what happened when the implicit cursor was last used. Attributes used in
PL/SQL not SQL. Can be used in the exception section of a block to gather information about the execution of a data
manipulation statement - PL/SQL does not consider a DML statement that affects no rows to have failed, unlike the SELECT
statement which returns an exception.
DATE FORMAT TABLE
(As used with TO_CHAR function)
Valid Date Format Table
Element Description Example

SCC or CC Century, S prefixes BC date with - (minus) SELECT TO_CHAR(SYSDATE, 'CC')


FROM dual;
(returns century - 20)
YYYY or SYYY Year, S prefixes BC date with - (minus)
YYY, YY, or Y Last three, two, one digit of the year
Y,YYY Comma in year
IYYY, IYY, IY, I Four, three, two, one digit year based on the ISO standard
RR Similar to YY etc but selects Century according to the
specified two digit year (0-49 and 50-99)
SYEAR, YEAR Year spelled out, S prefixes BC date with - (minus)
BC or AD BC/AD indicator
Q Quarter of a year
MM Month, two-digit value
MONTH Name of month padded with blanks to length of nine
characters
MON Month - 3 letters
RM Roman numeral month
WW, W Week of year or month
DDD, DD, D Day of year, month, or week
DAY Name of day padded with blanks to length of nine characters
DY Day - 3 leters
J Julian day: the number of days since 31 Dec 4713 BC
Valid Time Format Table
AM or PM Meridian indicator
A.M. or P.M. Meridian indicator with periods
HH or HH12 or Hour of day or hour (1-12) or hour (0-23)
HH24
MI Minute (0-59)
SS Second (0-59)
SSSSS Seconds past midnight (0-86399)
Other Date Format Features
/., Punctuation is reproduced in the result
"of the" Quoted string is reproduced in the result
Suffixes
TH Ordinal number (e.g. DDTH for 4TH)
SP Spelled out number (e.g. DDSP for FOUR)
SPTH or THSP Spelled out ordinal number

TO_CHAR with numbers


TO_CHAR (number, 'fmt') See also TO_CHAR (With Numbers)
Example Result
9 Represents a number 999999 1234
0 Forces a zero to be displayed 099999 001234
$ Places a floating dollar symbol $999999 $1234
L Uses the floating local currency symbol L999999 1234
. Prints a decimal point 999999.99 1234.00
, Prints a thousand indicator 999,999 1,234
MI Minus signs to right (negative values) 999999MI 1234-
PR Parenthesise negative numbers 999999PR <1234>
EEEE Scientific notation (format must specify four Es) 99.999EEEE 1.234E+03
V Multiply by 10 n times (n = number of 9s after V) 9999V99 123400
B Display zero values as blank, not 0 B9999.99 1234.00

You might also like