Lec - 7 SQL Plus Quick Ref
Lec - 7 SQL Plus Quick Ref
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)
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 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
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)
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)
= SELECT ename, job, deptno Selection restricted to where job is eqaul to clerk (character
FROM emp strings are case sensitive)
WHERE 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)
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
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
CONCAT CONCAT(column1|expression1, column2|expression2) Concatenates the first character value to the second
character value; equivalent to concatenation operator (||)
SELECT ename, job Lists enames where first 5 characters of job are SALES
FROM emp
WHERE SUBSTR (job, 1, 5) = 'SALES';
SELECT ename, LENGTH(ename) AS "How long?" Lists ename and number of characters
FROM emp;
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
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';
SELECT TRUNC (45.923, 2), TRUNC (45.923, 0), Gives 45.92, 45, 40
TRUNC (45.923, -1)
FROM dual;
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 '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 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
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(+);
AVG AVG ([DISTINCT|ALL]n) Average value of n ignoring null values. ALL is default on
all group functions.
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
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);
& 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 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;
PROMPT text Displays the text before the user can enter the value
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
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)
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 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 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
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;
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
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
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';
SELECT * Retrieving data from a view (ORDER BY alias not original column
FROM empvu10 name)
ORDER BY NAME;
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
SELECT * Retrieving data from a view (ORDER BY alias not original column
FROM empvu10 name)
ORDER BY NAME;
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
SELECT * Retrieving data from a view (ORDER BY alias not original column
FROM empvu10 name)
ORDER BY NAME;
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
SELECT * Retrieving data from a view (ORDER BY alias not original column
FROM empvu10 name)
ORDER BY NAME;
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
SELECT * Retrieving data from a view (ORDER BY alias not original column
FROM empvu10 name)
ORDER BY NAME;
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}];
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');
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
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;
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
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
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
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
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
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
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;
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;
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.
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)
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
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
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:
SELECT *
FROM user_tables;
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
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
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
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
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
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
%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
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
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.