PL/SQL Revision - Introduction to Oracle: SQL and PL/SQL SELECT Data retrieval Retrieves data from the database INSERT UPDATE DELETE Data manipulation language (DML) Enters new rows, changes existing rows, and removes unwanted rows from tables in the database, respectively. Data definition language (DDL) Set up, changes, and removes data structures from tables. CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT Transaction control GRANT REVOKE Data control language (DCL) Manages the changes made by DML statements. Changes to the data can be grouped into logical transactions. A database transaction consists of a collection of DML statements that form a logical unit of work, one DDL, or one DCL statement. Gives or removes access rights to both the Oracle database and the structures within it. SQL / SQL*Plus: (Notation these notes: [ ] optional, { } must contain something) Notation (Keywords U-Case) SELECT FROM WHERE ORDER BY Syntax Description SELECT [DISTINCT] {*, column [alias],…} FROM table [WHERE condition (s)] [ORDER BY {column, expr, alias} [ASC|DESC]]; Select and identify which columns Identifies which table ( ; - runs the statement) Restrict selection Order ascending or descending ; runs the SQL statement / runs the SQL statement or PL/SQL block (also a mathematical operator) SELECT * FROM Dept; Select all (*) columns from table called dept SELECT deptno, loc FROM Dept; Select deptno and location columns (displayed in order of declaration) SELECT deptno AS department_number, loc AS location FROM Dept; Gives columns alias (AS) names (default of upper case no spaces allowed) SELECT deptno department_number, loc location FROM Dept; AS can be omitted "" SELECT deptno AS "Department Number", loc AS "Location" FROM Dept; Gives alias case format and spaces allowed + SELECT ename, sal, sal+300 FROM emp; SELECT ename, sal, sal-300 Add 300 to salary figure and display as sal+300 with other columns subtract 300 from salary figure and display as sal-300 * AS - Notation (Keywords U-Case) Syntax Description FROM emp; SELECT ename, sal, sal*12 AS "Annual Salary" FROM emp; SELECT ename, sal, sal/1.15 FROM emp; () SELECT ename, sal, 12*(sal+100) FROM emp; || SELECT ename||job AS "Employees" FROM emp; with other columns multiply salary figure by 12 and display as Annual Salary with the other columns ename and sal. divide salary figure by 1.15 and display as sal/1.15 with other columns Operator Precedence * / + - (then left to right) Adds 100 to salary and then multiplies by 12 displayed as 12*(sal+100) Parentheses override rules of Operator Precedence (* / + [then left to right]) Concatenates (joins together) ename and job in a column called Employees SELECT ename||' is a '||job AS "Employee Details" FROM emp; Displays ename is a job in a column called Employee Details SELECT deptno FROM emp; Displays all occurrences of deptno in emp table SELECT DISTINCT deptno FROM emp; Displays each deptno in emp table (eliminating duplicates) DESCRIBE tablename tablename = any existing table, view, or synonym accessible to the user. Can be abbreviated to DESC DESCRIBE emp Displays column name, whether can be null, and data type of table emp (Doesn’t require semi-colon) A[PPEND] text Adds text to the end of the current line * / DISTINCT DESC[RIBE] (SQL*Plus) A[PPEND] Notation (Keywords U-Case) (SQL*Plus Editing) C[HANGE] (SQL*Plus Editing) Syntax Description C[HANGE] / old / new Changes old text to new in the current line C[HANGE] / text / Deletes text from the current line CL[EAR] BUFF[ER] (SQL*Plus Editing) CL BUFF Deletes all lines from the SQL buffer (like a clipboard) CL[EAR] SCR[EEN] (SQL*Plus Editing) CL SCR Clears screen DEL (SQL*Plus Editing) DEL DEL n DEL m n Deletes current line Deletes line n Deletes line m to n I[NPUT] (SQL*Plus Editing) I[NPUT] I[NPUT] text Inserts an indefinite number of lines Inserts a line consisting of text. L[IST] (SQL*Plus Editing) L[IST] L[IST] DEL n L[IST] DEL m n Lists all lines in the SQL buffer Lists line n Lists line m to n R[UN] (SQL*Plus Editing) R Displays and runs the current SQL statement in the buffer Displays and runs a SQL statement from file R filename n (SQL*Plus Editing) Specifies the line to make the current line Notation (Keywords U-Case) n text (SQL*Plus Editing) 0 text (SQL*Plus Editing) SAV[E] (SQL*Plus File) GET (SQL*Plus File) STA[RT] (SQL*Plus File) @ (SQL*Plus File) ED[IT] (SQL*Plus File) SPO[OL] (SQL*Plus File) EXIT (SQL*Plus File) Syntax Description Replaces line n with text Inserts a line before line 1 SAV filename [.ext] SAV filename [.ext] REP[LACE] SAV filename [.ext] App[end] GET filename [.ext] Saves buffer contents to a file (default extension .sql) Overwrites an existing file with buffer contents Adds buffer contents on to the contents of an existing file Writes the contents of a file to buffer STA filename [.ext] Runs a file @ filename [.ext] Runs a file (as START) ED ED [filename] [.ext] Invokes editor and saves buffer to a file afiedt.buf Invokes the editor and gets a saved file SPO [filename] [.ext] SPO [filename] [.ext] OFF SPO [filename] [.ext] OUT Stores query results in a file. OFF closes the spool file. OUT closes the spool file and sends the file results to the system printer. Leaves SQL*Plus Notation (Keywords U-Case) WHERE Syntax Description SELECT [DISTINCT] {*, Column [Alias],…} FROM Table; WHERE Condition (S); WHERE restricts the query to rows that meet a condition composed of column names, expressions, constants, and a comparison operator (column name / comparison operator / column name, constant, or list of values) WHERE expr operator value = SELECT ename, job, deptno FROM emp WHERE job='CLERK'; Selection restricted to where job is eqaul to clerk (character strings are case sensitive) > >= < <= <> BETWEEN …AND… IN LIKE WHERE sal>1500 WHERE sal>=1500 WHERE sal<1500 WHERE sal<=1500 WHERE sal<>1500 WHERE sal BETWEEN 1000 AND 1500 WHERE ename IN ('FORD', 'ALLEN') WHERE ename LIKE 'S%' Greater than Greater than or equal to Less than Less than or equal to Not equal to Within a range Values in a specified list Where ename starts with S (% any sequence of zero or more characters) Employees started during 1981 Where ename has second letter A (_ is any one character, __ is any two etc) WHERE hiredate LIKE '%1981' WHERE ename LIKE '_A%' 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 (Keywords U-Case) OR Syntax Description WHERE sal>=1100 OR job='CLERK' Returns TRUE if one component condition is TRUE 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 FROM emp ORDER BY hiredate; ORDER BY comes last in the SELECT statement Default is ascending (ASC) (can use column alias to order by if applicable) DESC SELECT ename, job, deptno, hiredate FROM emp ORDER BY hiredate DESC; Order descending SELECT ename, deptno, sal FROM emp ORDER BY deptno, sal DESC; Orders by deptno ascending (default) and then salary descending Notation (Keywords U-Case) LOWER Syntax Description LOWER(column|expression) Converts alpha character values to lowercase SELECT 'The job title for ' || INITCAP(ename) || ' is ' ||LOWER(job) AS "EMPLOYEE DETAILS" FROM emp; Gives column EMPLOYEE DETAILS with string including ename with first letter uppercase and job in lower case UPPER UPPER(column|expression) Converts alpha character values to uppercase INITCAP SELECT empno, ename, deptno FROM emp WHERE ename = UPPER ('blake'); INITCAP(column|expression) Without UPPER the SELECT would fail - looking for a lowercase entry. Also useful for stopping entry of names in non-standard case. Converts alpha character values to uppercase for the first letter of each word, all other letters in lowercase INITCAP('SQL COURSE') (see also LOWER example) Result = Sql Course 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 employees FROM emp; Lists ename with comments XXXXXOnly used to connect two character values?XXX CONCAT Notation (Keywords U-Case) SUBSTR LENGTH INSTR Syntax Description 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 FROM emp; Lists first 4 characters of ename SELECT ename, job FROM emp WHERE SUBSTR (job, 1, 5) = 'SALES'; Lists enames where first 5 characters of job are SALES LENGTH(column|expression) Returns the number of characters in a value SELECT ename, LENGTH(ename) AS "How long?" FROM emp; Lists ename and number of characters INSTR(column|expression, m) Returns the numeric position of a named character SELECT ename, INSTR(ename, 'N') AS "Where's N?" FROM emp; Lists ename and position of N in enames (0 = no N) Notation (Keywords U-Case) LPAD TRIM Syntax Description LPAD(column|expression, n, 'string') Pads the character value right-justified to a total width of n character positions LPAD(sal, 10, '*') (see TRIM examples) Result = ******5000 RPAD = 5000****** TRIM(leading|trailing|both, trim_character FROM trim_source) Enables you to trim heading or trailing characters (or both) 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) Trims S from either side of ename where it occurs SELECT TRIM ('S' FROM ename) AS name FROM emp; SELECT RTRIM(LPAD(ename, 10, '*'),'S') AS name FROM emp; SELECT LPAD (TRIM('S' FROM ename), 10, '*') AS name FROM emp; Trims S from right side of ename where it occurs after LPAD. NOTE: This syntax for LTRIM & RTRIM not TRIM Trims before LPAD Notation (Keywords U-Case) ROUND TRUNC MOD Syntax Description 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), ROUND (45.923, -1) FROM dual; Gives 45.92, 46, 50 SELECT empno, hiredate, ROUND(hiredate, 'MONTH'), TRUNC(hiredate, 'MONTH') FROM emp WHERE hiredate LIKE '%82'; Selects by hiredate (82) and gives hiredate as is, rounded (up/down), and truncated (down) 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), TRUNC (45.923, -1) FROM dual; Gives 45.92, 45, 40 (see also ROUND example - dates) MOD (m, n) SELECT MOD (16, 5) FROM dual; Returns the remainder of m divided by n. Returns 1 (16/5 = 3 and 1 left over) Notation (Keywords U-Case) SYSDATE Syntax Description SELECT SYSDATE FROM dual; MONTHS_BETWEEN(date 1, date 2) Returns today's date as DD-MMM-YY SELECT ROUND(MONTHS_BETWEEN('20-MAY2005' , SYSDATE)) AS "Months till I'm 50" FROM dual; Rounds to the nearest month time till I'm 50 ADD_MONTHS(date, n) Add n calendar months to date SELECT 'In 6 months the date will be '|| ADD_MONTHS(sysdate, 6)||' wont it?' FROM dual; Returns the date in 6 months time within a sentence NEXT_DAY NEXT_DAY(date, 'char') Finds the date of the next specified day Returns the date of next Friday in a sentence LAST_DAY SELECT 'Next weekend starts on Friday the '||NEXT_DAY(SYSDATE, 'FRIDAY') FROM dual; LAST_DAY(date) SELECT LAST_DAY(SYSDATE) FROM dual; Gives the date of the last day of this month MONTHS_BETWEEN ADD_MONTHS Number of months between two dates Finds the date of the last day of the month within the date Notation (Keywords U-Case) TO_DATE TO_CHAR (With Dates) Syntax Description TO_DATE (char [, fmt]) Convert a character string to a date format SELECT ROUND(TO_DATE('20-MAY-2005') SYSDATE) AS "Days till I'm 50" FROM dual; A frightening number! TO_CHAR(date, 'fmt') Valid fmt's = YYYY (number), YEAR (text), 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 Returns today's day SELECT TO_CHAR(SYSDATE, 'day') FROM dual; SELECT TO_CHAR(SYSDATE + 45, 'month') FROM dual; Returns month in 45 days time SELECT ename, TO_CHAR(hiredate, 'fmDDspth "of" Month YYYY fmHH:MI:SS AM') AS hiredate FROM emp; (see Date Format Table) SELECT 'On the ' || TO_CHAR((TO_DATE('19-JAN-01')(7*6)), 'fmDDSPTH "day of" fmMONTH "in the year" YYYY') || ' I should check that Peter has booked my SQL exam.' AS " " FROM dual; Sentence saying reminder due 6 weeks before date. Notation (Keywords U-Case) TO_CHAR (With Numbers) Syntax Description TO_CHAR(number, 'fmt') Set format of display for a number Displays name and salary as dollars TO_NUMBER SELECT ename AS "Name", TO_CHAR (sal,'$99,999') AS "Salary" FROM emp; TO_NUMBER (char[, 'fmt']) Converts character string '1000' to number 1000 NVL SELECT TO_NUMBER ('1000') FROM emp; NVL (expr1, expr2) Convert a character string to a number format NVL (number_column, number) SELECT NVL(comm, 0) FROM emp; Converts null to an actual value. Datatypes must remain same Number datatype Converts null values in comm to zero (NVL(comm, 100) changes them to 100) NVL (date_column, date) SELECT NVL (hiredate, '01-JAN-95') FROM emp; Date datatype Converts null to a date Would convert any null values in hiredate to 01-JAN-95 NVL (character_column, 'text') SELECT NVL(job, ' No Job') FROM emp; Character data Converts null to characters Would convert any null values in job to "No Job" SELECT AVG(comm), AVG(NVL(comm, 0)) FROM emp; NVL forces a group function to count null values as 0 Notation (Keywords U-Case) DECODE Syntax Description DECODE (col/expression, search1, result1[, search2, result2, …,] [, default]) Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statements SELECT job, sal, DECODE (job, As for an IF-THEN-ELSE statement: IF job = 'ANALYST' THEN sal = sal*1.1 IF job = 'CLERK' THEN sal = sal*1.15 IF job = 'MANAGER' THEN sal = sal*1.20 ELSE sal = sal FROM emp; (see also p05q11) WHERE table1.column = table2.column Joins table where two columns are the same. Often Primary and Foreign Keys Adds location from dept to info retrieved from emp. Prefixing column with table name identifies ambiguous column names (e.g. emp.deptno vs dept.deptno) also improves performance. For more than 2 tables use WHERE…AND table2.column = table3.column etc. 'ANALYST', SAL*1.1, 'CLERK', SAL*1.15, 'MANAGER', SAL*1.20, SAL) AS revised_salary Equijoin SELECT emp.empno, emp.ename, emp.deptno, dept.loc FROM emp, dept WHERE emp.deptno = dept.deptno; Table aliases SELECT emp.empno, emp.ename, emp.deptno, dept.loc FROM emp, dept WHERE emp.deptno = dept.deptno AND INITCAP(ename) = 'King'; AND additional search conditions where required. SELECT e.empno, e.ename, e.deptno, d.loc FROM emp e, dept d WHERE e.deptno = d.deptno; Saves long prefixes but must be used throughout the select statement (alias valid for select statement only). Alias up to 30 chars, but short as pos, make meaningful. Notation (Keywords U-Case) Non-equijoin Outer join Syntax Description WHERE table1.column CONDITION table2.column/s Where the join is conditional SELECT e.ename, e.sal, s.grade FROM emp e, salgrade s WHERE e.sal BETWEEN s.losal AND s.hisal; Selects name, salary, and grade identifying grade by checking where the salary is between the grade high & low salary columns SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column = table2.column (+); (+) returns missing rows where there is no direct match SELECT e.ename, e.deptno, d.dname FROM emp e, dept d WHERE e.deptno = d.deptno; Does not display d.dname - OPERATIONS (there is noone in that dept.) SELECT e.ename, e.deptno, d.dname FROM emp e, dept d WHERE e.deptno (+) = d.deptno; Displays d.dname - OPERATIONS once (no ename/deptno next to it) - adding that which is not included in emp. Placing the (+) after d.deptno does not display OPERATIONS Switching e.deptno to d.deptno displays 40 & OPERATIONS SELECT e.ename, d.deptno, d.dname FROM emp e, dept d WHERE e.deptno (+) = d.deptno; Notation (Keywords U-Case) Self join Syntax Description SELECT table1alias1.column1, table1alias2.column1 FROM table1 alias1, table1 alias2 WHERE table1alias1.column2 = table1alias2.column3 An equijoin where a table relationship is to the same table, see example below. SELECT worker.ename || ' works for ' || manager.ename FROM emp worker, emp manager WHERE worker.mgr = manager.empno; Does not show King as he has no manager SELECT worker.ename || ' works for ' || NVL(manager.ename, 'the shareholders') FROM emp worker, emp manager WHERE worker.mgr = manager.empno(+); (+) ensures King is listed NVL inserts 'the shareholders' where no manager exists Set operators XXXXXXXX?????????????????? AVG AVG ([DISTINCT|ALL]n) Average value of n ignoring null values. ALL is default on all group functions. SELECT Average of salaries rounded to 2 decimal places Maximum value of salaries paid Minimum value of salaries paid Sum of salaries paid Count of commissions paid Count of different salaries Count of all rows in table Variance of salaries paid Standard deviation of salaries paid FROM emp; ROUND(AVG(sal), 2), MAX(sal), MIN(sal), SUM(sal), COUNT(comm), COUNT(DISTINCT sal), COUNT(*), ROUND(VARIANCE (sal) , 2), ROUND(STDDEV (sal), 2) Notation (Keywords U-Case) COUNT Syntax Description 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) MIN MIN ([DISTINCT|ALL]expr) STDDEV STDDEV ([DISTINCT|ALL]x) Maximum value of expr, ignoring null values (Char - last in alphabetical order) Minimum value of expr, ignoring null values(Char - first in alphabetical order) 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 (Keywords U-Case) GROUP BY Syntax Description GROUP BY column Returns group functions by group specified SELECT deptno, SUM(sal), COUNT(sal), ROUND(AVG(sal), 2), SUM(comm), COUNT(comm), ROUND(AVG(comm) , 2) FROM emp GROUP BY deptno; HAVING Sum of sal by deptno Count of sal by deptno Average of sal by deptno to two decimal places Sum of comm by deptno to two decimal places Count of comm by deptno to two decimal places Average of comm by deptno to two decimal places (null returns on comm for deptno 10 & 20) SELECT deptno, job, sum (sal) FROM emp GROUP BY deptno, job; Returns sum of salary by deptno and job HAVING group_condition Used to restrict groups because WHERE does not work with groups, WHERE has to be used prior to the group clause Returns maximum salary and truncated average salary for departments that have a maximum salary of more than 2900. SELECT deptno, MAX (sal), TRUNC(AVG (sal),) FROM emp GROUP BY deptno HAVING MAX (sal)>2900; Notation (Keywords U-Case) Subqueries single-row subquery Syntax Description SELECT select_list FROM table WHERE expr operator (SELECT FROM Used to select a condition on which a SELECT statement is based. Do not add an ORDER BY clause to a subquery SELECT ename, job FROM emp WHERE job = (SELECT FROM WHERE AND sal > (SELECT FROM WHERE SELECT FROM WHERE select_list table); Two single-row subqueries. job emp empno = 7369) sal emp empno = 7876); ename, job, sal emp sal = (SELECT FROM Subquery using a group function MIN(sal) emp); Notation (Keywords U-Case) Multiple-row subquery Syntax SELECT FROM emp WHERE AND SELECT FROM WHERE Multiple-column subquery Description empno, ename, job sal < ANY (SELECT sal FROM emp WHERE job = 'CLERK') job <> 'CLERK'; empno, ename, job emp sal > ALL (SELECT AVG(sal) FROM emp GROUP BY deptno Use of ANY If a null value is expected to be returned in a suquery NOT IN will return a null value. SELECT statement should be structured to use an IN, it will then return the other values selected Use of ALL SELECT column, column,…. FROM table WHERE (column, column, ….) IN (SELECT (column, column, …. FROM table WHERE condition); Pairwise comparison SELECT column, column,…. FROM table WHERE column IN (SELECT column FROM table WHERE condition) AND column IN (SELECT column FROM table WHERE condition) [AND…..]; Nonpairwise comparison Notation (Keywords U-Case) ANY Syntax Description 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 FROM WHERE empno, ename, sal, deptno emp empno = &employee_num; & Calls the variable or prompts for a value if the variable does not already exist Value discarded once used SELECT FROM WHERE ename, deptno, sal *12 emp job = '&job_title'; Single quotes for dates and character values Can use UPPER, LOWER, & INITCAP with character values, e.g. WHERE job = UPPER('&job_title'); SELECT FROM WHERE SELECT FROM ORDER BY ename, &column_name emp &condition; empno, ename, job, &&column_name emp &column_name; Can be used for names, conditions, expressions, and text e.g. WHERE &condition, ORDER BY &clause. Even whole select statement - SELECT &Select_statement Prompts for column_name once and reuses it as necessary. Has to be UNDEFINE'd to change or use DEFINE or ACCEPT to redefine i.e. repeating &&column_name gives an error message. Value also lost when SQL exited && Notation (Keywords U-Case) DEFINE UNDEFINE Syntax Description DEFINE Lists all variable values DEFINE variable Returns specific variable value DEFINE variable = value Defines a varable as a CHAR datatype DEFINE SELECT FROM ORDER BY column_name = 'deptno' empno, ename, job, &column_name emp &column_name; Defines column name and uses it when the & calls it UNDEFINE variable Undefines the named variable UNDEFINE column_name Undefines column name. Next & or && (&&column_name) gives a prompt for a value Notation (Keywords U-Case) ACCEPT Syntax ACCEPT ACCEPT SELECT FROM WHERE Description variable [datatype] [FORMAT format] [PROMPT text] [HIDE] Reads a line of user input and stores it in a variable - if the 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 dept PROMPT 'Provide the department name: ' * dept dname = UPPER ('&dept'); XXXXXXXXXXNot working - takes the SELECT * as the variable value!!!!!!!!!!!!!!!!!!!!!!!!!!XXXXXXX Notation (Keywords U-Case) SET Syntax Description SET system_variable value SET commands customise the SQL*Plus Environment VERIFY SET VERIFY ON SET VERIFY OFF ECHO SET ECHO ON SET ECHO OFF ARRAYSIZE SQL*Plus command which toggles display of text before and after variables substituted by a value (demonstrate with & example) Controls whether the START command lists each command in a command file as the command is executed. ON lists the commands; OFF suppresses the listing. Sets the database data fetch size LINESIZE ARRAY[SIZE] {20 | n} (Underlined value represents default) COLSEP {_ | text} Sets text to be printed between columns (default single space) FEED[BACK] {6 | n | OFF | ON} Displays the number of records returned by a query when the query selects at least n records HEA[DING] {OFF | ON} Determines whether column headings are displayed in reports 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} TERMOUT TERM[OUT] {OFF | ON} Controls scrolling of the terminal (press [RETURN] after seeing each paused screen) Determines whether output is displayed on screen login.sql Contains std SET and other SQL*Plus commands. COLSEP FEEDBACK HEADING Can use to add permanent changes to set up for each set up, otherwise all the above make alts for session only Notation (Keywords U-Case) COLUMN Syntax Description 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 0 Enforces leading zero $ Floating dollar sign L Local currency . position of decimal point , Thousand separator COLUMN ename HEADING 'Employee|Name' FORMAT A15 COLUMN sal JUSTIFY LEFT FORMAT $99,990.00 COLUMN mgr FORMAT 999999999 NULL 'No manager' 999999 099999 $9999 L9999 9999.99 9,999 1234 001234 $1234 £1234 1234.00 1,234 e.g. formatting columns ename, sal, and mgr Notation (Keywords U-Case) Syntax Description COL[UMN] COL[UMN] ename Displays all column formats Displays ename column formats COL[UMN] ename CLE[AR] CL[EAR] COL[UMN] Clears all formatting for ename Clears all column settings TTITLE TTITLE [text | OFF | ON] Specifies header to appear at the top of each page BTITLE BTITLE [text | OFF | ON] BREAK BRE[AK] [ON report_element] Specifies a footer to appear at the bottom of each page of the report Suppresses duplicate values and sections rows of data with line feeds. Use ORDER BY on columns using break on. Notation (Keywords U-Case) Sample Report Syntax Description SET PAGESIZE 37 SET LINESIZE 60 SET FEEDBACK OFF TTITLE 'Employee|Report' BTITLE 'Confidential' BREAK ON job COL job HEADING 'Job|Category' FORMAT A15 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 FROM emp WHERE sal < 3000 ORDER BY job, ename / SET FEEDBACK ON COL job CLE COL ename CLE COL sal CLE COL sal*12 CLE Page Size Line Length Page Title Page Footer Print job tile once (ORDERed BY job) Formatting required columns including a calculated field The select statement Clear column formats set above Notation (Keywords U-Case) INSERT INTO Syntax Description INSERT INTO FROM table [(column [, column…])] (value [, value…]); Adds a new row. (One row at a time). INSERT INTO VALUES dept (deptno, dname, loc) (50, 'DEVELOPMENT', 'DETROIT'); Puts values into each field in the row INSERT INTO VALUES dept (deptno, dname) (60, 'MIS'); Implicit method of inserting a null value (into loc) omitting column name INSERT INTO VALUES dept (70, 'FINANCE', NULL); Explicit method of inserting a null value Columns filled in order of appearance in table rather than in order stated in 1st example INSERT INTO emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) (7196, USER, 'SALESMAN', 7782, SYSDATE, 2000, NULL, 10); Inserting special values - current user name and current date VALUES INSERT INTO emp VALUES (2296, 'AROMANO', 'SALESMAN', 7782, TO_DATE('FEB 3, 1997', 'MON DD, YYYY'), 1300, NULL, 10); Inserting a date INSERT INTO VALUES Using substitution variables. Customise prompts by using ACCEPT command. (UPPER('&department_ID'), UPPER('&department_name'), UPPER('&location')); eliminates uppercase entry requirement dept (deptno, dname, loc) ('&department_ID', '&department_name', '&location'); Notation (Keywords U-Case) INSERT (cont) Syntax Description UPDATE UPDATE SET [WHERE table column = value [ , column= value, … condition]; Modify existing rows. Can update more than one row at a time, if required. UPDATE SET WHERE emp deptno = 20 empno = 7782; Changes deptno for emp 7782. No WHERE clause would mean all employees changed to deptno 20 Integrity Constraint would prevent deptno 21 being entered (deptno is a foreign key) UPDATE SET emp (job, deptno) = WHERE (SELECT FROM WHERE empno = 7698; INSERT INTO SELECT FROM WHERE UPDATE SET WHERE managers (id, name, salary, hiredate) empno, ename, sal, hiredate emp job = 'MANAGER'; employee deptno = (SELECT FROM WHERE job = (SELECT FROM WHERE Copies rows from another table using a subquery (For creation of managers table see CREATE TABLE example using a subquery) Updates emp 7698 with same job and deptno as emp 7499 job, deptno using a multi-column subquery emp empno =7499) deptno emp empno = 7788) job emp empno = 7788); Changes the deptno in table employee for those employees with a job like emp 7788 to the same dept (as in per the date in table emp). Notation (Keywords U-Case) DELETE Syntax Description DELETE [FROM] [WHERE table condition]; Remove existing rows from a table DELETE FROM WHERE dept dname = 'DEVELOPMENT'; DELETE FROM WHERE emp deptno = (SELECT deptno FROM dept WHERE dname = 'SALES'); Deletes a specific row or rows. Omitting the WHERE clause deletes all rows in the table. If row deleting has a key used elsewhere as a foreign key Integrity Constraint prevents deletion Deletes using subquery COMMIT COMMIT SAVEPOINT SAVEPOINT name Ends the current transaction by making all pending data changes permanent (Action can not be undone) 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 (Keywords U-Case) CREATE TABLE Syntax Description CREATE [GLOBAL TEMPORARY] TABLE [ schema.] table (column datatype [DEFAULT expr] [,…]); Must have CREATE TABLE privilege & a storage area You specify: - Table name - Column name, column datatype, and column size CREATE TABLE shallambeer (BeerID BeerName ABV PriceGallon NUMBER (4), VARCHAR2 (20), NUMBER (3, 2), NUMBER (4,2); (hiredate DATE DEFAULT SYSDATE, …) CREATE TABLE managers AS SELECT empno AS id, ename AS name, sal AS salary, hiredate FROM emp WHERE job = 'MANAGER'; GLOBAL TEMPORARY - Specifies that the table is temporary and definition is visible to all sessions Schema - Same as the owners name. To reference another users table need to prefix the table with the users name. DEFAULT expr specifies default value if a value is omitted in the INSERT statement Creating a table from a subquery Notation (Keywords U-Case) ALTER TABLE ADD Syntax Description ALTER TABLE ADD table (column datatype [DEFAULT expr] [,column datatype…..]); Adding a column ALTER TABLE ADD shallambeer (Comments VARCHAR2 (80) DEFAULT 'Very tastey'); Adds column called comments ALTER TABLE MODIFY table (column datatype [DEFAULT expr] [,column datatype…..]); Modifies an existing column ALTER TABLE MODIFY shallambeer (Comments VARCHAR2 (100) DEFAULT 'Like vinegar'); Modifies datatype length and default. Cannot change data type unless column is empty. ALTER TABLE DROP COLUMN table column; Remove a column (does not have to be empty). ALTER TABLE DROP COLUMN shallambeer comments; SET UNUSED ALTER TABLE SET UNUSED table (column); DROP UNUSED ALTER TABLE table DROP UNUSED COLUMNS; MODIFY DROP COLUMN Removes column from use so that it can be deleted later when demand on system resources is less. Column data no longer available. Deletes all columns which have been previously marked unused. Notation (Keywords U-Case) DROP TABLE Syntax Description RENAME RENAME TRUNCATE TRUNCATE TABLE table; COMMENT COMMENT ON TABLE table | COLUMN table.column IS 'text'; DROP TABLE table; old_name Deletes named table - definition, data, associated indexes TO COMMENT ON TABLE emp IS 'Employee information'; new_name Change the name of an object - table, view, sequence, or synonym. (you must be the owner of the table to rename it) 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.) Adds a comment (up to 2000 bytes) about a table, column, view, or snapshot. Comment stored in the data dictionary. View comments in: - ALL_COL_COMMENTS - USER_COL_COMMENTS - ALL_TAB_COMMENTS - USER_TAB_COMMENTS SELECT comments FROM ALL_TAB_COMMENTS WHERE table_name = 'EMP'; Views comments on table emp COMMENT ON TABLE emp IS ''; 'Drops' a comment by replacing with a space. Notation (Keywords U-Case) CONSTRAINT Defining when creating the table (See Glossary for more information) Syntax CREATE TABLE Description [schema] table (column datatype [DEFAULT expr] [column_constraint], … [table_constraint] [,…]; CREATE TABLE shallamdelivery (DelvID NUMBER (6), CustID NUMBER (4) CONSTRAINT shallamdelivery_CustID_nn NOT NULL, DelvDate DATE DEFAULT SYSDATE, DutyRate NUMBER (5, 2) CONSTRAINT shallamdelivery_DutyRate_nn NOT NULL, OrderNo NUMBER (6), CONSTRAINT shallamdelivery_DelvID_pk PRIMARY KEY (DelvID), CONSTRAINT shallamdelivery_CustID_fk FOREIGN KEY (CustID) REFERENCES shallamcustomer (CustID)); CONSTRAINT shalamdelivery_CustDD_uk UNIQUE (CustID, DelvDate) Setting constraints when the table is created To view USER_CONSTRAINTS & USER_CONS_COLUMNS data dictionary Naming convention for column constraints table_column_pk - PRIMARY KEY table_column_fk - FOREIGN KEY table_column_uk - UNIQUE table_column_nn - NOT NULL table_column_ck - CHECK Setting a NOT NULL constraint Setting a PRIMARY KEY Setting a FOREIGN KEY If this UNIQUE KEY were set it would prevent deliveries on the same day to a particular customer being entered. Notation (Keywords U-Case) ADD CONSTRAINT to an existing table Syntax Description ALTER TABLE table ADD CONSTRAINT constraint_name type (column [constraint]); ADD a CONSTRAINT to an existing table Ensures a value between 10 & 99 is used for DeptNo Cannot add NOT NULL by this method - see below ALTER TABLE emp ADD CONSTRAINT emp_DeptNo_ck CHECK (DeptNo BETWEEN 10 AND 99); DROP CONSTRAINT ALTER TABLE emp MODIFY (DeptNo NOT NULL); Adding a NOT NULL constraint to an existing table (Does not appear to be a way of naming the constraint by this method - receives a SYS_C999999 code from Oracle) ALTER TABLE DROP CONSTRAINT table constraint_name; Deleting a constraint ALTER TABLE DROP CONSTRAINT emp emp_DeptNo_ck; ALTER TABLE emp DROP PRIMARY KEY CASCADE; DISABLE ALTER TABLE table DISABLE CONSTRAINT constraint_name [CASCADE]; ENABLE ALTER TABLE table DISABLE CONSTRAINT constraint_name; Dropping a primary key and cascading to remove dependant constraints (will not delete if there are foreign keys using it) Can also DISABLE in CREATE TABLE. CASCADE clause disables dependent integrity constraints Activates an integrity constraint currently disabled. All data in the table must currently fit the CONSTRAINT Can also ENABLE in CREATE TABLE. Notation (Keywords U-Case) Syntax USER_CONSTRAINTS SELECT USER_CONS_COLUMNS Description Viewing constraints in data dictionary table user_constraints by table FROM WHERE constraint_name, constraint_type, search_condition user_constraints table_name = 'EMP'; SELECT FROM WHERE constraint_name, column_name user_cons_columns table_name = 'EMP'; Viewing constraints in user_cons_columns Notation (Keywords U-Case) VIEW Modify a VIEW Syntax Description CREATE [OR REPLACE] [FORCE | NOFORCE] VIEW view [(alias[, alias]…)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint] ] [WITH READ ONLY]; The subquery cannot contain an ORDER BY clause OR REPLACE recreates the view if it already exists FORCE creates the view even if tables don’t exist NOFORCE creates the view only if tables don’t exist (default) 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 AS SELECT empno AS EMPLOYEE_NUMBER, ename AS name, sal AS SALARY FROM emp WHERE deptno = 30; Creating a simple view DESC view Describes view structure SELECT * FROM empvu10 ORDER BY NAME; Retrieving data from a view (ORDER BY alias not original column name) DROP VIEW empvu10; Deletes view CREATE OR REPLACE VIEW empvu10 (EMPLOYEE_NUMBER, NAME, SALARY) AS SELECT empno, ename, sal FROM emp WHERE deptno = 30; Recreates the view created above but defining aliases in CREATE VIEW clause instead of the SELECT statement A complex VIEW CREATE VIEW AS SELECT FROM WHERE GROUP BY dept_sum_vu (name, minsal, maxsal, avgsal) d.dname, MIN(e.sal), MAX(e.sal), AVG (e.sal) emp e, dept d e.deptno = d.deptno d.dname; Complex view containing group functions CHECK OPTION CREATE OR REPLACE VIEW empvu20 AS SELECT * FROM emp WHERE deptno = 20 WITH CHECK OPTION CONSTRAINT empvu20_ck; ensures that DML operations remain within the domain of the view Stops deptno being changed and so taking the line out of the view (allows other fields to be updated) READ ONLY CREATE OR REPLACE VIEW AS SELECT * FROM emp WHERE deptno = 20 WITH READ ONLY; READ ONLY stops any DML changes empvu20 Notation (Keywords U-Case) Inline views Syntax SELECT FROM WHERE AND Top-N SELECT FROM WHERE Description a.ename, a.ename, a.sal, a.deptno, b.maxsal emp a, (SELECT deptno, max(sal) maxsal FROM emp GROUP BY deptno) b a.deptno = b.deptno a.sal < b.maxsal; Subquery with the alias b [column_list], ROWNUM (SELECT [column_list] FROM table ORDER BY Top-N_column) ROWNUM <= N Asks for the n largest or smallest values WHERE clause must contain < or <= operators SELECT ROWNUM AS rank, ename, sal FROM (SELECT ename, sal FROM emp ORDER BY sal DESC) WHERE ROWNUM <= 6; Ranks employees by sal and shows top 6 SELECT ROWNUM AS rank, ename, sal+NVL(comm, 0) FROM (SELECT ename, sal, comm FROM emp ORDER BY sal+NVL(comm, 0) DESC) WHERE ROWNUM <= 6; Ranks employees by sal + comm and shows top 6 Notation (Keywords U-Case) SEQUENCE Syntax Description CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}]; Creating a sequence CREATE SEQUENCE dept_deptno INCREMENT BY 1 START WITH 91 MAXVALUE 100 NOCYCLE NOCACHE; SELECT FROM sequence_name, min_value, max_value, increment_by, last_number user_sequences; Do not cycle if the sequence is to be used as a primary key unless you have a reliable mechanism that purges old rows faster than the sequence cylcles Confirming a sequence. Last number displays the next available number (if cache size 0) Notation (Keywords U-Case) NEXTVAL Syntax Description INSERT INTO VALUES dept(deptno, dname, loc) (dept_deptno.NEXTVAL, 'MARKETING', 'SAN DIEGO'); NEXT VALUE returns the next available sequence number (A unique value even for different users) CURRVAL SELECT FROM dept_deptno.CURRVAL dual; CURRVAL obtains the current sequence value Modifying a sequence ALTER SEQUENCE dept_deptno INCREMENT BY 1 MAXVALUE 999999 NOCACHE NOCYCLE; Deleting a sequence DROP SEQUENCE dept_deptno; NEXT VALUE & CURRVAL can be used in: the SELECT list of a SELECT statement that is not part of a subquery the SELECT list of a subquery in an INSERT statement the VALUES clause of an INSERT statement the SET clause of an UPDATE statement NEXT VALUE & CURRVAL cannot be used in: 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 (Keywords U-Case) INDEX Confirming Indexes Syntax CREATE INDEX ON index table (column[, column]…); CREATE INDEX ON emp_ename_idx emp(ename); SELECT FROM WHERE AND Remove an index Description ic.index_name, ic.column_name, ic.column_position col_pos, ix.uniqueness user_indexes ix, user_ind_columns ic ic.index_name = ix.index_name ic.table_name = 'EMP'; DROP INDEX index; DROP INDEX emp_ename_idx; Function-Based Indexes CREATE INDEX index ON table (function/column); CREATE INDEX uppercase_idx ON emp (UPPER(ename)); When to create an index: a column is used frequently in a WHERE clause a column contains a wide range of values a column contains a large number of null values two or more columns are frequently used in a WHERE clause or a join the table is large and most queries are expected to retrieve less than 2-4% of the rows More is not always better - the more indexes the more effort the Oracle Server must take to update them. When to create an index: the table is small the columns are not often used as a condition in the query most queries are expected to retrieve more than 2-4% of the rows the table is updated frequently Facilitates queries like: SELECT * FROM emp WHERE UPPER(ename) = 'KING' ; 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 (Keywords U-Case) SYNONYM USER Syntax Description CREATE [PUBLIC] SYNONYM synonym FOR object; Used to: CREATE SYNONYM FOR d_sum dept_sum_vu; DROP SYNONYM d_sum; CREATE USER user IDENTIFIED BY password; CREATE USER pete IDENTIFIED BY abcde; GRANT Privileges GRANT privilege [,privilege…] TO user [, user…]; GRANT create session, create table, create sequence, create view, create procedure TO pete; ROLE CREATE ROLE role; Refer to a table owned by another user Shorten lengthy object names Note: does not work 'insufficient privileges' (scott's privileges) - user and privilege notes copied and left as it is very basic coverage and should therefore be covered more fully in later modules E.g. privileges: CREATE SESSION CREATE TABLE CREATE SEQUENCE CREATE VIEW CREATE PROCEDURE connect to the database create tables in user's schema create sequence in user's schema create view in user's schema create a stored procedure, function, or package in user's schema (see note under user) Role can then be allocated privileges. Makes allocating privileges to a lot of users simpler and standardised CREATE ROLE manager; Changing passwords ALTER USER scott IDENTIFIED BY lion; (see note under user) scott privileges allow this operation Notation (Keywords U-Case) Object Privileges Confirming Privileges REVOKE privilege Syntax Description GRANT object_priv [(columns)] ON object TO {user | role | PUBLIC } [WITH GRANT OPTION]; See list of object privileges in glossary ALL specifies all object privileges PUBLIC grants object privileges to all users WITH GRANT OPTION allows grantee to grant the privileges to others GRANT ON TO select emp sue, rich; SELECT FROM [WHERE * data_dictionary USER = 'name']; SELECT FROM WHERE * USER_SYS_PRIVS USER = scott; Data Dictionary ROLE_SYSTEM_PRIVS ROLE_TAB_PRIVS USER_SYSTEM_PRIVS USER_ROLE_PRIVS USER_TAB_PRIVS_MADE USER_TAB_PRIVS_RECD USER_COL_PRIVS_MADE USER_COL_PRIVS_RECD REVOKE { privilege [,privilege…] | ALL} ON object FROM {user[, user…] | role | PUBLIC} [CASCADE CONSTRAINTS]; CSACADE CONSTRAINTS necessary where REFERENCES privilege has been used REVOKE ON FROM If a WITH GRANT OPTION is revoked the revoke cascades to all users who have been granted by that user including any new WITH GRANT OPTION's select, insert dept scott; PL/SQL: (Notation these notes: [ ] optional, { } must contain something) Notation (Keywords U-Case) PL/SQL block types Anonymous: Syntax Description Every unit of PL/SQL comprises one or more blocks. Anonymous: Unnamed blocks declared at the point in an application where they are to be executed. Can be embedded within a pre-compiler program and within SQL*Plus or Server manager. Triggers in Oracle Developer components consist of such blocks. [DECLARE] BEGIN --statements [EXEPTION] Procedure: (subprogram) Function: (subprogram) END; PROCEDURE IS name BEGIN --statements [EXEPTION] END; FUNCTION name RETURN datatype IS BEGIN --statements RETURN value; [EXEPTION] END; Subprograms: Named PL/SQL blocks (procedures or functions) that can take parameters and can be invoked. Generally procedures perform an action and functions return a value. Can store at server or application level. Can be called from other procedures, functions, and triggers within the same application. Notation (Keywords U-Case) Variables DECLARE Syntax Description DECLARE identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; DECLARE v_hiredate v_deptno v_location c_comm %TYPE Assigning Values DECLARE v_ename DATE; NUMBER (2) NOT NULL := 10; VARCHAR2 (13) := 'Atlanta'; CONSTANT NUMBER := 1400; emp.ename%TYPE; identifier := expr; Naming convention v_variable and c_constant Two variables can have the same name, provided they are in different blocks Identifier should not be the same as the name of columns used in the same block Initialise using the assignment operator (:=) or the DEFAULT reserved word Must initialise variables designated as NOT NULL and CONSTANT Declare only one identifier per line Variables are initialised every time a block or subprogram is entered - default to null unless initialised v_hiredate := '31-DEC-98' v_hiredate DEFAULT '31-DEC-98' Note: No TO_DATE function required in 8i SELECT INTO FROM WHERE BOOLEAN (Initialising with an expression) sal * 0.10 v_bonus emp empno = 7369; v_sal1 := 50000 v_sal2 := 60000 v_comm_sal := (v_sal1 < v_sal2); This case sets the variable to TRUE Notation (Keywords U-Case) Declaring a bind variable (in SQL*Plus) Syntax Description VARIABLE identifier TYPE Can be referenced by SQL and SQL*Plus. SQL*Plus can display its value. Display value PRINT identifier Referencing NonPL/SQL Variables VARIABLE g_monthly_sal NUMBER 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; END; / PRINT Note: Must prefix non-PL/SQL variables with a colon g_monthly_sal DBMS_OUTPUT.PUT_ SET SERVEROUTPUT ON ACCEPT p_annual_sal PROMPT 'Please enter the LINE annual salary: ' DECLARE 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; / An Oracle-supplied packaged procedure as an alternative to display data from a PL/SQL block. Must be enabled in SQL*Plus with: SET SERVEROUTPUT ON Notation (Keywords U-Case) Datatype conversion TO_CHAR Syntax Description DECLARE v_date VARCHAR2 (15) BEGIN SELECT TO_CHAR (hiredate, 'MON, DD, YYYY') INTO v_date FROM emp WHERE empno = 7839; TO_DATE v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY); Nested Blocks and Variable Scope … x BINARY_INTEGER; BEGIN … DECLARE y NUMBER; BEGIN scope … of y END; … END; TO_CHAR TO_DATE TO_NUMBER (value, fmt) (value, fmt) (value, fmt) PL/SQL will automatically try to convert data but it does not always work and can slow processing down - it is good practise to explicitly perform datatype conversions. A block can look up into the enclosing block A block cannot look down to enclosed blocks scope of x i.e. the nested block, shown left, can reference the external variable x, but y can only be referenced by the nested block (see also Introduction to Oracle: SQL & PL/SQL 17-20) Notation (Keywords U-Case) PL/SQL Operator examples Syntax Description Operator Operation **, NOT +, *, / +, -, || =, !=, <, >, <=, >=, IS NULL, LIKE, BETWEEN, IN AND OR Exponentiation, logical negation Identity, negation Multiplication, division Addition, subtraction, concatenation Comparison Conjunction Inclusion 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 (Keywords U-Case) SELECT in PL/SQL Syntax SELECT INTO FROM WHERE Description select_list {variable_name[, variable_name]… | record_name} table condition; e.g. DECLARE v_deptno v_loc BEGIN SELECT INTO FROM WHERE END; / NUMBER(2); VARCHAR2(15); deptno, loc v_deptno, v_loc dept dname = 'SALES'; select_list at least one column and can include SQL expressions, row functions, or group functons varriable_name the scalar variable to hold the retrieved values record_name PL/SQL RECORD to hold the retrieved values The INTO clause is mandatory to specify variables to hold the selected values (PL/SQL or host variables). One variable per value - order corresponding to selection order. Select statements within PL/SQL fall into the ANSI classification of Embedded SQL - queries must only return one row, more than one row returns an error. (exceptions NO_DATA_FOUND and TOO_MANY_ROWS) To retrieve data in PL/SQL: 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 (Keywords U-Case) INSERT in PL/SQL Syntax Description BEGIN INSERT INTO emp(empno, ename, job, deptno) VALUES (empno_sequence.NEXTVAL, 'HARDING', 'CLERK', 10); END; UPDATE in PL/SQL DECLARE v_sal_increase emp.sal%TYPE := 2000 BEGIN UPDATE emp SET sal = sal + v_sal_increase WHERE job = 'ANALYST'; END; If no rows are modified no error occurs. PL/SQL variable assignments always use := SQL variable assignments always use = DELETE in PL/SQL DECLARE v_deptno emp.deptno%TYPE := 10; BEGIN DELETE FROM emp WHERE deptno = v_deptno; END; Naming Conventions for identifiers Use a naming convention to avoid ambiguity in the WHERE clause 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 Use SQL Functions, Such As USER And SYSDATE Generate primary key values using database sequences Derive values in the PL/SQL block Add column default values e.g. deptno and v_deptno - meaningful variable name with a meaningful prefix Notation (Keywords U-Case) COMMIT Syntax Description 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] savepoint_name; Rolls back work to the savepoint named VARIABLE rows_deleted VARCHAR2(30) DECLARE v_name VARCHAR2(30) := 'MELLOR'; BEGIN DELETE FROM MANAGERS WHERE name = v_name; :rows_deleted := (SQL%ROWCOUNT ||' rows deleted.'); END; / PRINT rows_deleted SQL%ROWCOUNT being used to check how many rows have been deleted. Procedure returned successful even though nothing deleted (no manager named MELLOR) SQL%ROWCOUNT This PL/SQL block returns: PL/SQL procedure successfully completed. SQL> PRINT rows_deleted [RETURN] ROWS_DELETED -------------------------------0 rows deleted. See also SQL Cursor Attributes - Glossary Notation (Keywords U-Case) IF statements Syntax Description … IF condition THEN statements; [ELSIF condition THEN statements;] [ELSE statements;] END IF; … condition - a boolean variable or expression (TRUE, FALSE, or NULL) THEN - associates the preceding boolean expression with the sequence that follows. statements - one or more PL/SQL or SQL statements ELSIF - introduces further boolean expression which is used if the first is FALSE or NULL . 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 V_name := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF; For Boolean conditions see Glossary " Building Logical Conditions" IF - THEN - ELSE END IF IF v_shipdate - v_orderdate < 5 THEN 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 (Keywords U-Case) LOOP Syntax LOOP Statement1; … EXIT [WHEN condition]; END LOOP; FOR - LOOP Description -- delimiter -- statements Where the condition is a Boolean variable or expression (TRUE, FALSE, or NULL) -- EXIT statement -- delimiter EXIT can be used within an IF statement or as a standalone statement. A basic loop can contain multiple EXIT statements. DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER (2) := 1; BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter) v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP; END; FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; … END LOOP; DECLARE v_ordid item.ordid%TYPE := 601; BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP; END; If v_counter not set it is NULL and so v_counter + 1 would never get to 10 and so never satisfy the EXIT condition. (i.e. null + 1 = null) Counter does not need to be declared (implicitly declared as an integer) and can be named anything you like, e.g. FOR i in [REVERSE] REVERSE causes the counter to decrement from the upper_bound to the lower_bound (lower_bound still referenced first) lower_bound specifies the lower bound for the range of counter values. upper_bound specifies the upper bound for the range of counter values. Can be literals, variables, or expressions. Notation (Keywords U-Case) WHILE - LOOP Syntax Description WHILE condition LOOP statement1; statement2; … END LOOP; Condition (Boolean variable or expression) is evaluated at the beginning of each iteration. If the condition yields null the loop is bypassed and control passes to next statement. 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 (Keywords U-Case) Nested Loops and Labels Syntax … 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; END LOOP Outer_loop; END; Description Inner_loop and Outer_loop andded after END LOOP statements for clarity. Notation (Keywords U-Case) Creating a PL/SQL Record Syntax Description TYPE type_name IS RECORD (field_declaration [, field_declaration]…); identifier type_name; type_name Where field_declaration is: field_name {field_type | variable%TYPE | table.column%TYPE | table&ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr] field_name field_type expr the name of the RECORD type (this identifier is used to declare records) the name of a field within the record the datatype of the field (any PL/SQL datatype except REFCURSOR. Can use %TYPE and %ROWTYPE attribitutes) the field_type or an initial value Note: NOT NULL fields must be initialised … TYPE emp_record_type IS RECORD (ename VARCHAR2(10), job VARCHAR2(9), sal NUMBER(7, 2)); emp_record emp_record_type; … Referencing a field within a record emp_record.job … Assigning values to record fields emp_record.job := 'CLERK'; Have to declare the datatype before declaring the identifier. User defined records are instantiated when you enter the block or subprogram and cease to exist when you exit. Can assign values by SELECT or FETCH statements selection must be in same order as record fields. Can also assign one record to another. A user-defined record and a %ROWTYPE record never have the same datatype. Notation (Keywords U-Case) %ROWTYPE Syntax Description DECLARE identifier reference.%ROWTYPE; Gives the record fields names and datatypes = table row. identifier - name of record, reference - name of table, view, cursor, or cursor variable Adv: number and datatypes of the underlying database may not be known, number and datatypes may change, useful when retrieving a row in a SELECT statement. DECLARE emp_rec emp.%ROWTYPE; BEGIN SELECT * INTO emp_rec FROM emp WHERE empno = &employee_number; INSERT INTO retired_emps(empno, ename, job, 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; Code left declares identifier and reference Selects a row from the emp table by user input and then identifies table and fields to insert the values into. Notation (Keywords U-Case) Creating PL/SQL Tables Syntax Description TYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] [INDEX BY BINARY_INTEGER]; identifier type_name; 1. Declare a TABLE datatype 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 INDEX BY BINARY_INTEGER; TYPE hiredate_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER; ename_table ename_table_type; hiredate_table hiredate_table_type; BEGIN ename_table(1) := 'CAMERON'; hiredate_table(8) := SYSDATE + 7; IF ename_table.EXISTS(1) THEN INSERT INTO … … END; BINARY_INTEGER range is -2147483647…2147483647 so the primary key value can be negative and indexing need not start with 1. (1) references row 1 (8) references row 8 EXISTS see Glossary - PL/SQL Table Methods Notation (Keywords U-Case) PL/SQL Table of Records Syntax Description DECLARE TYPE dept_table_type IS TABLE OF dept%ROWTYPE INDEX BY BINARY_INTEGER; dept_table dept_table_type; table(index).field dept_table(15).loc Declaring Explicit Cursors Each element of dept_table is a record and fields within the records can be accessed := '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) CURSOR cursor_name IS select_statement; Opening Explicit Cursors OPEN cursor_name; Fetching Data from a Cursor FETCH cursor_name Examples 21-11 [variable1, variable1, …] | record_name]; cursor_name is a PL/SQL identifier, select_statement is a SELECT statement without an INTO clause. Can include ORDER BY in query if required. Open the previously declared query to execute to query and 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. same number of variables as columns in the FETCH match variable and column positions (or define a record for the cursor and reference in the FETCH INTO 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 (Keywords U-Case) Syntax Description Glossary !Unexpected End of FormulaSQL SQL*Plus 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. Command language for communication with the Oracle Server from any tool or application. (see Introduction to Oracle: SQL and PL/SQL Volume 1 p 1-24 & 1-25) 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) Fixed-length character value of size s (max possible 2000) Null CHAR(s) LONG CLOB RAW(s) and LONG RAW(s) BLOB BFILE Variable-length character data up to 2 gigabytes Single-byte character data up to 4 gigabytes, e.g. book Raw binary data (max size 2000 and 2 gigabytes) Binary data up to 4 gigabytes, e.g. photo Binary data stored in an external file up to 4 gigabytes, e.g. film SQL Functions Single-row SQL functions Multiple-row SQL functions Character 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 Operate on single rows only and return one result per row - character, number, date, conversion, general (Can be nested) Manipulate groups of rows and give one result per group Case conversion functions LOWER UPPER INITCAP Character manipulation functions CONCAT SUBSTR LENGTH INSTR LPAD (RPAD) TRIM (LTRIM, RTRIM) Number functions ROUND 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 Functions Joins Group functions CHR Subqueries Implicit datatype conversion (automatically done by Oracle) From From From From Explicit datatype conversion TO_CHAR TO_NUMBER TO_DATE Where two columns the same in different tables (e.g. Primary/Foreign Keys) Where columns joined not the same (linked with a condition, e.g. BETWEEN) Two main types: Equijoin Non-equijoin Additional joins: Outer join Self join Set operators VARCHAR2 Or CHAR VARCHAR2 Or CHAR NUMBER DATE to to to to NUMBER DATE VARCHAR2 VARCHAR2 AVG COUNT MAX MIN STDDEV SUM VARIANCE GROUP BY HAVING SQL function that converts an ASCII code to its corresponding character 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 Objects PL/SQL Substitution variables Object Description Naming Conventions - all database objects Table View Sequence Basic unit of storage; composed of rows and columns Logically represents subsets of data from one or more tables. Contains no data of its own Generates primary key values Index Improves the performance of some queries Rules: 1. Must begin with a letter 2. 1-30 characters long 3. Must contain only A-Z, a-z, 0-9, _, $, and # 4. Must not duplicate the name of another object owned by the same user 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: Names are case insensitive Note: Other database objects exist but not covered this course 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. & to prompt for and temporarily store values && 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 Format Commands SQL*Plus Customization Commands Database Transaction Report formatting commands: COLUMN, TTITLE, BTITLE, BREAK ARRAYSIZE, COLSEP, FEEDBACK, HEADING, LINESIZE, LONG, PAGESIZE, PAUSE, TERMOUT, ECHO, VERIFY (full list in Oracle8I On-Line Generic Documentation CD) A database transaction consists of a collection of DML statements that form a logical unit of work, one DDL, or one DCL 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 Rollback If DML statement fails during execution, only that statement is rolled back (an implicit savepoint implemented by Oracle Server) and all other changes are retained. Read Consistency Read consistency (automatic implementation) ensures that each user sees data as it existed at the last commit (or DDL/DCL 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 Structures User Tables Tables can be created at any time even when users are accessing the database 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 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_ ALL_ DBA_ Contain information about objects owned by the user Contain information about all the tables (object tables and relational tables) accessible to the user These views are restricted views. These views can be accessed only by people who have been assigned the role of DBA Contain information about dynamic performance views, database server performance, and locking. V$_ Querying the data dictionary: SELECT FROM * user_tables; SELECT FROM DISTINCT object_type user_objects; SELECT FROM * user_catalog; (FROM CAT; uses synonym instead of user_catalog) Constraints Constraints are used to: NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK - 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 - specifies that this column may not contain a NULL value (Can only be set at column level not table level) - 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) - uniquely identifies each row of the table - establishes and enforces a foreign key relationship between the column and a column of the referenced table - 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 Contains functions Contain groups of data DML through view One No No Yes One or more Yes 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 Sequence You must be the owner or have the ALTER privilege for the 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: Privileges Object Privileges Oracle Developer - 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 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 Privilege Table View Sequence Procedure ALTER DELETE EXECUTE INDEX INSERT REFERENCES SELECT UPDATE Makes use of shared library and consists of Oracle Forms, Reports, and Graphics. Has its own independent PL/SQL engine. PL/SQL engine PL/SQL Program Constructs 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. Construct Description Availability Anonymous Unnamed block that is embedded within an application All PL/SQL environments block or is issued interactively Stored Procedure or function Named block stored in the Oracle Server that can be invoked repeatedly by name Oracle Server Application procedure or function Named block stored in an Oracle Developer application or shared library that can accept parameters and can be invoked repeatedly by name Oracle Developer components - for example, Forms Package Named module that groups related procedures, functions, and identifiers Oracle Server and Developer components - for example, Forms Database trigger A block that is associated with a table and is fired automatically when triggered by DML statements Oracle Server Application trigger A block that is associated with an application event and is fired automatically Oracle Developer components - for example, Forms PL/SQL Variables Use: Temporary storage of data 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 Variables Bind and host language variables such as those declared in pre-compiler programs, screen fields in Forms applications, and SQL*Plus host variables Scalar datatypes BOOLEAN 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 Stores TRUE, FALSE, or NULL BINARY_INTE GER Base type for integers between -2,147,483,647 and 2,147,483,647 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 datatypes (collections) LOB Can be TABLE, RECORD, NESTED TABLE, and VARRAY CLOB, BLOB, BFILE, NCLOB (national language character large object - used to store large blocks of single-byte or fixedwidth multibyte NCHAR data in the database, in line or out of line. PL/SQL Block Syntax and guidelines Statements can continue over several lines Lexical units can be separated by: - Spaces - Delimiters - Identifiers - Literals - Comments Reserved words should be written in uppercase to promote readability PL/SQL Delimiters Symbol + * / = @ ; Meaning Addition operator Subtraction/negation operator Multiplication operator Division operator Relational operator Remote access indicator Statement terminator Symbol <> != || /* */ := Meaning Relational operator Relational operator Concatenation operator Single line comment indicator Beginning comment indicator Ending comment indicator 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 in PL/SQL PL/SQL Functions Available in procedural statements: - 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) Built in function categories: Error reporting Number Character Conversion Date Miscellaneous Programming Guidelines Manipulating Data using PL/SQL Category Case Convention Examples SQL statements PL/SQL keywords Datatypes Identifiers and parameters Database tables and columns Uppercase Uppercase Uppercase Lowercase Lowercase SELECT, INSERT DECLARE, BEGIN, IF VARCHAR2, BOOLEAN v_sal, emp_cursor, g_sal, p_empno emp, orderdate, deptno Identifier Naming Convention Variable Constant Cursor Exception Table type Table Record type Record SQL*Plus substitution variable (also referred to as substitution parameter) SQL*Plus global variable (also referred to as host or bind variable) v_name c_name name_cursor e_name name_table_type name_table name_record_type name_record p_ name v_sal c_company_name emp_cursor e_too_many amount_table_type order_total_table emp_record_type customer_record p_sal g_ name g_year_sal Indent each level of code for clarity INSERT adds new rows of data UPDATE modifies existing rows in the table DELETE removes unwanted rows Building Logical Conditions Handle null values with the IS NULL operator. Any arithmetic expression containing a null value evaluates to NULL. Concatenated expressions with null values treat null values as an empty string. Logic Tables: AND TRUE FALSE NULL TRUE FALSE NULL OR TRUE FALSE TRUE FALSE NULL TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE NULL FALSE NULL TRUE NULL NULL * The negation of NULL(NOT NULL) results in a null value because null values are indeterminate Composite Datatypes PL/SQL Records PL/SQL Tables NULL TRUE NULL NULL NOT TRUE FALSE NULL Also known as collections, composite datatypes are: 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 A record is a group of related data items stored in fields, each with its own name and datatype. 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 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. FALSE TRUE NULL* PL/SQL Table Methods Method EXISTS(n) COUNT FIRST LAST PRIOR(n) NEXT(n) EXTEND* TRIM* DELETE* Description Returns TRUE if the nth element in a PL/SQL table exists. Returns the number of elements that a PL/SQL table currently contains. Returns the first and last (smallest and largest) index numbers in a PL/SQL table. Returns NULL if the PL/SQL table is empty. Returns the index number that precedes index n in a PL/SQL table. Returns the index number that succeeds index n in a PL/SQL table. 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 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 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 m…n from a PL/SQL TABLE. SQL Cursor (CURrent S et Of Rows) 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. A cursor is a private SQL work area There are two types of cursors: 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 Attributes SQL%ROWCOUNT SQL%FOUND Number of rows affected by the most recent SQL statement (an integer value) Boolean attribute that evaluates to TRUE if the most recent SQL statement affects one or more rows 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 YYY, YY, or Y Y,YYY IYYY, IYY, IY, I RR Year, S prefixes BC date with - (minus) Last three, two, one digit of the year Comma in year Four, three, two, one digit year based on the ISO standard SYEAR, YEAR BC or AD Q MM MONTH MON RM WW, W DDD, DD, D DAY DY J Similar to YY etc but selects Century according to the specified two digit year (0-49 and 50-99) Year spelled out, S prefixes BC date with - (minus) BC/AD indicator Quarter of a year Month, two-digit value Name of month padded with blanks to length of nine characters Month - 3 letters Roman numeral month Week of year or month Day of year, month, or week Name of day padded with blanks to length of nine characters Day - 3 leters Julian day: the number of days since 31 Dec 4713 BC Valid Time Format Table AM or PM A.M. or P.M. HH or HH12 or HH24 MI SS SSSSS Meridian indicator Meridian indicator with periods Hour of day or hour (1-12) or hour (0-23) Minute (0-59) Second (0-59) Seconds past midnight (0-86399) Other Date Format Features /., "of the" Punctuation is reproduced in the result Quoted string is reproduced in the result Suffixes TH SP SPTH or THSP Ordinal number (e.g. DDTH for 4TH) Spelled out number (e.g. DDSP for FOUR) Spelled out ordinal number 9 0 $ L . , MI PR EEEE V B TO_CHAR (number, 'fmt') See also TO_CHAR (With Numbers) Example Represents a number 999999 Forces a zero to be displayed 099999 Places a floating dollar symbol $999999 Uses the floating local currency symbol L999999 Prints a decimal point 999999.99 Prints a thousand indicator 999,999 Minus signs to right (negative values) 999999MI Parenthesise negative numbers 999999PR Scientific notation (format must specify four Es) 99.999EEEE Multiply by 10 n times (n = number of 9s after V) 9999V99 Display zero values as blank, not 0 B9999.99 TO_CHAR with numbers Result 1234 001234 $1234 £1234 1234.00 1,234 1234<1234> 1.234E+03 123400 1234.00