Your SlideShare is downloading. ×
Oracle sql & plsql
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Oracle sql & plsql

7,726
views

Published on

Oracle SQL & PLSQL fundamental

Oracle SQL & PLSQL fundamental

Published in: Technology

9 Comments
26 Likes
Statistics
Notes
No Downloads
Views
Total Views
7,726
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
1,329
Comments
9
Likes
26
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Copyright © 2004, Oracle. All rights reserved.
  • 2. Oracle SQL & PL/SQL Huiyun Mao Yolanda.mao@oracle.comCopyright © 2004, Oracle. All rights reserved.
  • 3. SQL OverviewCopyright © 2004, Oracle. All rights reserved.
  • 4. SQL Statements SELECT Data retrieval language (DRL) INSERT UPDATE Data manipulation language (DML) DELETE CREATE ALTER DROP Data definition language (DDL) RENAME TRUNCATE COMMIT ROLLBACK Transaction control SAVEPOINT GRANT Data control language (DCL) REVOKECopyright © 2004, Oracle. All rights reserved.
  • 5. Tables Used in the Course Three main tables are used in this course: Three main tables are used in this course: – – EMP table EMP table – – DEPT table DEPT tableCopyright © 2004, Oracle. All rights reserved.
  • 6. The EMP Table EMP EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ---------- --------- --------- --------- --------- --------- --------- 7839 KING PRESIDENT 17-NOV-81 5000 10 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 7782 CLARK MANAGER 7839 09-JUN-81 1500 10 7566 JONES MANAGER 7839 02-APR-81 2975 20 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30 7900 JAMES CLERK 7698 03-DEC-81 950 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 7902 FORD ANALYST 7566 03-DEC-81 3000 20 7369 SMITH CLERK 7902 17-DEC-80 800 20 7788 SCOTT ANALYST 7566 09-DEC-82 3000 20 7876 ADAMS CLERK 7788 12-JAN-83 1100 20 7934 MILLER CLERK 7782 23-JAN-82 1300 10 Primary key Foreign key Foreign keyCopyright © 2004, Oracle. All rights reserved.
  • 7. DEPT Tables DEPT DEPTNO DNAME LOC --------- -------------- ---------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON Primary keyCopyright © 2004, Oracle. All rights reserved.
  • 8. Writing Basic SQL StatementsCopyright © 2004, Oracle. All rights reserved.
  • 9. Capabilities of SQL SELECT Statements Restriction Projection Table 1 Table 1 Join Table 1 Table 2Copyright © 2004, Oracle. All rights reserved.
  • 10. Basic SELECT Statement SELECT [DISTINCT] {*, column [alias],...} FROM table [WHERE condition(s)] [GROUP BY group_by_expression] [ORDER BY column]; – – SELECT identifies the columns to be displayed. SELECT identifies the columns to be displayed. – – FROM identifies the table that contains the columns. FROM identifies the table that contains the columns.Copyright © 2004, Oracle. All rights reserved.
  • 11. Writing SQL Statements – – SQL statements are not case sensitive. SQL statements are not case sensitive. – – SQL statements can be on one or SQL statements can be on one or more lines. more lines. – – Keywords cannot be abbreviated or split across lines. Keywords cannot be abbreviated or split across lines. – – Clauses are usually placed on Clauses are usually placed on separate lines. separate lines. – – Tabs and indents are used to enhance readability. Tabs and indents are used to enhance readability.Copyright © 2004, Oracle. All rights reserved.
  • 12. Retrieving All Columns from a Table DEPT Retrieve all DEPTNO DNAME LOC columns from the 10 ACCOUNTING NEW YORK DEPT table 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON DEPT DEPTNO DNAME LOC 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON All columns are displayedCopyright © 2004, Oracle. All rights reserved.
  • 13. Selecting All Columns SQL> SELECT * 2 FROM dept; DEPTNO DNAME LOC --------- -------------- ------------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTONCopyright © 2004, Oracle. All rights reserved.
  • 14. Creating a Projection on a Table DEPT DEPTNO DNAME LOC Retrieve DEPTNO and LOC columns 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS from the DEPT 30 SALES CHICAGO table 40 OPERATIONS BOSTON DEPT DEPTNO LOC 10 NEW YORK 20 DALLAS 30 CHICAGO 40 BOSTON Only two columns are displayedCopyright © 2004, Oracle. All rights reserved.
  • 15. Selecting Specific Columns SQL> SELECT deptno, loc 2 FROM dept; DEPTNO LOC --------- ------------- 10 NEW YORK 20 DALLAS 30 CHICAGO 40 BOSTONCopyright © 2004, Oracle. All rights reserved.
  • 16. Default Column Justification Character Date Number left justified left justified right justified EMP ENAME HIREDATE SAL ---------- --------- --------- KING 17-NOV-81 5000 BLAKE 01-MAY-81 2850 CLARK 09-JUN-81 2450 JONES 02-APR-81 2975 MARTIN 28-SEP-81 1250 ALLEN 20-FEB-81 1600 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 17. Arithmetic Expressions Create expressions on NUMBER and DATE data Create expressions on NUMBER and DATE data types by using arithmetic operators. types by using arithmetic operators. Operator Description + Add - Subtract * Multiply / DivideCopyright © 2004, Oracle. All rights reserved.
  • 18. Using Arithmetic Operators SQL> SELECT ename, sal, sal+300 2 FROM emp; ENAME SAL SAL+300 ---------- --------- --------- KING 5000 5300 BLAKE 2850 3150 CLARK 2450 2750 JONES 2975 3275 MARTIN 1250 1550 ALLEN 1600 1900 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 19. Using Arithmetic Operators on Multiple Columns SQL> SELECT grade, hisal-losal 2 FROM salgrade; GRADE HISAL-LOSAL --------- ----------- 1 500 2 199 3 599 4 999 5 6998Copyright © 2004, Oracle. All rights reserved.
  • 20. Operator Precedence / + _ * – – Multiplication and division take priority over addition Multiplication and division take priority over addition and subtraction. and subtraction. – – Operators of the same priority are evaluated from left to Operators of the same priority are evaluated from left to right. right. – – Parentheses are used to force prioritized evaluation Parentheses are used to force prioritized evaluation and to clarify statements. and to clarify statements.Copyright © 2004, Oracle. All rights reserved.
  • 21. Operator Precedence SQL> SELECT ename, sal, 12*sal+100 2 FROM emp; ENAME SAL 12*SAL+100 ---------- --------- ---------- KING 5000 60100 BLAKE 2850 34300 CLARK 2450 29500 JONES 2975 35800 MARTIN 1250 15100 ALLEN 1600 19300 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 22. Using Parentheses SQL> SELECT ename, sal, 12*(sal+100) 2 FROM emp; ENAME SAL 12*(SAL+100) ---------- --------- ----------- KING 5000 61200 BLAKE 2850 35400 CLARK 2450 30600 JONES 2975 36900 MARTIN 1250 16200 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 23. Defining a Column Alias – – Renames a column heading Renames a column heading – – Is useful with calculations Is useful with calculations – – Immediately follows column name; optional AS Immediately follows column name; optional AS keyword between column name and alias keyword between column name and alias – – Requires double quotation marks if it is case sensitive Requires double quotation marks if it is case sensitive or contains spaces or special characters or contains spaces or special charactersCopyright © 2004, Oracle. All rights reserved.
  • 24. Using Column Aliases SQL> SELECT ename AS name, sal salary 2 FROM emp; NAME SALARY ------------- --------- KING 5000 BLAKE 2850 CLARK 2450 JONES 2975 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 25. Using Column Aliases SQL> SELECT ename "Name", 2 sal*12 "Annual Salary" 3 FROM emp; Name Annual Salary ------------- ------------- KING 60000 BLAKE 34200 CLARK 29400 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 26. Concatenation Operator – – Concatenates columns or character strings to other Concatenates columns or character strings to other columns columns – – Is represented by two vertical bars || Is represented by two vertical bars || – – Creates a result column that is a character expression Creates a result column that is a character expressionCopyright © 2004, Oracle. All rights reserved.
  • 27. Using the Concatenation Operator SQL> SELECT ename||job AS "Employees" 2 FROM emp; Employees ------------------- KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER MARTINSALESMAN ALLENSALESMAN ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 28. Literals – – A literal is a constant value of character, expression, or A literal is a constant value of character, expression, or number that can be included in the SELECT list. number that can be included in the SELECT list. – – Date and character literal values must be enclosed in Date and character literal values must be enclosed in single quotation marks. single quotation marks. – – Each character string is output once for each row Each character string is output once for each row returned. returned.Copyright © 2004, Oracle. All rights reserved.
  • 29. Using Literal Character Strings SQL> SELECT ename|| is a ||job AS 2 "Employee Details" 3 FROM emp; Employee Details ------------------------- KING is a PRESIDENT BLAKE is a MANAGER CLARK is a MANAGER JONES is a MANAGER MARTIN is a SALESMAN ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 30. Duplicate Rows The default display of queries is all rows, including The default display of queries is all rows, including duplicate rows. duplicate rows. SQL> SELECT deptno 2 FROM emp; DEPTNO --------- 10 30 10 20 .. 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 31. Eliminating Duplicate Rows Eliminate duplicate rows by using the DISTINCT Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause. keyword in the SELECT clause. SQL> SELECT DISTINCT deptno 2 FROM emp; DEPTNO --------- 10 20 30Copyright © 2004, Oracle. All rights reserved.
  • 32. Restricting and Sorting DataCopyright © 2004, Oracle. All rights reserved.
  • 33. Limiting Rows by Using a Restriction EMP EMPNO ENAME JOB ... DEPTNO Retrieve all 7839 KING PRESIDENT 10 employees 7698 BLAKE MANAGER 30 in department 10 7782 CLARK MANAGER 10 7566 JONES MANAGER 20 ... EMP EMPNO ENAME JOB ... DEPTNO 7839 KING PRESIDENT 10 7782 CLARK MANAGER 10 7934 MILLER CLERK 10Copyright © 2004, Oracle. All rights reserved.
  • 34. Using the WHERE Clause SQL> SELECT ename, job, deptno 2 FROM emp 3 WHERE deptno=10; ENAME JOB DEPTNO ---------- --------- --------- KING PRESIDENT 10 CLARK MANAGER 10 MILLER CLERK 10Copyright © 2004, Oracle. All rights reserved.
  • 35. Character Strings and Dates – – Character strings and date values are enclosed in Character strings and date values are enclosed in single quotation marks. single quotation marks. – – Character values are case sensitive and date values Character values are case sensitive and date values are format sensitive. are format sensitive. – – Default date format is DD-MON-YY. Default date format is DD-MON-YY. SQL> SELECT ename, job, deptno, hiredate 2 FROM emp 3 WHERE ename = JAMES;Copyright © 2004, Oracle. All rights reserved.
  • 36. Comparison Operators Operator Meaning = Equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to <> Not equal toCopyright © 2004, Oracle. All rights reserved.
  • 37. Using the Comparison Operators with Another Column SQL> SELECT ename, sal, comm 2 FROM emp 3 WHERE sal<=comm; ENAME SAL COMM ---------- --------- --------- MARTIN 1250 1400Copyright © 2004, Oracle. All rights reserved.
  • 38. Using the Comparison Operators with Characters SQL> SELECT ename, mgr 2 FROM emp 3 WHERE ename=SMITH; ENAME MGR ---------- --------- SMITH 7902Copyright © 2004, Oracle. All rights reserved.
  • 39. Other SQL Comparison Operators Operator Meaning BETWEEN Between two values (inclusive) ...AND... IN(list) Match any of a list of values LIKE Match a character pattern IS NULL Is a null valueCopyright © 2004, Oracle. All rights reserved.
  • 40. Using the BETWEEN Operator Use the BETWEEN operator to display rows based on Use the BETWEEN operator to display rows based on a range of values. a range of values. SQL> SELECT ename, sal 2 FROM emp 3 WHERE sal BETWEEN 1000 AND 1500; ENAME SAL ---------- --------- Lower Higher MARTIN 1250 limit limit TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300Copyright © 2004, Oracle. All rights reserved.
  • 41. Using the IN Operator Use the IN operator to test for values in a list. Use the IN operator to test for values in a list. SQL> SELECT empno, ename, sal, mgr 2 FROM emp 3 WHERE mgr IN (7902, 7566, 7788); EMPNO ENAME SAL MGR --------- ---------- --------- --------- 7902 FORD 3000 7566 7369 SMITH 800 7902 7788 SCOTT 3000 7566 7876 ADAMS 1100 7788Copyright © 2004, Oracle. All rights reserved.
  • 42. Using the IN Operator with Strings Use the IN operator to test for values in a list of Use the IN operator to test for values in a list of strings. strings. SQL> SELECT ename, deptno, hiredate 2 FROM emp 3 WHERE ename IN (BLAKE,MARTIN); ENAME DEPTNO HIREDATE ---------- --------- --------- BLAKE 30 01-MAY-81 MARTIN 30 28-SEP-81Copyright © 2004, Oracle. All rights reserved.
  • 43. Using the LIKE Operator – – Use the LIKE operator to perform wildcard searches of Use the LIKE operator to perform wildcard searches of valid search string values. valid search string values. – – Search conditions can contain either literal characters Search conditions can contain either literal characters or numbers. or numbers. % denotes zero or many characters % denotes zero or many characters _ denotes one character _ denotes one character SQL> SELECT ename 2 FROM emp 3 WHERE ename LIKE S%;Copyright © 2004, Oracle. All rights reserved.
  • 44. Using the LIKE Operator • You can combine pattern matching • You can combine pattern matching characters. characters. SQL> SELECT ename 2 FROM emp 3 WHERE ename LIKE _A%; ENAME ---------- MARTIN JAMES WARD • Use the ESCAPE identifier to search for • Use the ESCAPE identifier to search for % or _. % or _.Copyright © 2004, Oracle. All rights reserved.
  • 45. Using the IS NULL Operator Test for null values with the IS NULL operator. Test for null values with the IS NULL operator. SQL> SELECT ename, mgr 2 FROM emp 3 WHERE mgr IS NULL; ENAME MGR ---------- --------- KINGCopyright © 2004, Oracle. All rights reserved.
  • 46. Logical Operators Operator Meaning AND Returns TRUE if both component conditions are TRUE OR Returns TRUE if either component condition is TRUE NOT Returns TRUE if the following condition is FALSECopyright © 2004, Oracle. All rights reserved.
  • 47. Using the AND Operator AND requires both conditions to be TRUE. AND requires both conditions to be TRUE. SQL> SELECT empno, ename, job, sal 2 FROM emp 3 WHERE sal>=1100 4 AND job=CLERK; EMPNO ENAME JOB SAL --------- ---------- --------- --------- 7876 ADAMS CLERK 1100 7934 MILLER CLERK 1300Copyright © 2004, Oracle. All rights reserved.
  • 48. Using the AND Operator AND requires both conditions to be TRUE. AND requires both conditions to be TRUE. SQL> SELECT ename, mgr, sal,deptno 2 FROM emp 3 WHERE sal>1000 4 AND deptno = 10; ENAME MGR SAL DEPTNO ---------- --------- --------- --------- KING 5000 10 CLARK 7839 2450 10 MILLER 7782 1300 10Copyright © 2004, Oracle. All rights reserved.
  • 49. Using the OR Operator OR requires either condition to be TRUE. OR requires either condition to be TRUE. SQL> SELECT empno, ename, job, sal 2 FROM emp 3 WHERE sal>=2000 4 OR job=CLERK; EMPNO ENAME JOB SAL --------- ---------- --------- --------- 7839 KING PRESIDENT 5000 7698 BLAKE MANAGER 2850 7782 CLARK MANAGER 2450 7566 JONES MANAGER 2975 7900 JAMES CLERK 950 7902 FORD ANALYST 3000 ... 10 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 50. Using the OR Operator OR requires either condition to be TRUE. OR requires either condition to be TRUE. SQL> SELECT ename, deptno, mgr 2 FROM emp 3 WHERE deptno = 10 4 OR mgr = 7839; ENAME DEPTNO MGR ---------- -------- --------- KING 10 BLAKE 30 7839 CLARK 10 7839 JONES 20 7839 MILLER 10 7782Copyright © 2004, Oracle. All rights reserved.
  • 51. Using the NOT Operator SQL> SELECT ename, job 2 FROM emp 3 WHERE job NOT IN (CLERK,MANAGER,ANALYST); ENAME JOB ---------- --------- KING PRESIDENT MARTIN SALESMAN ALLEN SALESMAN TURNER SALESMAN WARD SALESMANCopyright © 2004, Oracle. All rights reserved.
  • 52. Using the NOT Operator SQL> SELECT empno,ename,deptno,mgr 2 FROM emp 3 WHERE mgr NOT LIKE 78%; EMPNO ENAME DEPTNO MGR --------- ---------- --------- --------- 7654 MARTIN 30 7698 7499 ALLEN 30 7698 ... ... 7902 FORD 20 7566 7369 SMITH 20 7902 ... 10 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 53. Using the NOT Operator SQL> SELECT empno, sal, mgr 2 FROM emp 3 WHERE sal NOT BETWEEN 1000 AND 1500; EMPNO SAL MGR --------- --------- --------- 7839 5000 7698 2850 7839 7782 2450 7839 7566 2975 7839 7499 1600 7698 7900 950 7698 7902 3000 7566 7369 800 7902 7788 3000 7566 9 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 54. Using the NOT Operator SQL> SELECT ename, sal AS "Salary Before Commission", 2 comm 3 FROM emp 4 WHERE comm IS NOT NULL; ENAME Salary Before Commission COMM ---------- ------------------------ --------- MARTIN 1250 1400 ALLEN 1600 300 TURNER 1500 0 WARD 1250 500Copyright © 2004, Oracle. All rights reserved.
  • 55. Rules of Precedence Order Evaluated Operator 1 All comparison operators 2 NOT 3 AND 4 OR Use parentheses to override rules of precedence. Use parentheses to override rules of precedence.Copyright © 2004, Oracle. All rights reserved.
  • 56. Rules of Precedence SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE job=SALESMAN 4 OR job=PRESIDENT 5 AND sal>1500; ENAME JOB SAL ---------- ------- --------- KING PRESIDENT 5000 MARTIN SALESMAN 1250 ALLEN SALESMAN 1600 TURNER SALESMAN 1500 WARD SALESMAN 1250Copyright © 2004, Oracle. All rights reserved.
  • 57. Rules of Precedence Use parentheses to force priority. Use parentheses to force priority. SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE (job=SALESMAN 4 OR job=PRESIDENT) 5 AND sal>1500; ENAME JOB SAL ---------- --------- --------- KING PRESIDENT 5000 ALLEN SALESMAN 1600Copyright © 2004, Oracle. All rights reserved.
  • 58. ORDER BY Clause – – Sort rows with the ORDER BY clause: Sort rows with the ORDER BY clause: ASC: ascending order, default ASC: ascending order, default DESC: descending order DESC: descending order – – The ORDER BY clause comes last in the SELECT The ORDER BY clause comes last in the SELECT statement. statement. SQL> SELECT ename, job, deptno 2 FROM emp 3 ORDER BY deptno; ENAME JOB DEPTNO ---------- --------- --------- KING PRESIDENT 10 CLARK MANAGER 10 ... JONES MANAGER 20 SCOTT ANALYST 20 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 59. Sorting in Descending Order SQL> SELECT ename, job, deptno, sal 2 FROM emp 3 ORDER BY sal DESC; ENAME JOB DEPTNO SAL ---------- --------- --------- --------- KING PRESIDENT 10 5000 FORD ANALYST 20 3000 SCOTT ANALYST 20 3000 JONES MANAGER 20 2975 BLAKE MANAGER 30 2850 CLARK MANAGER 10 2450 ALLEN SALESMAN 30 1600 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 60. Sorting by Column Alias SQL> SELECT empno, ename, sal*12 annsal 2 FROM emp 3 ORDER BY annsal; EMPNO ENAME ANNSAL --------- ---------- --------- 7369 SMITH 9600 7900 JAMES 11400 7876 ADAMS 13200 7654 MARTIN 15000 7521 WARD 15000 7934 MILLER 15600 7844 TURNER 18000 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 61. Sorting by Multiple Columns The order of an ORDER BY list is the order of the The order of an ORDER BY list is the order of the sort. sort. SQL> SELECT ename, deptno, sal 2 FROM emp 3 ORDER BY deptno, sal DESC; ENAME DEPTNO SAL ---------- --------- --------- KING 10 5000 CLARK 10 2450 MILLER 10 1300 FORD 20 3000 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 62. Sorting by a Column Not in the SELECT List SQL> SELECT ename, deptno 2 FROM emp 3 ORDER BY sal; ENAME DEPTNO ---------- --------- SMITH 20 JAMES 30 ADAMS 20 MARTIN 30 WARD 30 MILLER 10 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 63. Single-Row Number and Character FunctionsCopyright © 2004, Oracle. All rights reserved.
  • 64. How a Function Works Input Function Output Performs operationCopyright © 2004, Oracle. All rights reserved.
  • 65. Two Types of SQL Functions Functions Single-row Multiple-row functions functionsCopyright © 2004, Oracle. All rights reserved.
  • 66. Single-Row Functions – – Manipulate data items Manipulate data items – – Accept arguments and return one value Accept arguments and return one value – – Act on each row returned Act on each row returned – – Return one result per row Return one result per row – – Can modify the data type Can modify the data type – – Can be nested Can be nestedCopyright © 2004, Oracle. All rights reserved.
  • 67. Single-Row Functions Character Number Single-row functions Conversion DateCopyright © 2004, Oracle. All rights reserved.
  • 68. Character Functions Character functions Case conversion Character manipulation functions functions LOWER UPPER INITCAPCopyright © 2004, Oracle. All rights reserved.
  • 69. Case Conversion Functions Convert the case for character strings Convert the case for character strings Function Result LOWER(SQL Course) sql course UPPER(SQL Course) SQL COURSE INITCAP(SQL Course) Sql CourseCopyright © 2004, Oracle. All rights reserved.
  • 70. Using Case Conversion Functions Display the employee number, name, and department Display the employee number, name, and department number for employee Blake. number for employee Blake. SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE ename = blake; no rows selected SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE ename = UPPER(blake); EMPNO ENAME DEPTNO --------- ---------- --------- 7698 BLAKE 30Copyright © 2004, Oracle. All rights reserved.
  • 71. Using Case Conversion Functions Display the employee name for all employees with an Display the employee name for all employees with an initial capital. initial capital. SQL> SELECT INITCAP(ename) as EMPLOYEE 2 FROM emp; EMPLOYEE ---------- King Blake Clark Jones Martin ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 72. Number Functions – – ROUND: Rounds value to specified decimal ROUND: Rounds value to specified decimal ROUND(45.926, 2) ROUND(45.926, 2) 45.93 45.93 – – TRUNC: Truncates value to specified decimal TRUNC: Truncates value to specified decimal TRUNC(45.926, 2) TRUNC(45.926, 2) 45.92 45.92 – – MOD: Returns remainder of division MOD: Returns remainder of division MOD(1600, 300) MOD(1600, 300) 100 100Copyright © 2004, Oracle. All rights reserved.
  • 73. Defining a Null Value – – A null is a value that is unavailable, unassigned, A null is a value that is unavailable, unassigned, unknown, or inapplicable. unknown, or inapplicable. – – A null is not the same as zero or a blank space. A null is not the same as zero or a blank space. SQL> SELECT ename, job, comm 2 FROM emp; ENAME JOB COMM ---------- --------- --------- KING PRESIDENT BLAKE MANAGER ... TURNER SALESMAN 0 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 74. Null Values in Arithmetic Expressions Arithmetic expressions that contain a null value Arithmetic expressions that contain a null value evaluate to null. evaluate to null. SQL> SELECT ename NAME, 12*sal+comm 2 FROM emp; NAME 12*SAL+COMM ---------- ----------- KING BLAKE CLARK JONES MARTIN 16400 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 75. Using the NVL Function NVL (expr1, expr2) Use the NVL function to force a value where a null Use the NVL function to force a value where a null would otherwise appear: would otherwise appear: – – NVL can be used with date, character, and number NVL can be used with date, character, and number data types. data types. – – Data types must match. For example: Data types must match. For example: NVL(comm,0) NVL(comm,0) NVL(hiredate,01-JAN-97) NVL(hiredate,01-JAN-97) NVL(job,no job yet) NVL(job,no job yet yet)Copyright © 2004, Oracle. All rights reserved.
  • 76. Using the NVL Function to Handle Null Values SQL> SELECT ename, job, sal * 12 + NVL(comm,0) 2 FROM emp; ENAME JOB SAL*12+NVL(COMM,0) ---------- --------- ------------------ KING PRESIDENT 60000 BLAKE MANAGER 34200 CLARK MANAGER 29400 JONES MANAGER 35700 MARTIN SALESMAN 16400 ALLEN SALESMAN 19500 TURNER SALESMAN 18000 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 77. Single-Row Date and Conversion FunctionsCopyright © 2004, Oracle. All rights reserved.
  • 78. Single-Row Functions Character Number Single-row functions Conversion DateCopyright © 2004, Oracle. All rights reserved.
  • 79. Working with Dates – – Oracle stores dates in an internal 7 byte numeric format: Oracle stores dates in an internal 7 byte numeric format: century, year, month, day, hours, minutes, seconds. century, year, month, day, hours, minutes, seconds. – – The default date format is DD-MON-YY. The default date format is DD-MON-YY.Copyright © 2004, Oracle. All rights reserved.
  • 80. SYSDATE – – Use SYSDATE to display the current date and time. Use SYSDATE to display the current date and time. – – DUAL is a one-column, one-row table that is used as a DUAL is a one-column, one-row table that is used as a dummy table. dummy table. SQL> SELECT SYSDATE 2 FROM DUAL; SYSDATE --------- 26-JAN-98Copyright © 2004, Oracle. All rights reserved.
  • 81. Default Date Formats Columns that are defined as DATE are Columns that are defined as DATE are displayed as DD-MON-YY by default. displayed as DD-MON-YY by default. SQL> SELECT ename, hiredate 2 FROM emp 3 WHERE ename=SMITH; ENAME HIREDATE ---------- --------- SMITH 17-DEC-80Copyright © 2004, Oracle. All rights reserved.
  • 82. Arithmetic with Dates – – Add or subtract a number to or from a date to obtain a date Add or subtract a number to or from a date to obtain a date value value – – Subtract two dates to find the number of days between Subtract two dates to find the number of days between those dates those datesCopyright © 2004, Oracle. All rights reserved.
  • 83. Using Arithmetic Operators with Dates SQL> SELECT ename, hiredate, hiredate+30 "NEW DATE" 2 FROM emp 3 WHERE ename=SMITH; ENAME HIREDATE NEW DATE ---------- --------- --------- SMITH 17-DEC-80 16-JAN-81Copyright © 2004, Oracle. All rights reserved.
  • 84. Using SYSDATE in Calculations Determine for how many weeks employees have Determine for how many weeks employees have worked worked SQL> SELECT ename, (SYSDATE-hiredate)/7 2 "WEEKS AT WORK" 3 FROM emp 4 WHERE deptno=10; ENAME WEEKS AT WORK ---------- ------------- KING 844.94617 CLARK 867.94617 MILLER 835.37474Copyright © 2004, Oracle. All rights reserved.
  • 85. Explicit Data Type Conversion TO_NUMBER TO_DATE NUMBER CHARACTER DATE TO_CHAR TO_CHARCopyright © 2004, Oracle. All rights reserved.
  • 86. Modifying the Display Format of Dates Tuesday the 27th of January, 1998 27-JAN-98 January 27, 1998 01/27/98Copyright © 2004, Oracle. All rights reserved.
  • 87. TO_CHAR Function with Dates TO_CHAR(date, fmfmt) The format model: The format model: – – Is case sensitive and must be enclosed in single Is case sensitive and must be enclosed in single quotation marks quotation marks – – Can include any valid date format element Can include any valid date format element – – Has an fm element to remove padded blanks or Has an fm element to remove padded blanks or suppress leading zeros suppress leading zeros – – Is separated from the date value by a comma Is separated from the date value by a commaCopyright © 2004, Oracle. All rights reserved.
  • 88. Date Format Model Elements YYYY Full year in numbers YEAR Year spelled out MM 2-digit value for month MONTH Full name of the month 3-letter abbreviation of the day DY of the week DAY Full name of the dayCopyright © 2004, Oracle. All rights reserved.
  • 89. Using the TO_CHAR Function with Dates SQL> SELECT ename, TO_CHAR(hiredate, Month DDth, YYYY) 2 AS HIREDATE 3 FROM emp 4 WHERE job=MANAGER; ENAME HIREDATE ---------- -------------------- BLAKE May 01st, 1981 CLARK June 09th, 1981 JONES April 02nd, 1981Copyright © 2004, Oracle. All rights reserved.
  • 90. Using the TO_CHAR Function with Dates SQL> SELECT empno, TO_CHAR(hiredate, MM/YY) AS MONTH 2 FROM emp 3 WHERE ename=BLAKE; EMPNO MONTH --------- ----- 7698 05/81Copyright © 2004, Oracle. All rights reserved.
  • 91. Using the TO_CHAR Function with Dates SQL> SELECT ename, 2 TO_CHAR(hiredate, fmDD Month YYYY) AS HIREDATE 3 FROM emp; ENAME HIREDATE ---------- ----------------- KING 17 November 1981 BLAKE 1 May 1981 CLARK 9 June 1981 JONES 2 April 1981 MARTIN 28 September 1981 ALLEN 20 February 1981 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 92. Using the TO_CHAR Function with DatesSQL> SELECT ename, mgr, sal,TO_CHAR(hiredate,YYYY-MON-DD) 2 AS HIREDATE 3 FROM emp 4 WHERE sal<1000 5 AND hiredate like %80; ENAME MGR SAL HIREDATE ---------- --------- --------- ----------- SMITH 7902 800 1980-DEC-17 Copyright © 2004, Oracle. All rights reserved.
  • 93. Using the TO_CHAR Function with DatesSQL> SELECT empno,ename,deptno,TO_CHAR(hiredate,MM-DD-YYYY) 2 AS HIREDATE 3 FROM emp 4 WHERE hiredate NOT LIKE %81; EMPNO ENAME DEPTNO HIREDATE -------- ---------- --------- ----------- 7369 SMITH 20 12-17-1980 7788 SCOTT 20 12-09-1982 7876 ADAMS 20 01-12-1983 7934 MILLER 10 01-23-1982 Copyright © 2004, Oracle. All rights reserved.
  • 94. Using the TO_CHAR Function with Dates SQL> SELECT ename, job, deptno, 2 TO_CHAR(hiredate,DD-MON-YYYY) AS HIRE_DATE 3 FROM emp 4 ORDER BY hiredate DESC; ENAME JOB DEPTNO HIRE_DATE ---------- --------- --------- ----------- ADAMS CLERK 20 12-JAN-1983 SCOTT ANALYST 20 09-DEC-1982 MILLER CLERK 10 23-JAN-1982 JAMES CLERK 30 03-DEC-1981 FORD ANALYST 20 03-DEC-1981 KING PRESIDENT 10 17-NOV-1981 MARTIN SALESMAN 30 28-SEP-1981 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 95. Date Format Model Elements • Time elements format the time portion of the date. Time elements format the time portion of the date. HH24:MI:SS AM 15:45:32 PM DD "of" MONTH 12 of OCTOBER ddspth fourteenthCopyright © 2004, Oracle. All rights reserved.
  • 96. Using Format Models to Display Time SQL> SELECT TO_CHAR(SYSDATE,HH24:MI:SS) TIME 2 FROM DUAL; TIME -------- 13:55:46Copyright © 2004, Oracle. All rights reserved.
  • 97. TO_CHAR Function with Numbers TO_CHAR(n,fmt) Use these formats with the TO_CHAR function to Use these formats with the TO_CHAR function to display a number value as a character: display a number value as a character: 9 Represents a number 0 Forces a zero to be displayed $ Places a floating dollar sign L Uses the floating local currency symbol . Prints a decimal point , Places a thousand indicator Copyright © 2004, Oracle. All rights reserved.
  • 98. Using the TO_CHAR Function with Numbers SQL> SELECT TO_CHAR(sal,$99,999) SALARY 2 FROM emp 3 WHERE ename = SCOTT; SALARY -------- $3,000 Thousand indicator Dollar signCopyright © 2004, Oracle. All rights reserved.
  • 99. Using the TO_NUMBER and TO_DATE Functions – – Convert a character string to a number data type using the Convert a character string to a number data type using the TO_NUMBER function TO_NUMBER function TO_NUMBER(char) • Convert a character string to a date data • Convert a character string to a date data type using the TO_DATE function type using the TO_DATE function TO_DATE(char[, fmt])Copyright © 2004, Oracle. All rights reserved.
  • 100. Using the TO_NUMBER Function SQL> SELECT TO_NUMBER(1000)+sal AS NEW_SALARY 2 FROM emp 3 WHERE ename = SCOTT; NEW_SALARY ---------- 4000Copyright © 2004, Oracle. All rights reserved.
  • 101. Date Functions FUNCTION DESCRIPTION MONTHS_BETWEEN Number of months between two dates ADD_MONTHS Adds calendar months to date NEXT_DAY Next day following the date specified LAST_DAY Last day of the month ROUND Round off date TRUNC Truncate dateCopyright © 2004, Oracle. All rights reserved.
  • 102. Using Date Functions Use the ADD_MONTHS function to add months to Use the ADD_MONTHS function to add months to a date. a date. SQL> SELECT ename, hiredate, ADD_MONTHS(hiredate, 6) 2 AS "+6 MONTHS" 3 FROM emp 4 WHERE ename=BLAKE; ENAME HIREDATE +6 MONTHS ---------- --------- --------- BLAKE 01-MAY-81 01-NOV-81Copyright © 2004, Oracle. All rights reserved.
  • 103. Nesting Functions – – Single-row functions can be nested to any level. Single-row functions can be nested to any level. – – Nested functions are evaluated from the innermost level to Nested functions are evaluated from the innermost level to the outermost level. the outermost level. F3(F2(F1(col,arg1),arg2),arg3) Step 1 = Result 1 Step 2 = Result 2 Step 3 = Result 3Copyright © 2004, Oracle. All rights reserved.
  • 104. Nesting Functions Result 2 Result 1 SQL> SELECT ename, 2 NVL(TO_CHAR(mgr),No Manager) 3 FROM emp 4 WHERE mgr IS NULL; ENAME NVL(TO_CHAR(MGR),NOMANAGER) ---------- ----------------------------- KING No ManagerCopyright © 2004, Oracle. All rights reserved.
  • 105. Nesting Functions SQL> SELECT MONTHS_BETWEEN 2 (TO_DATE(02-02-1995,MM-DD-YYYY), 3 TO_DATE(01-01-1995,MM-DD-YYYY)) 4 "Months" 5 FROM DUAL; Months ---------- 1.03225806Copyright © 2004, Oracle. All rights reserved.
  • 106. Displaying Data from Multiple TablesCopyright © 2004, Oracle. All rights reserved.
  • 107. Obtaining Data from Multiple TablesObtaining Data from Multiple Tables EMP DEPT EMPNO ENAME ... DEPTNO DEPTNO DNAME LOC ------ ----- ... ------ ------ ---------- -------- 7839 KING ... 10 10 ACCOUNTING NEW YORK 7698 BLAKE ... 30 20 RESEARCH DALLAS ... 30 SALES CHICAGO 7934 MILLER ... 10 40 OPERATIONS BOSTON EMPNO DEPTNO LOC ----- ------- -------- 7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO Copyright © 2004, Oracle. All rights reserved.
  • 108. Joining Tables Use a join to query data from more than one table: Use a join to query data from more than one table: SELECT table1.column1, table2.column2 FROM table1, table2 WHERE Write the join condition in the WHERE clause. table1.column1 = table2.column2; – Write the join condition in the WHERE clause. – – – Prefix the column name with the table name when the Prefix the column name with the table name when the same column name appears in more than one table. same column name appears in more than one table.Copyright © 2004, Oracle. All rights reserved.
  • 109. Types of Joins Equijoin Nonequijoin Self join Equijoin Nonequijoin Self joinCopyright © 2004, Oracle. All rights reserved.
  • 110. What Is an Equijoin? EMP EMPNO ENAME DEPTNO ------ ------- ------- ... DEPT 7782 CLARK 10 DEPTNO DNAME LOC ------- ---------- -------- ... 10 ACCOUNTING NEW YORK ... Links rows that satisfy a specified condition WHERE emp.deptno=dept.deptnoCopyright © 2004, Oracle. All rights reserved.
  • 111. Equijoin EMP DEPT EMPNO ENAME DEPTNO DEPTNO DNAME LOC ------ ------- ------- ------- ---------- -------- 7839 KING 10 10 ACCOUNTING NEW YORK 7698 BLAKE 30 30 SALES CHICAGO 7782 CLARK 10 10 ACCOUNTING NEW YORK 7566 JONES 20 20 RESEARCH DALLAS 7654 MARTIN 30 30 SALES CHICAGO 7499 ALLEN 30 30 SALES CHICAGO 7844 TURNER 30 30 SALES CHICAGO 7900 JAMES 30 30 SALES CHICAGO 7521 WARD 30 30 SALES CHICAGO 7902 FORD 20 20 RESEARCH DALLAS 7369 SMITH 20 20 RESEARCH DALLAS ... ... 14 rows selected. 14 rows selected. Foreign key Primary keyCopyright © 2004, Oracle. All rights reserved.
  • 112. Retrieving Records with an Equijoin SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno; EMPNO ENAME DEPTNO DEPTNO LOC ----- ------ ------ ------ --------- 7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 113. Qualifying Ambiguous Column Names – – Use table prefixes to qualify column names that are in Use table prefixes to qualify column names that are in multiple tables. multiple tables. – – Use table prefixes to improve performance. Use table prefixes to improve performance.Copyright © 2004, Oracle. All rights reserved.
  • 114. Additional Search Conditions Using the AND Operator EMP DEPT EMPNO ENAME DEPTNO DEPTNO DNAME LOC ------ ------- ------- ------ --------- -------- 7839 KING 10 10 ACCOUNTING NEW YORK 7698 BLAKE 30 30 SALES CHICAGO 7782 CLARK 10 10 ACCOUNTING NEW YORK 7566 JONES 20 20 RESEARCH DALLAS 7654 MARTIN 30 30 SALES CHICAGO 7499 ALLEN 30 30 SALES CHICAGO 7844 TURNER 30 30 SALES CHICAGO 7900 JAMES 30 30 SALES CHICAGO ... ... 14 rows selected. 14 rows selected. WHERE emp.deptno=dept.deptno AND ename=KINGCopyright © 2004, Oracle. All rights reserved.
  • 115. Using Additional Search Conditions with a Join SQL> SELECT emp.empno, emp.ename, emp.deptno, dept.loc 2 FROM emp, dept; 3 WHERE emp.deptno = dept.deptno 4 AND emp.ename = KING; EMPNO ENAME DEPTNO LOC --------- ---------- --------- ------------- 7839 KING 10 NEW YORKCopyright © 2004, Oracle. All rights reserved.
  • 116. Using Additional Search Conditions with a Join SQL> SELECT emp.ename, emp.job, dept.deptno, dept.dname 2 FROM emp, dept 3 WHERE emp.deptno=dept.deptno 4 AND emp.job IN (MANAGER,PRESIDENT); ENAME JOB DEPTNO DNAME ---------- --------- --------- -------------- KING PRESIDENT 10 ACCOUNTING BLAKE MANAGER 30 SALES CLARK MANAGER 10 ACCOUNTING JONES MANAGER 20 RESEARCHCopyright © 2004, Oracle. All rights reserved.
  • 117. Table Aliases Simplify queries by using table aliases. Simplify queries by using table aliases. SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno; … can be written as ... … can be written as ... SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno=d.deptno;Copyright © 2004, Oracle. All rights reserved.
  • 118. Using Table Aliases SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno=d.deptno; EMPNO ENAME DEPTNO DEPTNO LOC --------- ---------- --------- --------- ----------- 7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS 7654 MARTIN 30 30 CHICAGO 7499 ALLEN 30 30 CHICAGO ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 119. Nonequijoins EMP SALGRADE EMPNO ENAME SAL GRADE LOSAL HISAL ------ ------- ------ ----- ----- ------ 7839 KING 5000 1 700 1200 7698 BLAKE 2850 2 1201 1400 7782 CLARK 2450 3 1401 2000 7566 JONES 2975 4 2001 3000 7654 MARTIN 1250 5 3001 9999 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 ... Salary in the EMP 14 rows selected. table is between low salary and high salary in the SALGRADE table.Copyright © 2004, Oracle. All rights reserved.
  • 120. Retrieving Records with Nonequijoins SQL> SELECT e.ename, e.sal, s.grade 2 FROM emp e, salgrade s 3 WHERE e.sal 4 BETWEEN s.losal AND s.hisal; ENAME SAL GRADE ---------- --------- --------- JAMES 950 1 SMITH 800 1 ADAMS 1100 1 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 121. Joining More Than Two Tables EMP DEPT ENAME SAL DEPTNO DEPTNO DNAME ---------- --------- --------- --------- ---------- JAMES 950 30 10 ACCOUNTING SMITH 800 20 20 RESEARCH ADAMS 1100 20 30 SALES MARTIN 1250 30 40 OPERATIONS WARD 1250 30 MILLER 1300 10 … SALGRADE 14 rows selected. LOSAL HISAL GRADE --------- --------- --------- 700 1200 1WHERE emp.sal BETWEEN 1201 1400 2salgrade.losal AND 1401 2000 3salgrade.hisal 2001 3000 4AND emp.deptno = dept.deptno 3001 9999 5Copyright © 2004, Oracle. All rights reserved.
  • 122. Using Multiple Joins SQL> SELECT e.ename, e.deptno, d.dname, e.sal, s.grade 2 FROM emp e, dept d, salgrade s 3 WHERE e.deptno=d.deptno 4 AND e.sal BETWEEN s.losal and s.hisal; ENAME DEPTNO DNAME SAL GRADE ---------- --------- -------------- --------- --------- JAMES 30 SALES 950 1 SMITH 20 RESEARCH 800 1 ADAMS 20 RESEARCH 1100 1 MARTIN 30 SALES 1250 2 WARD 30 SALES 1250 2 MILLER 10 ACCOUNTING 1300 2 ALLEN 30 SALES 1600 3 ... 14 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 123. Selfjoins EMP (WORKER) EMP (MANAGER) EMPNO ENAME MGR EMPNO ENAME ----- ------ ---- ----- -------- 7839 KING 7698 BLAKE 7839 7839 KING 7782 CLARK 7839 7839 KING 7566 JONES 7839 7839 KING 7654 MARTIN 7698 7698 BLAKE 7499 ALLEN 7698 7698 BLAKE MGR in the WORKER table is equal to EMPNO in the MANAGER table.Copyright © 2004, Oracle. All rights reserved.
  • 124. Joining a Table to Itself SQL> SELECT worker.ename|| works for ||manager.ename 2 AS WHO_WORKS_FOR_WHOM 3 FROM emp worker, emp manager 4 WHERE worker.mgr = manager.empno; WHO_WORKS_FOR_WHOM ------------------------------- BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE ... 13 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 125. Aggregating Data by Using Group FunctionsCopyright © 2004, Oracle. All rights reserved.
  • 126. What Are Group Functions? Group functions operate on sets of rows to give one result Group functions operate on sets of rows to give one result per group. per group. EMP DEPTNO SAL --------- --------- 10 2450 10 5000 10 1300 20 800 20 1100 20 3000 maximum MAX(SAL) 20 3000 salary in --------- 20 2975 the EMP table 5000 30 1600 30 2850 30 1250 30 950 30 1500 30 1250Copyright © 2004, Oracle. All rights reserved.
  • 127. Types of Group Functions – – AVG AVG – – COUNT COUNT – – MAX MAX – – MIN MIN – – SUM SUMCopyright © 2004, Oracle. All rights reserved.
  • 128. Guidelines for Using Group Functions Many aggregate functions accept these Many aggregate functions accept these options: options: – DISTINCT – DISTINCT – ALL – ALL – NVL – NVLCopyright © 2004, Oracle. All rights reserved.
  • 129. Using the AVG and SUM Functions You can use AVG and SUM for numeric data. You can use AVG and SUM for numeric data. SQL> SELECT AVG(sal), SUM(sal) 2 FROM emp 3 WHERE job LIKE SALES%; AVG(SAL) SUM(SAL) -------- --------- 1400 5600Copyright © 2004, Oracle. All rights reserved.
  • 130. Using the MIN and MAX Functions You can use MIN and MAX for any data type. You can use MIN and MAX for any data type. SQL> SELECT TO_CHAR(MIN(hiredate),DD-MON-YYYY), 2 TO_CHAR(MAX(hiredate),DD-MON-YYYY) 3 FROM emp; T0_CHAR(MIN TO_CHAR(MAX --------- --------- 17-DEC-1980 12-JAN-1983Copyright © 2004, Oracle. All rights reserved.
  • 131. Using the MIN and MAX Functions You can use MIN and MAX for any data type. You can use MIN and MAX for any data type. SQL> SELECT MIN(sal) AS "Lowest Salary", 2 MAX(sal) AS "Highest Salary" 3 FROM emp; Lowest Salary Highest Salary ------------- -------------- 800 5000Copyright © 2004, Oracle. All rights reserved.
  • 132. Using the COUNT Function COUNT(*) returns the number of rows in a query. COUNT(*) returns the number of rows in a query. SQL> SELECT COUNT(*) 2 FROM emp 3 WHERE deptno = 30; COUNT(*) --------- 6Copyright © 2004, Oracle. All rights reserved.
  • 133. Using the COUNT Function COUNT(expr) returns the number of nonnull rows. COUNT(expr) returns the number of nonnull rows. SQL> SELECT COUNT(comm) 2 FROM emp 3 WHERE deptno = 30; COUNT(COMM) ----------- 4Copyright © 2004, Oracle. All rights reserved.
  • 134. Group Functions and Null Values Group functions ignore null values in the column. Group functions ignore null values in the column. SQL> SELECT AVG(comm) 2 FROM emp; AVG(COMM) --------- 550Copyright © 2004, Oracle. All rights reserved.
  • 135. Using the NVL Function with Group Functions The NVL function forces group functions to include The NVL function forces group functions to include null values. null values. SQL> SELECT AVG(NVL(comm,0)) 2 FROM emp; AVG(NVL(COMM,0)) ---------------- 157.14286Copyright © 2004, Oracle. All rights reserved.
  • 136. Using the NVL Function with Group Functions Average commission for all people hired in 1981 Average commission for all people hired in 1981 SQL> SELECT AVG(NVL(comm,0)) 2 FROM emp 3 WHERE hiredate 4 BETWEEN TO_DATE(01-JAN-1981,DD-MON-YYYY) 5 AND TO_DATE(31-DEC-1981,DD-MON-YYYY); AVG(NVL(COMM,0)) ---------------- 220Copyright © 2004, Oracle. All rights reserved.
  • 137. Creating Groups of Data EMP DEPTNO SAL --------- --------- 10 2450 10 5000 2916.6667 10 1300 20 800 average DEPTNO AVG(SAL) 20 1100 salary ------- --------- 20 3000 2175 in EMP 10 2916.6667 20 3000 table 20 2975 for each 20 2175 30 1600 department 30 1566.6667 30 2850 30 1250 1566.6667 30 950 30 1500 30 1250Copyright © 2004, Oracle. All rights reserved.
  • 138. Creating Groups of Data: GROUP BY Clause Use the GROUP BY clause to divide rows in a table Use the GROUP BY clause to divide rows in a table into smaller groups. into smaller groups. SELECT column, group_function FROM table [WHERE condition] [GROUP BY group_by_expression] [ORDER BY column];Copyright © 2004, Oracle. All rights reserved.
  • 139. Using the GROUP BY Clause All columns in the SELECT list that are not in group All columns in the SELECT list that are not in group functions must be in the GROUP BY clause. functions must be in the GROUP BY clause. SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 GROUP BY deptno; DEPTNO AVG(SAL) --------- --------- 10 2916.6667 20 2175 30 1566.6667Copyright © 2004, Oracle. All rights reserved.
  • 140. Using the GROUP BY Clause The GROUP BY column does not have to be in the The GROUP BY column does not have to be in the SELECT list. SELECT list. SQL> SELECT AVG(sal) 2 FROM emp 3 GROUP BY deptno; AVG(SAL) --------- 2916.6667 2175 1566.6667Copyright © 2004, Oracle. All rights reserved.
  • 141. Using the GROUP BY Clause Display the number of people in each department. Display the number of people in each department. SQL> SELECT deptno, COUNT(*) AS "Dept Employees" 2 FROM emp 3 GROUP BY deptno; DEPTNO Dept Employees --------- -------------- 10 3 20 5 30 6Copyright © 2004, Oracle. All rights reserved.
  • 142. Using a Group Function in the ORDER BY Clause SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 GROUP BY deptno 4 ORDER BY AVG(sal); DEPTNO AVG(SAL) ---------- ------------ 30 1566.6667 20 2175 10 2916.6667Copyright © 2004, Oracle. All rights reserved.
  • 143. Illegal QueriesUsing Group Functions Any column or expression in the SELECT list that is Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY not an aggregate function must be in the GROUP BY clause. clause. usse e lla u ca Yc BY PB UP SQL> SELECT deptno, COUNT(ename) SQL> SELECT deptno, COUNT(ename) OU RO 2 FROM 2 FROM emp; emp; eG GR tth e h n in SELECT deptno, COUNT(ename) g i SELECT deptno, COUNT(ename) g * * iis s siin sn ERROR at line 1: m ERROR at line 1: nm n ORA-00937: not a single-group group function um llu m ORA-00937: not a single-group group function Co CoCopyright © 2004, Oracle. All rights reserved.
  • 144. Using Set OperatorsCopyright © 2004, Oracle. All rights reserved.
  • 145. The Set Operators A B Intersect A B A B Union / Union All A B MinusCopyright © 2004, Oracle. All rights reserved.
  • 146. Tables Used in This LessonEMP EMPNO ENAME EMPNO ENAME JOB JOB MGR HIREDATE MGR HIREDATE SAL SAL COMM COMMDEPTNODEPTNO--------- ---------- --------- --------- --------- ------------------ ---------- --------- --------- --------- --------- --------- -------- --------- ---------- 7839 KING 7839 KING PRESIDENT PRESIDENT 17-NOV-81 17-NOV-81 5000 50001010 7698 BLAKE 7698 BLAKE MANAGER MANAGER 7839 01-MAY-81 7839 01-MAY-81 2850 28503030 7782 CLARK 7782 CLARK MANAGER MANAGER 7839 09-JUN-81 7839 09-JUN-81 1500 15001010 7566 JONES 7566 JONES MANAGER MANAGER 7839 02-APR-81 7839 02-APR-81 2975 29752020 EMPID NAME EMPID NAME TITLE TITLE DATE_OUT DATE_OUT 7654 MARTIN 7654 MARTIN SALESMAN DEPTID 7698 28-SEP-81 SALESMAN DEPTID 7698 28-SEP-81 1250 1250 1400 14003030 --------- -------------------- --------- -------------------- --------- --------- --------- -------- --------- -------- 7499 ALLEN 7499 ALLEN SALESMAN - SALESMAN - 7698 20-FEB-81 7698 20-FEB-81 1600 1600 300 3003030 6087 SPENCER 6087 SPENCER OPERATOR OPERATOR 27-NOV-81 27-NOV-81 7844 TURNER 7844 TURNER SALESMAN 20 SALESMAN 20 7698 08-SEP-81 7698 08-SEP-81 1500 1500 0 03030 6185 VANDYKE 6185 VANDYKE MANAGER MANAGER 17-JAN-81 17-JAN-81 7900 JAMESEMP_HISTORY 10 7900 JAMES CLERK CLERK 10 7698 03-DEC-81 7698 03-DEC-81 950 9503030 6235 BALFORD 6235 BALFORD CLERK CLERK 22-FEB-80 22-FEB-80 7521 WARD 7521 WARD SALESMAN 20 SALESMAN 20 7698 22-FEB-81 7698 22-FEB-81 1250 1250 500 5003030 7788 SCOTT 7788 SCOTT ANALYST ANALYST 05-MAY-81 05-MAY-81 7902 FORD 7902 FORD ANALYST 20 ANALYST 20 7566 03-DEC-81 7566 03-DEC-81 3000 30002020 7001 JEWELL 7001 JEWELL ANALYST ANALYST 10-JUN-81 10-JUN-81 7369 SMITH All rights reserved. Copyright © 2004, SMITH 7369 Oracle. CLERK CLERK 30 30 7902 17-DEC-80 7902 17-DEC-80 800 8002020 7499 ALLEN 7499 ALLEN SALESMAN 01-AUG-80 SALESMAN 01-AUG-80
  • 147. UNION A BCopyright © 2004, Oracle. All rights reserved.
  • 148. Using the UNION Operator Display the name, employee number, and job title of Display the name, employee number, and job title of all employees. Display each employee only once. all employees. Display each employee only once. SQL> SELECT ename, empno, job 2 FROM emp 3 UNION 4 SELECT name, empid, title 5 FROM emp_history; ENAME EMPNO JOB ---------- --------- --------- ADAMS 7876 CLERK ALLEN 7499 SALESMAN BALFORD 6235 CLERK ... 20 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 149. Using the UNION Operator Display the name, job title, and salary of all Display the name, job title, and salary of all employees. employees. SQL> SELECT ename, job, sal 2 FROM emp 3 UNION 4 SELECT name, title, 0 5 FROM emp_history; ENAME JOB SAL ---------- --------- --------- ADAMS CLERK 1100 ALLEN SALESMAN 0 ALLEN SALESMAN 1600 BALFORD CLERK 0 ... 23 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 150. UNION ALL A BCopyright © 2004, Oracle. All rights reserved.
  • 151. Using the UNION ALL Operator Display the names, employee numbers, and job Display the names, employee numbers, and job titles of all employees. titles of all employees. SQL> SELECT ename, empno, job 2 FROM emp 3 UNION ALL 4 SELECT name, empid, title 5 FROM emp_history; ENAME EMPNO JOB ---------- --------- --------- KING 7839 PRESIDENT BLAKE 7698 MANAGER CLARK 7782 MANAGER CLARK 7782 MANAGER ... 23 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 152. INTERSECT A BCopyright © 2004, Oracle. All rights reserved.
  • 153. Using the INTERSECT Operator Display the distinct names, employee numbers, and Display the distinct names, employee numbers, and job titles of employees found in both the EMP and job titles of employees found in both the EMP and EMP_HISTORY tables. EMP_HISTORY tables. SQL> SELECT ename, empno, job 2 FROM emp 3 INTERSECT 4 SELECT name, empid, title 5 FROM emp_history; ENAME ENAME EMPNO JOB EMPNO JOB ---------- --------- --------- ---------- --------- --------- ALLEN ALLEN 7499 SALESMAN 7499 SALESMAN CLARK CLARK 7782 MANAGER 7782 MANAGER SCOTT SCOTT 7788 ANALYST 7788 ANALYSTCopyright © 2004, Oracle. All rights reserved.
  • 154. MINUS A BCopyright © 2004, Oracle. All rights reserved.
  • 155. MINUS Display the names, employee numbers, and Display the names, employee numbers, and job titles for all employees who have left the job titles for all employees who have left the company. company. SQL> SELECT name, empid, title 2 FROM emp_history 3 MINUS 4 SELECT ename, empno, job 5 FROM emp; NAME NAME EMPID EMPID TITLE TITLE ---------- --------- ---------- --------- --------- --------- BALFORD BALFORD 6235 6235 CLERK CLERK BRIGGS BRIGGS 7225 7225 PAY CLERK PAY CLERK ... ... 6 rows selected. 6 rows selected.Copyright © 2004, Oracle. All rights reserved.
  • 156. SET Operator Rules – – The expressions in the SELECT lists must match in The expressions in the SELECT lists must match in number and datatype. number and datatype. – – Duplicate rows are automatically eliminated except in Duplicate rows are automatically eliminated except in UNION ALL. UNION ALL. – – Column names from the first query appear in the result. Column names from the first query appear in the result. – – The output is sorted in ascending order by default The output is sorted in ascending order by default except in UNION ALL. except in UNION ALL. – – Parentheses can be used to alter the sequence of Parentheses can be used to alter the sequence of execution. execution.Copyright © 2004, Oracle. All rights reserved.
  • 157. Matching the SELECT Statement Display the department numbers, Display the department numbers, locations, and hiredates for all employees. locations, and hiredates for all employees. SQL> SELECT deptno, null location, hiredate 2 FROM emp 3 UNION 4 SELECT deptno, loc, TO_DATE(null) 5 FROM dept;Copyright © 2004, Oracle. All rights reserved.
  • 158. Controlling the Order of Rows Produce an English sentence using two Produce an English sentence using two UNION operators. UNION operators. SQL> SQL> COLUMN a_dummy NOPRINT COLUMN a_dummy NOPRINT SQL> SQL> SELECT sing "My dream", 3 a_dummy SELECT sing "My dream", 3 a_dummy 2 2 FROM dual FROM dual 3 3 UNION UNION 4 4 SELECT Id like to teach, 1 SELECT Id like to teach, 1 5 5 FROM dual FROM dual 6 6 UNION UNION 7 7 SELECT the world to, 2 SELECT the world to, 2 8 8 FROM dual FROM dual 9 9 ORDER BY 2; ORDER BY 2; My dream My dream ------------------------- ------------------------- Id like to teach Id like to teach the world to the world to sing singCopyright © 2004, Oracle. All rights reserved.
  • 159. Writing SubqueriesCopyright © 2004, Oracle. All rights reserved.
  • 160. Using a Subquery to Solve a Problem Who has a salary greater than Jones’s? Who has a salary greater than Jones’s? Main Query ? Which employees have a salary greater than Jones’s salary? Subquery ? What is Jones’s salary?Copyright © 2004, Oracle. All rights reserved.
  • 161. Subqueries SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table); – – The subquery (inner query) executes once before the main The subquery (inner query) executes once before the main query. query. – – The result of the subquery is used by the main query (outer The result of the subquery is used by the main query (outer query). query).Copyright © 2004, Oracle. All rights reserved.
  • 162. Using a Subquery “Who has a salary greater than Jones’?” SQL> SELECT ename 2 FROM emp 2975 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE ename=JONES); ENAME ---------- KING FORD SCOTTCopyright © 2004, Oracle. All rights reserved.
  • 163. Guidelines for Using Subqueries – – Enclose subqueries in parentheses. Enclose subqueries in parentheses. – – Place subqueries on the right side of the comparison Place subqueries on the right side of the comparison operator. operator. – – Do not add an ORDER BY clause to a subquery. Do not add an ORDER BY clause to a subquery. – – Use single-row operators with single-row subqueries. Use single-row operators with single-row subqueries.Copyright © 2004, Oracle. All rights reserved.
  • 164. Types of Subqueries – – Single-row subquery Single-row subquery Main query returns Subquery Multiple-row subquery CLERK – – Multiple-row subquery Main query returns CLERK Subquery MANAGERCopyright © 2004, Oracle. All rights reserved.
  • 165. Single-Row Subqueries – – Return only one row Return only one row – – Use single-row comparison operators Use single-row comparison operators Operator Meaning = Equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to <> Not equal toCopyright © 2004, Oracle. All rights reserved.
  • 166. Executing Single-Row Subqueries Who works in the same department as King? SQL> SELECT ename, deptno 2 FROM emp 10 3 WHERE deptno = 4 (SELECT deptno 5 FROM emp 6 WHERE ename=KING); ENAME DEPTNO ---------- --------- KING 10 CLARK 10 MILLER 10Copyright © 2004, Oracle. All rights reserved.
  • 167. Executing Single-Row Subqueries Who has the same manager as Blake? SQL> SELECT ename, mgr 2 FROM emp 7839 3 WHERE mgr = 4 (SELECT mgr 5 FROM emp 6 WHERE ename=BLAKE); ENAME MGR ---------- --------- BLAKE 7839 CLARK 7839 JONES 7839Copyright © 2004, Oracle. All rights reserved.
  • 168. Executing Single-Row Subqueries Who has the same job as employee 7369 and earns a higher salary than employee 7876? SQL> SELECT ename, job 2 FROM emp CLERK 3 WHERE job = 4 (SELECT job 5 FROM emp 6 WHERE empno = 7369) 7 AND sal > 1100 8 (SELECT sal 9 FROM emp 10 WHERE empno = 7876); ENAME JOB ---------- --------- MILLER CLERKCopyright © 2004, Oracle. All rights reserved.
  • 169. Using Group Functions in a Subquery Display all employees who earn the minimum salary. SQL> SELECT ename, job, sal 2 FROM emp 800 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp); ENAME JOB SAL ---------- --------- --------- SMITH CLERK 800Copyright © 2004, Oracle. All rights reserved.
  • 170. What Is Wrong with This Statement? ry ue SQL> SELECT empno, ename bq 2 FROM emp su 3 WHERE sal = ow 4 (SELECT MIN(sal) e -r 5 FROM emp ipl 6 GROUP BY lt deptno); u m ith ERROR: rw to returns ORA-01427: single-row ra subquery more than one row ope ow no rows selected -r gle S inCopyright © 2004, Oracle. All rights reserved.
  • 171. Will This Statement Work? SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4 (SELECT job es lu va 5 FROM emp 6 WHERE o ename=SMYTHE); n ns ur no rows selected r et ry ue bq SuCopyright © 2004, Oracle. All rights reserved.
  • 172. Multiple-Row Subqueries – – Return more than one row Return more than one row – – Use the IN multiple-row comparison operator to Use the IN multiple-row comparison operator to compare an expression to any member in the list that a compare an expression to any member in the list that a subquery returns subquery returnsCopyright © 2004, Oracle. All rights reserved.
  • 173. Using Group Functions in a Multiple-Row Subquery Display all employees who earn the same salary as the minimum salary for each department. SQL> SELECT ename, sal, deptno 2 FROM emp 800, 950, 1300 3 WHERE sal IN 4 (SELECT MIN(sal) 5 FROM emp 6 GROUP BY deptno); ENAME SAL DEPTNO ---------- --------- --------- SMITH 800 20 JAMES 950 30 MILLER 1300 10Copyright © 2004, Oracle. All rights reserved.
  • 174. Using Group Functions in a Multiple-Row Subquery Display the employees who were hired on the same date as the longest serving employee in any department.SQL> SELECT ename, sal, deptno, 2 TO_CHAR(hiredate,DD-MON-YYYY)HIREDATE 3 FROM emp 4 WHERE hiredate IN 5 (SELECT MIN(hiredate) 6 FROM emp 7 GROUP BY deptno); ENAME SAL DEPTNO HIREDATE ---------- --------- --------- ----------- SMITH 800 20 17-DEC-1980 ALLEN 1600 30 20-FEB-1981 CLARK 2450 10 09-JUN-1981Copyright © 2004, Oracle. All rights reserved.
  • 175. Controlling TransactionsCopyright © 2004, Oracle. All rights reserved.
  • 176. Data Manipulation Language – – A DML statement is executed when you: A DML statement is executed when you: Add new rows to a table (INSERT) Add new rows to a table (INSERT) Modify existing rows in a table (UPDATE) Modify existing rows in a table (UPDATE) Remove existing rows from a table (DELETE) Remove existing rows from a table (DELETE) – – A transaction consists of a collection of DML statements A transaction consists of a collection of DML statements that form a logical unit of work. that form a logical unit of work.Copyright © 2004, Oracle. All rights reserved.
  • 177. Database Transactions Database transactions can consist of: Database transactions can consist of: – – DML statements that make up one consistent change to the DML statements that make up one consistent change to the data data Example: UPDATE Example: UPDATE – – One DDL statement One DDL statement Example: CREATE Example: CREATE – – One DCL statement One DCL statement Example: GRANT and REVOKE Example: GRANT and REVOKECopyright © 2004, Oracle. All rights reserved.
  • 178. Database Transactions – – Begin when the first executable SQL statement is Begin when the first executable SQL statement is executed executed – – End with one of the following events: End with one of the following events: COMMIT or ROLLBACK COMMIT or ROLLBACK DDL or DCL statement executes (automatic commit) DDL or DCL statement executes (automatic commit) User exits User exits System crashes System crashesCopyright © 2004, Oracle. All rights reserved.
  • 179. Advantages of COMMIT and ROLLBACK – – COMMIT and ROLLBACK ensure data consistency. COMMIT and ROLLBACK ensure data consistency. – – Users can preview data changes before making Users can preview data changes before making changes permanent. changes permanent. – – Users can group logically related operations. Users can group logically related operations.Copyright © 2004, Oracle. All rights reserved.
  • 180. Controlling Transactions Transaction Transaction INSERT UPDATE INSERT DELETECOMMIT Savepoint A Savepoint B ROLLBACK to Savepoint B ROLLBACK to Savepoint A ROLLBACKCopyright © 2004, Oracle. All rights reserved.
  • 181. Implicit Transaction Processing – – An automatic commit occurs under the following An automatic commit occurs under the following circumstances: circumstances: A DDL statement is issued, such as CREATE A DDL statement is issued, such as CREATE A DCL statement is issued, such as GRANT A DCL statement is issued, such as GRANT A normal exit from SQL*Plus occurs without an explicitly A normal exit from SQL*Plus occurs without an explicitly issued COMMIT or ROLLBACK statement issued COMMIT or ROLLBACK statement – – An automatic rollback occurs under an abnormal An automatic rollback occurs under an abnormal termination of SQL*Plus or a system failure. termination of SQL*Plus or a system failure.Copyright © 2004, Oracle. All rights reserved.
  • 182. State of the Data Before COMMIT or ROLLBACK – – The previous state of the data can be recovered. The previous state of the data can be recovered. – – The current user can review the results of the DML operations The current user can review the results of the DML operations by using the SELECT statement. by using the SELECT statement. – – Other users cannot view the results of the DML statements by Other users cannot view the results of the DML statements by the current user. the current user. – – The affected rows are locked; other users cannot change the The affected rows are locked; other users cannot change the data within the affected rows. data within the affected rows.Copyright © 2004, Oracle. All rights reserved.
  • 183. Committing Data Change the department number of an employee Change the department number of an employee (Clark) identified by a employee number. (Clark) identified by a employee number. – – Make the changes. Make the changes. SQL> UPDATE emp SQL> UPDATE emp 2 SET 2 SET deptno = 10 deptno = 10 3 WHERE 3 WHERE empno = 7782; empno = 7782; 1 row updated. 1 row updated. • Commit the changes. • Commit the changes. SQL> COMMIT; Commit complete.Copyright © 2004, Oracle. All rights reserved.
  • 184. State of the Data After COMMIT • Data changes are made permanent in the • Data changes are made permanent in the database. database. • The previous state of the data is • The previous state of the data is permanently lost. permanently lost. • All users can view the results. • All users can view the results. • Locks on the affected rows are released; • Locks on the affected rows are released; those rows are available for other users to those rows are available for other users to manipulate. manipulate. • All savepoints are erased. • All savepoints are erased.Copyright © 2004, Oracle. All rights reserved.
  • 185. State of the Data After ROLLBACK Discard all pending changes by using the Discard all pending changes by using the ROLLBACK statement. Following a ROLLBACK: ROLLBACK statement. Following a ROLLBACK: – – Data changes are undone. Data changes are undone. – – The previous state of the data is restored. The previous state of the data is restored. – – Locks on the affected rows are released. Locks on the affected rows are released. SQL> DELETE FROM employee; 14 rows deleted. SQL> ROLLBACK; Rollback complete.Copyright © 2004, Oracle. All rights reserved.
  • 186. Rolling Back Changes to a Marker – – Create a marker within a current transaction by using Create a marker within a current transaction by using the SAVEPOINT statement. the SAVEPOINT statement. – – Roll back to that marker by using the ROLLBACK TO Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement. SAVEPOINT statement. SQL> UPDATE... SQL> SAVEPOINT update_done; Savepoint created. SQL> INSERT... SQL> ROLLBACK TO update_done; Rollback complete.Copyright © 2004, Oracle. All rights reserved.
  • 187. Statement-Level Rollback – – If a single DML statement fails during execution, only If a single DML statement fails during execution, only that statement is rolled back. that statement is rolled back. – – Oracle implements an implicit savepoint. Oracle implements an implicit savepoint. – – All other changes are retained. All other changes are retained. – – The user should terminate transactions explicitly by The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK statement. executing a COMMIT or ROLLBACK statement.Copyright © 2004, Oracle. All rights reserved.
  • 188. Read Consistency – – Read consistency guarantees a consistent view of the Read consistency guarantees a consistent view of the data at all times. data at all times. – – Changes made by one user do not conflict with Changes made by one user do not conflict with changes made by another user. changes made by another user. – – Read consistency ensures that on the same data: Read consistency ensures that on the same data: Readers do not wait for writers or other readers Readers do not wait for writers or other readers Writers do not wait for readers Writers do not wait for readersCopyright © 2004, Oracle. All rights reserved.
  • 189. Implementation of Read Consistency UPDATE emp Data SET sal = 2000 blocks WHERE ename = SCOTT; Rollback segments User A Changed and SELECT * unchanged Read FROM emp; data consistent image Before change “old” data User BCopyright © 2004, Oracle. All rights reserved.
  • 190. Locking The Oracle Server locks: The Oracle Server locks: – – Prevent destructive interaction between concurrent Prevent destructive interaction between concurrent transactions transactions – – Require no user action Require no user action – – Automatically use the lowest level of restrictiveness Automatically use the lowest level of restrictiveness – – Are held for the duration of the transaction Are held for the duration of the transaction – – Have two basic modes: Have two basic modes: Exclusive Exclusive Share ShareCopyright © 2004, Oracle. All rights reserved.
  • 191. Locking Modes Lock Mode Description Exclusive lock 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 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.Copyright © 2004, Oracle. All rights reserved.
  • 192. Implicit Locking User Action Row-Level Lock Table-Level Lock SELECT ... FROM table ... None None INSERT INTO table ... X RX UPDATE table ... X RX DELETE FROM table ... X RX DDL Operation None XCopyright © 2004, Oracle. All rights reserved.
  • 193. Explicit Locking User Action Row-Level lock Table-Level lock SELECT FOR UPDATE X RS [NOWAIT] LOCK TABLE IN option None Depends on the MODE restrictiveness used Override the default lock mechanism: Override the default lock mechanism: – – For a consistent view of data when reading across For a consistent view of data when reading across multiple tables multiple tables – – When a transaction may change data based on other When a transaction may change data based on other data that must not change until the whole transaction is data that must not change until the whole transaction is complete completeCopyright © 2004, Oracle. All rights reserved.
  • 194. Overview of PL/SQLCopyright © 2004, Oracle. All rights reserved.
  • 195. About PL/SQL – – PL/SQL is an extension to SQL with design features of PL/SQL is an extension to SQL with design features of programming languages. programming languages. – – Data manipulation and query statements of SQL are Data manipulation and query statements of SQL are included within procedural units of code. included within procedural units of code.Copyright © 2004, Oracle. All rights reserved.
  • 196. PL/SQL Environment PL/SQL engine PL/SQL Procedural PL/SQL PL/SQL block block SQL Statement Executor SQL Statement Executor Oracle ServerCopyright © 2004, Oracle. All rights reserved.
  • 197. Benefits of PL/SQL Integration Integration Application Shared Oracle Server libraryCopyright © 2004, Oracle. All rights reserved.
  • 198. Benefits of PL/SQL Improve Performance Improve Performance SQL SQL Application Application Other DBMSs Other DBMSs SQL SQL SQL IF...THEN SQL Oracle with Oracle with Application Application ELSE PL/SQL SQL PL/SQL END IF; SQLCopyright © 2004, Oracle. All rights reserved.
  • 199. Benefits of PL/SQL Modularize program development Modularize program development DECLARE BEGIN EXCEPTION END;Copyright © 2004, Oracle. All rights reserved.
  • 200. Benefits of PL/SQL – – It is portable. It is portable. – – You can declare identifiers. You can declare identifiers.Copyright © 2004, Oracle. All rights reserved.
  • 201. Benefits of PL/SQL – – You can program with procedural language control You can program with procedural language control structures. structures. – – It can handle errors. It can handle errors.Copyright © 2004, Oracle. All rights reserved.
  • 202. Declaring VariablesCopyright © 2004, Oracle. All rights reserved.
  • 203. PL/SQL Block Structure •• DECLARE ––Optional DECLARE Optional – Variables, cursors, user-defined exceptions – Variables, cursors, user-defined exceptions •• BEGIN ––Mandatory BEGIN Mandatory – SQL statements – SQL statements – PL/SQL statements – PL/SQL statements •• EXCEPTION ––Optional EXCEPTION Optional – Actions to perform when – Actions to perform when errors occur errors occur •• END; ––Mandatory END; Mandatory DECLARE BEGIN EXCEPTION END;Copyright © 2004, Oracle. All rights reserved.
  • 204. PL/SQL Block Structure DECLARE DECLARE v_variable VARCHAR2(5); v_variable VARCHAR2(5); BEGIN BEGIN SELECT SELECT column_name column_name INTO INTO v_variable v_variable FROM FROM table_name; table_name; EXCEPTION EXCEPTION WHEN exception_name THEN WHEN exception_name THEN DECLARE ... ... END; BEGIN END; EXCEPTION END;Copyright © 2004, Oracle. All rights reserved.
  • 205. Block Types Anonymous Procedure Function [DECLARE] [DECLARE] PROCEDURE name PROCEDURE name FUNCTION name FUNCTION name IS IS RETURN datatype RETURN datatype IS IS BEGIN BEGIN BEGIN BEGIN BEGIN BEGIN --statements --statements --statements --statements --statements --statements RETURN value; RETURN value; [EXCEPTION] [EXCEPTION] [EXCEPTION] [EXCEPTION] [EXCEPTION] [EXCEPTION] END; END; END; END; END; END;Copyright © 2004, Oracle. All rights reserved.
  • 206. Program Constructs Stored Stored Anonymous Anonymous procedure/ procedure/ block block DECLARE function function BEGIN Application Application Application Application procedure/ procedure/ trigger trigger function function EXCEPTION Database END; Packaged Packaged Database procedure/ trigger procedure/ trigger function functionCopyright © 2004, Oracle. All rights reserved.
  • 207. Use of Variables Use variables for: Use variables for: – – Temporary storage of data Temporary storage of data – – Manipulation of stored values Manipulation of stored values – – Reusability Reusability – – Ease of maintenance Ease of maintenanceCopyright © 2004, Oracle. All rights reserved.
  • 208. Handling Variables in PL/SQL – – Declare and initialize variables in the declaration Declare and initialize variables in the declaration section. section. – – Assign new values to variables in the executable Assign new values to variables in the executable section. section. – – Pass values into PL/SQL blocks through parameters. Pass values into PL/SQL blocks through parameters. – – View results through output variables. View results through output variables.Copyright © 2004, Oracle. All rights reserved.
  • 209. Types of Variables – – PL/SQL variables: PL/SQL variables: Scalar Scalar Composite Composite Reference Reference LOB (large objects) LOB (large objects) – – Non-PL/SQL variables: Bind and host variables Non-PL/SQL variables: Bind and host variablesCopyright © 2004, Oracle. All rights reserved.
  • 210. Types of Variables – – PL/SQL variables: PL/SQL variables: Scalar Scalar Composite Composite Reference Reference LOB (large objects) LOB (large objects) – – Non-PL/SQL variables: Bind and host variables Non-PL/SQL variables: Bind and host variablesCopyright © 2004, Oracle. All rights reserved.
  • 211. Types of Variables 25-OCT-99 TRUE “Four score and seven years ago our fathers brought forth upon this continent, a new nation, conceived in LIBERTY, and dedicated256120.08 to the proposition that all men are created equal.” AtlantaCopyright © 2004, Oracle. All rights reserved.
  • 212. Declaring PL/SQL Variables Syntax Syntax identifier [CONSTANT] datatype [NOT NULL] identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; [:= | DEFAULT expr]; Examples Examples Declare Declare v_hiredate v_hiredate DATE; DATE; v_deptno v_deptno NUMBER(2) NOT NULL := 10; NUMBER(2) NOT NULL := 10; v_location v_location VARCHAR2(13) := Atlanta; VARCHAR2(13) := Atlanta; c_comm c_comm CONSTANT NUMBER := 1400; CONSTANT NUMBER := 1400;Copyright © 2004, Oracle. All rights reserved.
  • 213. Declaring PL/SQL Variables Guidelines Guidelines – – Follow naming conventions. Follow naming conventions. – – Initialize variables designated as NOT NULL. Initialize variables designated as NOT NULL. – – Initialize identifiers by using the assignment operator Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word. (:=) or the DEFAULT reserved word. – – Declare at most one identifier per line. Declare at most one identifier per line.Copyright © 2004, Oracle. All rights reserved.
  • 214. Naming Rules – – Two variables can have the same name, provided they Two variables can have the same name, provided they are in different blocks. are in different blocks. – – The variable name (identifier) should not be the same The variable name (identifier) should not be the same as the name of table columns used in the block. as the name of table columns used in the block. ffor or ttiion n o n ven nve s:: co n er g c o tiiffiier s o DECLARE ng n miin den t mpn o na m L iide _e mpn DECLARE empno NUMBER(4); empno NUMBER(4); a na Q L ptt a //S Q lle,, v _e BEGIN BEGIN do p PL S mp e v A do PL a mp empno A SELECT SELECT empno ex a r ex INTO INTO empno empno ffo r o FROM FROM emp emp WHERE WHERE ename = SMITH; ename = SMITH; END; END;Copyright © 2004, Oracle. All rights reserved.
  • 215. Assigning Values to Variables Syntax Syntax identifier := expr; identifier := expr; Example Example • Set a predefined hiredate for new • Set a predefined hiredate for new employees. employees. v_hiredate := 31-DEC-98; v_hiredate := 31-DEC-98; • Set the employee name to “Maduro.” • Set the employee name to “Maduro.” v_ename := Maduro; v_ename := Maduro;Copyright © 2004, Oracle. All rights reserved.
  • 216. Variable Initialization and Keywords Using: Using: – – Assignment operator (:=) Assignment operator (:=) – – DEFAULT keyword DEFAULT keyword – – NOT NULL constraint NOT NULL constraintCopyright © 2004, Oracle. All rights reserved.
  • 217. Scalar Datatypes • Hold a single value • Hold a single value • Have no internal components • Have no internal components 25-OCT-99 and seven years “Four score ago our fathers brought forth upon this continent, a TRUE new nation, conceived in256120.08 LIBERTY, and dedicated to the proposition that all men are created equal.” AtlantaCopyright © 2004, Oracle. All rights reserved.
  • 218. Base Scalar Datatypes – – VARCHAR2 (maximum_length) VARCHAR2 (maximum_length) – – NUMBER [(precision, scale)] NUMBER [(precision, scale)] – – DATE DATE – – CHAR [(maximum_length)] CHAR [(maximum_length)] – – LONG LONG – – LONG RAW LONG RAW – – BOOLEAN BOOLEAN – – BINARY_INTEGER BINARY_INTEGER – – PLS_INTEGER PLS_INTEGERCopyright © 2004, Oracle. All rights reserved.
  • 219. Base Scalar Datatypes – – DATE DATE – – TIMESTAMP TIMESTAMP – – TIMESTAMP WITH TIMEZHONE TIMESTAMP WITH TIMEZHONE – – TIMESTAMP WITH LOCAL TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE – – INTERVAL YEAR TO MONTH INTERVAL YEAR TO MONTH – – INVERTAL YEAR TO SECOND INVERTAL YEAR TO SECONDCopyright © 2004, Oracle. All rights reserved.
  • 220. Scalar Variable Declarations Example Example v_job v_job VARCHAR2(9); VARCHAR2(9); v_count v_count BINARY_INTEGER := 0; BINARY_INTEGER := 0; v_total_sal v_total_sal NUMBER(9,2) := 0; NUMBER(9,2) := 0; v_orderdate v_orderdate DATE := SYSDATE + 7; DATE := SYSDATE + 7; c_tax_rate c_tax_rate CONSTANT NUMBER(3,2) := 8.25; CONSTANT NUMBER(3,2) := 8.25; v_valid v_valid BOOLEAN NOT NULL := TRUE; BOOLEAN NOT NULL := TRUE;Copyright © 2004, Oracle. All rights reserved.
  • 221. The %TYPE Attribute – – Declare a variable according to: Declare a variable according to: A database column definition A database column definition Another previously declared variable Another previously declared variable – – Prefix %TYPE with: Prefix %TYPE with: The database table and column The database table and column The previously declared variable name The previously declared variable nameCopyright © 2004, Oracle. All rights reserved.
  • 222. Declaring Variables with the %TYPE Attribute Example Example ... ... v_ename v_ename emp.ename%TYPE; emp.ename%TYPE; v_balance v_balance NUMBER(7,2); NUMBER(7,2); v_min_balance v_min_balance v_balance%TYPE := 10; v_balance%TYPE := 10; ... ...Copyright © 2004, Oracle. All rights reserved.
  • 223. Declaring Boolean Variables – – Only the values TRUE, FALSE, and NULL can be Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable. assigned to a Boolean variable. – – The variables are connected by the logical operators The variables are connected by the logical operators AND, OR, and NOT. AND, OR, and NOT. – – The variables always yield TRUE, FALSE, or NULL. The variables always yield TRUE, FALSE, or NULL. – – Arithmetic, character, and date expressions can be Arithmetic, character, and date expressions can be used to return a Boolean value. used to return a Boolean value.Copyright © 2004, Oracle. All rights reserved.
  • 224. Composite Datatypes – – PL/SQL TABLES PL/SQL TABLES – – PL/SQL RECORDS PL/SQL RECORDSCopyright © 2004, Oracle. All rights reserved.
  • 225. LOB Datatype Variables Recipe (CLOB) Photo (BLOB) Movie (BFILE) NCLOBCopyright © 2004, Oracle. All rights reserved.
  • 226. Bind Variables O/S Bind Variable ServerCopyright © 2004, Oracle. All rights reserved.
  • 227. Referencing Non-PL/SQL Variables Store the annual salary into a SQL*Plus host Store the annual salary into a SQL*Plus host variable. variable. :g_monthly_sal := v_sal / 12; :g_monthly_sal := v_sal / 12; – – Reference non-PL/SQL variables as host variables. Reference non-PL/SQL variables as host variables. – – Prefix the references with a colon (:). Prefix the references with a colon (:).Copyright © 2004, Oracle. All rights reserved.
  • 228. Copyright © 2004, Oracle. All rights reserved.
  • 229. DBMS_OUTPUT.PUT_LINE – – An Oracle-supplied packaged procedure An Oracle-supplied packaged procedure – – An alternative for displaying data from a PL/SQL block An alternative for displaying data from a PL/SQL block – – Must be enabled in SQL*Plus with Must be enabled in SQL*Plus with SET SERVEROUTPUT ON SET SERVEROUTPUT ONCopyright © 2004, Oracle. All rights reserved.
  • 230. Writing Executable StatementsCopyright © 2004, Oracle. All rights reserved.
  • 231. PL/SQL Block Syntax and Guidelines – – Statements can continue over several lines. Statements can continue over several lines. – – Lexical units can be separated by: Lexical units can be separated by: Spaces Spaces Delimiters Delimiters Identifiers Identifiers Literals Literals Comments CommentsCopyright © 2004, Oracle. All rights reserved.
  • 232. PL/SQL Block Syntax and Guidelines Identifiers Identifiers – – Can contain up to 30 characters Can contain up to 30 characters – – Cannot contain reserved words unless enclosed in Cannot contain reserved words unless enclosed in double quotation marks double quotation marks – – Must begin with an alphabetic character Must begin with an alphabetic character – – Should not have the same name as a database table Should not have the same name as a database table column name column nameCopyright © 2004, Oracle. All rights reserved.
  • 233. PL/SQL Block Syntax and Guidelines Literals Literals – – Character and date literals must be enclosed in single Character and date literals must be enclosed in single quotation marks. quotation marks. v_ename := Henderson; values or scientific notation. – Numbers can be simple v_ename := Henderson; values or scientific notation. – Numbers can be simpleCopyright © 2004, Oracle. All rights reserved.
  • 234. Commenting Code – – Prefix single-line comments with two dashes (--). Prefix single-line comments with two dashes (--). – – Place multi-line comments between the symbols /* and Place multi-line comments between the symbols /* and */. */. Example Example ... ... v_sal NUMBER (9,2); v_sal NUMBER (9,2); BEGIN BEGIN /* Compute the annual salary based on the /* Compute the annual salary based on the monthly salary input from the user */ monthly salary input from the user */ v_sal := &p_monthly_sal * 12; v_sal := &p_monthly_sal * 12; END; -- This is the end of the transaction END; -- This is the end of the transactionCopyright © 2004, Oracle. All rights reserved.
  • 235. SQL Functions in PL/SQL – – Available: Available: Single-row number Single-row number } Single-row character Single-row character Datatype conversion Datatype conversion Date Date Same as in SQL – – Not available: Not available: DECODE DECODE Group functions Group functionsCopyright © 2004, Oracle. All rights reserved.
  • 236. PL/SQL Functions Example Example – – Build the mailing list for a company. Build the mailing list for a company. v_mailing_address := v_name||CHR(10)|| v_mailing_address := v_name||CHR(10)|| v_address||CHR(10)||v_state|| v_address||CHR(10)||v_state|| CHR(10)||v_zip; CHR(10)||v_zip; – – Convert the employee name to lowercase. Convert the employee name to lowercase. v_ename v_ename := LOWER(v_ename); := LOWER(v_ename);Copyright © 2004, Oracle. All rights reserved.
  • 237. Datatype Conversion – – Convert data to comparable datatypes. Convert data to comparable datatypes. – – Mixed datatypes can result in an error and affect Mixed datatypes can result in an error and affect performance. performance. – – Conversion functions: Conversion functions: TO_CHAR TO_CHAR TO_DATE TO_DATE DECLARE DECLARE TO_NUMBER TO_NUMBER v_date v_date VARCHAR2(15); VARCHAR2(15); BEGIN BEGIN SELECT SELECTTO_CHAR(hiredate, TO_CHAR(hiredate, MON. DD, YYYY) MON. DD, YYYY) INTO INTO v_date v_date FROM FROM emp emp WHERE empno = 7839; WHERE empno = 7839; END; END;Copyright © 2004, Oracle. All rights reserved.
  • 238. Datatype Conversion This statement produces a compilation This statement produces a compilation error if the variable v_date is declared as error if the variable v_date is declared as datatype DATE. datatype DATE. v_date := January 13, 1998; v_date := January 13, 1998; To correct the error, use the TO_DATE To correct the error, use the TO_DATE conversion function. conversion function. v_date := TO_DATE (January 13, 1998, v_date := TO_DATE (January 13, 1998, Month DD, YYYY); Month DD, YYYY);Copyright © 2004, Oracle. All rights reserved.
  • 239. Nested Blocks and Variable Scope – – Statements can be nested wherever an executable Statements can be nested wherever an executable statement is allowed. statement is allowed. – – A nested block becomes a statement. A nested block becomes a statement. – – An exception section can contain nested blocks. An exception section can contain nested blocks. – – The scope of an object is the region of the program that The scope of an object is the region of the program that can refer to the object. can refer to the object.Copyright © 2004, Oracle. All rights reserved.
  • 240. Nested Blocks and Variable Scope An identifier is visible in the regions in which you An identifier is visible in the regions in which you can reference the unqualified identifier: can reference the unqualified identifier: – – A block can look up to the enclosing block. A block can look up to the enclosing block. – – A block cannot look down to enclosed blocks. A block cannot look down to enclosed blocks.Copyright © 2004, Oracle. All rights reserved.
  • 241. Nested Blocks and Variable Scope Example Example ... ... x BINARY_INTEGER; x BINARY_INTEGER; BEGIN BEGIN Scope of x ... ... DECLARE DECLARE y NUMBER; y NUMBER; BEGIN BEGIN Scope of y ... ... END; END; ... ... END; END;Copyright © 2004, Oracle. All rights reserved.
  • 242. Operators in PL/SQL – – Logical Logical – – Arithmetic Arithmetic – – Concatenation Concatenation – – Parentheses to control order of Parentheses to control order of Same as in operations operations SQL – – Exponential operator (**) Exponential operator (**)Copyright © 2004, Oracle. All rights reserved.
  • 243. Operators in PL/SQL Example Example – – Increment the index for a loop. Increment the index for a loop. v_count v_count := v_count + 1; := v_count + 1; – – Set the value of a Boolean flag. Set the value of a Boolean flag. v_equal v_equal := (v_n1 = v_n2); := (v_n1 = v_n2); – Validate an employee number if it contains a value. – Validate an employee number if it contains a value. v_valid v_valid := (v_empno IS NOT NULL); := (v_empno IS NOT NULL);Copyright © 2004, Oracle. All rights reserved.
  • 244. Using Bind Variables To reference a bind variable in PL/SQL, you must To reference a bind variable in PL/SQL, you must prefix its name with a colon (:). prefix its name with a colon (:). Example Example VARIABLE g_salary NUMBER VARIABLE g_salary NUMBER DECLARE DECLARE v_sal v_sal emp.sal%TYPE; emp.sal%TYPE; BEGIN BEGIN SELECT SELECT sal sal INTO INTO v_sal v_sal FROM FROM emp emp WHERE WHERE empno = 7369; empno = 7369; :g_salary :g_salary := v_sal; := v_sal; END; END; / /Copyright © 2004, Oracle. All rights reserved.
  • 245. Programming Guidelines Make code maintenance easier by: Make code maintenance easier by: – – Documenting code with comments Documenting code with comments – – Developing a case convention for the code Developing a case convention for the code – – Developing naming conventions for identifiers and Developing naming conventions for identifiers and other objects other objects – – Enhancing readability by indenting Enhancing readability by indentingCopyright © 2004, Oracle. All rights reserved.
  • 246. Code Naming Conventions Avoid ambiguity: Avoid ambiguity: – – The names of local variables and formal parameters The names of local variables and formal parameters take precedence over the names of database tables. take precedence over the names of database tables. – – The names of columns take precedence over the The names of columns take precedence over the names of local variables. names of local variables.Copyright © 2004, Oracle. All rights reserved.
  • 247. Indenting Code For clarity, indent each level of code. For clarity, indent each level of code. Example Example DECLARE DECLARE v_deptno v_deptno NUMBER(2); NUMBER(2); BEGIN BEGIN v_location v_location VARCHAR2(13); VARCHAR2(13); IF x=0 THEN IF x=0 THEN BEGIN BEGIN y:=1; y:=1; SELECT deptno, SELECT deptno, END IF; END IF; loc loc END; END; INTO INTO v_deptno, v_deptno, v_location v_location FROM FROM dept dept WHERE WHERE dname = SALES; dname = SALES; ... ... END; END;Copyright © 2004, Oracle. All rights reserved.
  • 248. Determining Variable Scope Class Exercise Class Exercise ... ... DECLARE DECLARE V_SAL V_SAL NUMBER(7,2) := 60000; NUMBER(7,2) := 60000; V_COMM V_COMM NUMBER(7,2) := V_SAL * .20; NUMBER(7,2) := V_SAL * .20; V_MESSAGE V_MESSAGE VARCHAR2(255) := eligible for commission; VARCHAR2(255) := eligible for commission; BEGIN ... BEGIN ... DECLARE DECLARE V_SAL V_SAL NUMBER(7,2) := 50000; NUMBER(7,2) := 50000; V_COMM V_COMM NUMBER(7,2) := 0; NUMBER(7,2) := 0; V_TOTAL_COMP V_TOTAL_COMP NUMBER(7,2) := V_SAL + V_COMM; NUMBER(7,2) := V_SAL + V_COMM; BEGIN ... BEGIN ... V_MESSAGE := CLERK not||V_MESSAGE; V_MESSAGE := CLERK not||V_MESSAGE; END; END; V_MESSAGE := SALESMAN||V_MESSAGE; V_MESSAGE := SALESMAN||V_MESSAGE; END; END;Copyright © 2004, Oracle. All rights reserved.
  • 249. Writing Control StructuresCopyright © 2004, Oracle. All rights reserved.
  • 250. Controlling PL/SQL Flow of Execution You can change the logical flow of statements You can change the logical flow of statements using conditional IF statements and loop control using conditional IF statements and loop control structures. structures. Conditional IF Conditional IF statements: statements: – – IF-THEN-END IF IF-THEN-END IF – – IF-THEN-ELSE-END IF IF-THEN-ELSE-END IF – – IF-THEN-ELSIF-END IF IF-THEN-ELSIF-END IFCopyright © 2004, Oracle. All rights reserved.
  • 251. IF Statements Syntax Syntax IF condition THEN IF condition THEN statements; statements; [ELSIF condition THEN [ELSIF condition THEN statements;] statements;] [ELSE [ELSE statements;] statements;] END IF; END IF; Simple IF statement: Simple IF statement: Set the manager ID to 22 if the employee Set the manager ID to 22 if the employee name is Osborne. name is Osborne. IF v_ename IF v_ename = OSBORNE THEN = OSBORNE THEN v_mgr := v_mgr := 22; 22; END IF; END IF;Copyright © 2004, Oracle. All rights reserved.
  • 252. Simple IF Statements Set the job title to Salesman, the department number to 35, Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last and the commission to 20% of the current salary if the last name is Miller. name is Miller. Example Example . . . . . . IF v_ename = MILLER THEN IF v_ename = MILLER THEN v_job := SALESMAN; v_job := SALESMAN; v_deptno := 35; v_deptno := 35; v_new_comm := sal * 0.20; v_new_comm := sal * 0.20; END IF; END IF; . . . . . .Copyright © 2004, Oracle. All rights reserved.
  • 253. IF-THEN-ELSE Statement Execution Flow TRUE FALSE IF condition THEN actions THEN actions ELSE actions ELSE actions (including further IFs) (including further IFs) (including further IFs) (including further IFs)Copyright © 2004, Oracle. All rights reserved.
  • 254. IF-THEN-ELSE Statements Set a flag for orders where there are fewer than Set a flag for orders where there are fewer than five days between order date and ship date. five days between order date and ship date. Example Example ... ... IF v_shipdate IF v_shipdate - v_orderdate < 5 THEN - v_orderdate < 5 THEN v_ship_flag v_ship_flag := Acceptable; := Acceptable; ELSE ELSE v_ship_flag v_ship_flag := Unacceptable; := Unacceptable; END IF; END IF; ... ...Copyright © 2004, Oracle. All rights reserved.
  • 255. IF-THEN-ELSIF Statement Execution Flow IF condition IF condition TRUE FALSE ELSIF ELSIF condition condition THEN actions THEN actions TRUE FALSE ELSE ELSE THEN actions THEN actions actions actionsCopyright © 2004, Oracle. All rights reserved.
  • 256. IF-THEN-ELSIF Statements For a given value, calculate a percentage of that For a given value, calculate a percentage of that value based on a condition. value based on a condition. Example Example . . . . . . IF v_start > 100 THEN IF v_start > 100 THEN v_start := 2 * v_start; v_start := 2 * v_start; ELSIF v_start >= 50 THEN ELSIF v_start >= 50 THEN v_start := .5 * v_start; v_start := .5 * v_start; ELSE ELSE v_start := .1 * v_start; v_start := .1 * v_start; END IF; END IF; . . . . . .Copyright © 2004, Oracle. All rights reserved.
  • 257. Building Logical Conditions – – You can handle null values with the IS NULL operator. You can handle null values with the IS NULL operator. – – Any arithmetic expression containing a null value Any arithmetic expression containing a null value evaluates to NULL. evaluates to NULL. – – Concatenated expressions with null values treat null Concatenated expressions with null values treat null values as an empty string. values as an empty string.Copyright © 2004, Oracle. All rights reserved.
  • 258. Logic Tables Build a simple Boolean condition with a Build a simple Boolean condition with a comparison operator. comparison operator. AND TRUE FALSE NULL OR TRUE FALSE NULL NOTTRUE TRUE FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSEFALSE FALSE FALSE FALSE FALSE TRUE FALSE NULL FALSE TRUENULL NULL FALSE NULL NULL TRUE NULL NULL NULL NULLCopyright © 2004, Oracle. All rights reserved.
  • 259. Boolean Conditions What is the value of V_FLAG in each case? What is the value of V_FLAG in each case? v_flag := v_reorder_flag AND v_available_flag; v_flag := v_reorder_flag AND v_available_flag; V_REORDER_FLAG V_AVAILABLE_FLAG V_FLAG TRUE TRUE TRUE TRUE FALSE FALSE NULL TRUE NULL NULL FALSE FALSECopyright © 2004, Oracle. All rights reserved.
  • 260. Iterative Control: LOOP Statements – – Loops repeat a statement or sequence of statements Loops repeat a statement or sequence of statements multiple times. multiple times. – – There are three loop types: There are three loop types: Basic loop Basic loop FOR loop FOR loop WHILE loop WHILE loopCopyright © 2004, Oracle. All rights reserved.
  • 261. Basic Loop Syntax Syntax LOOP LOOP -- delimiter statement1; statement1; -- statements . . . . . . EXIT [WHEN condition]; -- EXIT statement EXIT [WHEN condition]; END LOOP; END LOOP; -- delimiter where: where: condition condition is a Boolean variable or is a Boolean variable or expression (TRUE, FALSE, expression (TRUE, FALSE, or NULL); or NULL);Copyright © 2004, Oracle. All rights reserved.
  • 262. Basic Loop Example Example DECLARE DECLARE v_ordid v_ordid item.ordid%TYPE := 601; item.ordid%TYPE := 601; v_counter NUMBER(2) := 1; v_counter NUMBER(2) := 1; BEGIN BEGIN LOOP LOOP INSERT INTO item(ordid, itemid) INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); VALUES(v_ordid, v_counter); v_counter := v_counter + 1; v_counter := v_counter + 1; EXIT WHEN v_counter > 10; EXIT WHEN v_counter > 10; END LOOP; END LOOP; END; END;Copyright © 2004, Oracle. All rights reserved.
  • 263. FOR Loop FOR counter in [REVERSE] FOR counter in [REVERSE] lower_bound..upper_bound LOOP Syntax Syntax lower_bound..upper_bound LOOP statement1; statement1; statement2; statement2; . . . . . . END LOOP; END LOOP; – – Use a FOR loop to shortcut the test for the number of Use a FOR loop to shortcut the test for the number of iterations. iterations. – – Do not declare the index; it is declared implicitly. Do not declare the index; it is declared implicitly.Copyright © 2004, Oracle. All rights reserved.
  • 264. FOR Loop Guidelines Guidelines – – Reference the counter within the loop only; it is undefined Reference the counter within the loop only; it is undefined outside the loop. outside the loop. – – Use an expression to reference the existing value of a Use an expression to reference the existing value of a counter. counter. – – Do not reference the counter as the target of an Do not reference the counter as the target of an assignment. assignment.Copyright © 2004, Oracle. All rights reserved.
  • 265. FOR Loop Insert the first 10 new line items for order number Insert the first 10 new line items for order number 601. 601. Example Example DECLARE DECLARE v_ordid v_ordid item.ordid%TYPE := 601; item.ordid%TYPE := 601; BEGIN BEGIN FOR i IN 1..10 LOOP FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); VALUES(v_ordid, i); END LOOP; END LOOP; END; END;Copyright © 2004, Oracle. All rights reserved.
  • 266. WHILE Loop Syntax Syntax WHILE condition LOOP WHILE condition LOOP Condition is statement1; statement1; evaluated at the statement2; statement2; beginning of . . . . . . each iteration. END LOOP; END LOOP; Use the WHILE loop to repeat statements while a Use the WHILE loop to repeat statements while a condition is TRUE. condition is TRUE.Copyright © 2004, Oracle. All rights reserved.
  • 267. WHILE Loop Example Example ACCEPT p_new_order PROMPT Enter the order number: ACCEPT p_new_order PROMPT Enter the order number: ACCEPT p_items - ACCEPT p_items - PROMPT Enter the number of items in this order: PROMPT Enter the number of items in this order: DECLARE DECLARE v_count v_count NUMBER(2) := 1; NUMBER(2) := 1; BEGIN BEGIN WHILE v_count <= &p_items LOOP WHILE v_count <= &p_items LOOP INSERT INTO item (ordid, itemid) INSERT INTO item (ordid, itemid) VALUES (&p_new_order, v_count); VALUES (&p_new_order, v_count); v_count := v_count + 1; v_count := v_count + 1; END LOOP; END LOOP; COMMIT; COMMIT; END; END; / /Copyright © 2004, Oracle. All rights reserved.
  • 268. Nested Loops and Labels – – Nest loops to multiple levels. Nest loops to multiple levels. – – Use labels to distinguish between blocks and loops. Use labels to distinguish between blocks and loops. – – Exit the outer loop with the EXIT statement referencing Exit the outer loop with the EXIT statement referencing the label. the label.Copyright © 2004, Oracle. All rights reserved.
  • 269. Nested Loops and Labels ... ... BEGIN BEGIN <<Outer_loop>> <<Outer_loop>> LOOP LOOP v_counter := v_counter+1; v_counter := v_counter+1; EXIT WHEN v_counter>10; EXIT WHEN v_counter>10; <<Inner_loop>> <<Inner_loop>> LOOP LOOP ... ... EXIT Outer_loop WHEN total_done = YES; EXIT Outer_loop WHEN total_done = YES; -- Leave both loops -- Leave both loops EXIT WHEN inner_done = YES; EXIT WHEN inner_done = YES; -- Leave inner loop only -- Leave inner loop only ... ... END LOOP Inner_loop; END LOOP Inner_loop; ... ... END LOOP Outer_loop; END LOOP Outer_loop; END; END;Copyright © 2004, Oracle. All rights reserved.
  • 270. Writing Explicit CursorsCopyright © 2004, Oracle. All rights reserved.
  • 271. About Cursors Every SQL statement executed by the Oracle Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Server has an individual cursor associated with it: – – Implicit cursors: Declared for all DML and PL/SQL Implicit cursors: Declared for all DML and PL/SQL SELECT statements SELECT statements – – Explicit cursors: Declared and named by the Explicit cursors: Declared and named by the programmer programmerCopyright © 2004, Oracle. All rights reserved.
  • 272. Explicit Cursor Functions Active set 7369 SMITH CLERK 7566 JONES MANAGER Cursor 7788 SCOTT ANALYST Current row 7876 ADAMS CLERK 7902 FORD ANALYSTCopyright © 2004, Oracle. All rights reserved.
  • 273. Controlling Explicit Cursors No YesDECLAREDECLARE OPEN OPEN FETCH FETCH EMPTY? CLOSE CLOSE• Create a • Identify • Load the • Test for • Release named the active current existing the active SQL area set row into rows set variables • Return to FETCH if rows foundCopyright © 2004, Oracle. All rights reserved.
  • 274. Controlling Explicit Cursors Open the cursor. Pointer Cursor Fetch a row from the cursor. Pointer Cursor Continue until empty. Pointer Cursor Close the cursor. CursorCopyright © 2004, Oracle. All rights reserved.
  • 275. Declaring the Cursor Syntax Syntax CURSOR cursor_name IS CURSOR cursor_name IS select_statement; select_statement; – – Do not include the INTO clause in the cursor declaration. Do not include the INTO clause in the cursor declaration. – – If processing rows in a specific sequence is required, use the If processing rows in a specific sequence is required, use the ORDER BY clause in the query. ORDER BY clause in the query.Copyright © 2004, Oracle. All rights reserved.
  • 276. Declaring the Cursor Example Example DECLARE DECLARE CURSOR emp_cursor IS CURSOR emp_cursor IS SELECT empno, ename SELECT empno, ename FROM FROM emp; emp; CURSOR dept_cursor IS CURSOR dept_cursor IS SELECT * SELECT * FROM FROM dept dept WHERE deptno = 10; WHERE deptno = 10; BEGIN BEGIN ... ...Copyright © 2004, Oracle. All rights reserved.
  • 277. Opening the Cursor Syntax Syntax OPEN cursor_name; OPEN cursor_name; – – Open the cursor to execute the query and identify the Open the cursor to execute the query and identify the active set. active set. – – If the query returns no rows, no exception is raised. If the query returns no rows, no exception is raised. – – Use cursor attributes to test the outcome after a fetch. Use cursor attributes to test the outcome after a fetch.Copyright © 2004, Oracle. All rights reserved.
  • 278. Fetching Data from the Cursor Syntax Syntax FETCH cursor_name INTO [variable1, variable2, ...] FETCH cursor_name INTO [variable1, variable2, ...] | record_name]; | record_name]; – – Retrieve the current row values into output variables. Retrieve the current row values into output variables. – – Include the same number of variables. Include the same number of variables. – – Match each variable to correspond to the columns Match each variable to correspond to the columns positionally. positionally. – – Test to see if the cursor contains rows. Test to see if the cursor contains rows.Copyright © 2004, Oracle. All rights reserved.
  • 279. Fetching Data from the Cursor Example Example FETCH emp_cursor INTO v_empno, v_ename; FETCH emp_cursor INTO v_empno, v_ename; ... ... OPEN defined_cursor; OPEN defined_cursor; LOOP LOOP FETCH defined_cursor INTO defined_variables FETCH defined_cursor INTO defined_variables EXIT WHEN ...; EXIT WHEN ...; ... ... -- Process the retrieved data -- Process the retrieved data ... ... END; END;Copyright © 2004, Oracle. All rights reserved.
  • 280. Closing the Cursor Syntax Syntax CLOSE CLOSE cursor_name; cursor_name; – – Close the cursor after completing the processing of the Close the cursor after completing the processing of the rows. rows. – – Reopen the cursor, if required. Reopen the cursor, if required. – – Do not attempt to fetch data from a cursor once it has Do not attempt to fetch data from a cursor once it has been closed. been closed.Copyright © 2004, Oracle. All rights reserved.
  • 281. Explicit Cursor Attributes Obtain status information about a cursor. Obtain status information about a cursor. Attribute Type Description %ISOPEN Boolean Evaluates to TRUE if the cursor is open %NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row %FOUND Boolean Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND %ROWCOUNT Number Evaluates to the total number of rows returned so farCopyright © 2004, Oracle. All rights reserved.
  • 282. The %ISOPEN Attribute – – Fetch rows only when the cursor is open. Fetch rows only when the cursor is open. – – Use the %ISOPEN cursor attribute before performing a Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. fetch to test whether the cursor is open. Example Example IF NOT emp_cursor%ISOPEN THEN IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; OPEN emp_cursor; END IF; END IF; LOOP LOOP FETCH emp_cursor... FETCH emp_cursor...Copyright © 2004, Oracle. All rights reserved.
  • 283. Controlling Multiple Fetches – – Process several rows from an explicit cursor using a Process several rows from an explicit cursor using a loop. loop. – – Fetch a row with each iteration. Fetch a row with each iteration. – – Use the %NOTFOUND attribute to write a test for an Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. unsuccessful fetch. – – Use explicit cursor attributes to test the success of Use explicit cursor attributes to test the success of each fetch. each fetch.Copyright © 2004, Oracle. All rights reserved.
  • 284. The %NOTFOUND and %ROWCOUNT Attributes – – Use the %ROWCOUNT cursor attribute to retrieve an Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. exact number of rows. – – Use the %NOTFOUND cursor attribute to determine Use the %NOTFOUND cursor attribute to determine when to exit the loop. when to exit the loop.Copyright © 2004, Oracle. All rights reserved.
  • 285. Copyright © 2004, Oracle. All rights reserved.
  • 286. Cursors and Records Process the rows of the active set conveniently by Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. fetching values into a PL/SQL RECORD. Example Example DECLARE DECLARE CURSOR emp_cursor IS CURSOR emp_cursor IS SELECT empno, ename SELECT empno, ename FROM FROM emp; emp; emp_record emp_record emp_cursor%ROWTYPE; emp_cursor%ROWTYPE; BEGIN BEGIN OPEN emp_cursor; OPEN emp_cursor; LOOP LOOP FETCH emp_cursor INTO emp_record; FETCH emp_cursor INTO emp_record; ... ...Copyright © 2004, Oracle. All rights reserved.
  • 287. Cursor FOR Loops Syntax Syntax FOR record_name IN cursor_name LOOP FOR record_name IN cursor_name LOOP statement1; statement1; statement2; statement2; . . . . . . END LOOP; – END LOOP; FOR loop is a shortcut to process explicit – The cursor FOR loop is a shortcut to process explicit The cursor cursors. cursors. – – Implicit open, fetch, and close occur. Implicit open, fetch, and close occur. – – The record is implicitly declared. The record is implicitly declared.Copyright © 2004, Oracle. All rights reserved.
  • 288. Cursor FOR Loops Retrieve employees one by one until no more are Retrieve employees one by one until no more are left. left. Example Example DECLARE DECLARE CURSOR emp_cursor IS CURSOR emp_cursor IS SELECT ename, deptno SELECT ename, deptno FROM FROM emp; emp; BEGIN BEGIN FOR emp_record IN emp_cursor LOOP FOR emp_record IN emp_cursor LOOP -- implicit open and implicit fetch occur -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN IF emp_record.deptno = 30 THEN ... ... END LOOP; -- implicit close occurs END LOOP; -- implicit close occurs END; END;Copyright © 2004, Oracle. All rights reserved.
  • 289. Cursor FOR Loops Using Subqueries No need to declare the cursor. No need to declare the cursor. Example Example BEGIN BEGIN FOR emp_record IN ( SELECT ename, deptno FOR emp_record IN ( SELECT ename, deptno FROM FROM emp) LOOP emp) LOOP -- implicit open and implicit fetch occur -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN IF emp_record.deptno = 30 THEN ... ... END LOOP; -- implicit close occurs END LOOP; -- implicit close occurs END; END;Copyright © 2004, Oracle. All rights reserved.
  • 290. Advanced Explicit Cursor ConceptsCopyright © 2004, Oracle. All rights reserved.
  • 291. Cursors with Parameters Syntax CURSOR cursor_name CURSOR cursor_name [(parameter_name datatype, ...)] [(parameter_name datatype, ...)] IS IS select_statement; select_statement; – Pass parameter values to a cursor when the cursor is opened and the query is executed. – Open an explicit cursor several times with a different active set each time.Copyright © 2004, Oracle. All rights reserved.
  • 292. Cursors with Parameters Pass the department number and job title to the Pass the department number and job title to the WHERE clause. WHERE clause. Example Example DECLARE DECLARE CURSOR emp_cursor CURSOR emp_cursor (v_deptno NUMBER, v_job VARCHAR2) IS (v_deptno NUMBER, v_job VARCHAR2) IS SELECT SELECT empno, ename empno, ename FROM FROM emp emp WHERE WHERE deptno = v_deptno deptno = v_deptno AND AND job = v_job; job = v_job; BEGIN BEGIN OPEN emp_cursor(10, CLERK); OPEN emp_cursor(10, CLERK); ... ...Copyright © 2004, Oracle. All rights reserved.
  • 293. The FOR UPDATE Clause Syntax Syntax SELECT ... SELECT ... FROM FROM ... ... FOR UPDATE [OF column_reference][NOWAIT] FOR UPDATE [OF column_reference][NOWAIT] – – Explicit locking lets you deny access for the duration of Explicit locking lets you deny access for the duration of a transaction. a transaction. – – Lock the rows before the update or delete. Lock the rows before the update or delete.Copyright © 2004, Oracle. All rights reserved.
  • 294. The FOR UPDATE Clause Retrieve the employees who work in department 30. Retrieve the employees who work in department 30. Example Example DECLARE DECLARE CURSOR emp_cursor IS CURSOR emp_cursor IS SELECT empno, ename, sal SELECT empno, ename, sal FROM FROM emp emp WHERE deptno = 30 WHERE deptno = 30 FOR UPDATE NOWAIT; FOR UPDATE NOWAIT;Copyright © 2004, Oracle. All rights reserved.
  • 295. The WHERE CURRENT OF Clause Syntax WHERE CURRENT OF cursor WHERE CURRENT OF cursor – Use cursors to update or delete the current row. – Include the FOR UPDATE clause in the cursor query to lock the rows first. – Use the WHERE CURRENT OF clause to reference the current row from an explicit cursor.Copyright © 2004, Oracle. All rights reserved.
  • 296. The WHERE CURRENT OF Clause Example Example DECLARE DECLARE CURSOR sal_cursor IS CURSOR sal_cursor IS SELECT SELECT sal sal FROM FROM emp emp WHERE WHERE deptno = 30 deptno = 30 FOR UPDATE NOWAIT; FOR UPDATE NOWAIT; BEGIN BEGIN FOR emp_record IN sal_cursor LOOP FOR emp_record IN sal_cursor LOOP UPDATE UPDATE emp emp SET SET sal = emp_record.sal * 1.10 sal = emp_record.sal * 1.10 WHERE CURRENT OF sal_cursor; WHERE CURRENT OF sal_cursor; END LOOP; END LOOP; COMMIT; COMMIT; END; END;Copyright © 2004, Oracle. All rights reserved.
  • 297. Cursors with Subqueries Example Example DECLARE DECLARE CURSOR my_cursor IS CURSOR my_cursor IS SELECT t1.deptno, dname, STAFF SELECT t1.deptno, dname, STAFF FROM FROM dept t1, (SELECT deptno, dept t1, (SELECT deptno, count(*) STAFF count(*) STAFF FROM FROM emp emp GROUP BY deptno) t2 GROUP BY deptno) t2 WHERE t1.deptno = t2.deptno WHERE t1.deptno = t2.deptno AND AND STAFF >= 5; STAFF >= 5;Copyright © 2004, Oracle. All rights reserved.
  • 298. Handling ExceptionsCopyright © 2004, Oracle. All rights reserved.
  • 299. Handling Exceptions with PL/SQL – – What is an exception? What is an exception? Identifier in PL/SQL that is raised during execution Identifier in PL/SQL that is raised during execution – – How is it raised? How is it raised? An Oracle error occurs. An Oracle error occurs. You raise it explicitly. You raise it explicitly. – – How do you handle it? How do you handle it? Trap it with a handler. Trap it with a handler. Propagate it to the calling environment. Propagate it to the calling environment.Copyright © 2004, Oracle. All rights reserved.
  • 300. Handling Exceptions Trap the exception Propagate the exception DECLARE DECLARE BEGIN BEGIN Exception Exception is raised is raised EXCEPTION EXCEPTION Exception Exception is is trapped END; END; not trapped Exception propagates to calling environmentCopyright © 2004, Oracle. All rights reserved.
  • 301. Exception Types – – Predefined Oracle Server Predefined Oracle Server – – – – Non-predefined Oracle Server Non-predefined Oracle Server User-defined User-defined } Implicitly raised Explicitly raisedCopyright © 2004, Oracle. All rights reserved.
  • 302. Trapping Exceptions Syntax Syntax EXCEPTION EXCEPTION WHEN exception1 [OR exception2 . . .] THEN WHEN exception1 [OR exception2 . . .] THEN statement1; statement1; statement2; statement2; . . . . . . [WHEN exception3 [OR exception4 . . .] THEN [WHEN exception3 [OR exception4 . . .] THEN statement1; statement1; statement2; statement2; . . .] . . .] [WHEN OTHERS THEN [WHEN OTHERS THEN statement1; statement1; statement2; statement2; . . .] . . .]Copyright © 2004, Oracle. All rights reserved.
  • 303. Trapping Exceptions Guidelines – – WHEN OTHERS is the last clause. WHEN OTHERS is the last clause. – – EXCEPTION keyword starts exception-handling EXCEPTION keyword starts exception-handling section. section. – – Several exception handlers are allowed. Several exception handlers are allowed. – – Only one handler is processed before leaving the Only one handler is processed before leaving the block. block.Copyright © 2004, Oracle. All rights reserved.
  • 304. Trapping Predefined Oracle Server Errors – – Reference the standard name in the exception- Reference the standard name in the exception- handling routine. handling routine. – – Sample predefined exceptions: Sample predefined exceptions: NO_DATA_FOUND NO_DATA_FOUND TOO_MANY_ROWS TOO_MANY_ROWS INVALID_CURSOR INVALID_CURSOR ZERO_DIVIDE ZERO_DIVIDE DUP_VAL_ON_INDEX DUP_VAL_ON_INDEXCopyright © 2004, Oracle. All rights reserved.
  • 305. Predefined Exception Syntax Syntax BEGIN SELECT ... COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN statement1; statement2; WHEN TOO_MANY_ROWS THEN statement1; WHEN OTHERS THEN statement1; statement2; statement3; END;Copyright © 2004, Oracle. All rights reserved.
  • 306. Trapping Non-Predefined Oracle Server Errors Declare Associate Reference Declarative section Exception-handling section • Name the • Code the PRAGMA • Handle the exception EXCEPTION_INIT raised exceptionCopyright © 2004, Oracle. All rights reserved.
  • 307. Non-Predefined Error Trap for Oracle Server error number Trap for Oracle Server error number –2292, an integrity constraint violation. –2292, an integrity constraint violation. DECLARE DECLARE e_emps_remaining EXCEPTION; EXCEPTION; e_emps_remaining EXCEPTION; e_emps_remaining 1 PRAGMA EXCEPTION_INIT ( PRAGMA EXCEPTION_INIT ( PRAGMA EXCEPTION_INIT ( e_emps_remaining, -2292); e_emps_remaining, -2292); e_emps_remaining, -2292); 2 v_deptno v_deptno dept.deptno%TYPE := &p_deptno; dept.deptno%TYPE := &p_deptno; BEGIN BEGIN DELETE FROM dept DELETE FROM dept WHERE WHERE deptno = v_deptno; deptno = v_deptno; COMMIT; COMMIT; EXCEPTION EXCEPTION WHEN e_emps_remaining THEN WHEN e_emps_remaining THEN 3 DBMS_OUTPUT.PUT_LINE (Cannot remove dept || DBMS_OUTPUT.PUT_LINE (Cannot remove dept || TO_CHAR(v_deptno) || . Employees exist. ); TO_CHAR(v_deptno) || . Employees exist. ); END; END;Copyright © 2004, Oracle. All rights reserved.
  • 308. Trapping User-Defined Exceptions Declare Raise Reference Declarative Executable Exception-handling section section section• Name the • Explicitly raise • Handle the exception the exception by raised using the RAISE exception statementCopyright © 2004, Oracle. All rights reserved.
  • 309. User-Defined Exception Example Example DECLARE DECLARE EXCEPTION; e_invalid_product EXCEPTION; e_invalid_product EXCEPTION; 1 BEGIN BEGIN UPDATE UPDATE product product SET SET descrip = &product_description descrip = &product_description WHERE WHERE prodid = &product_number; prodid = &product_number; IF SQL%NOTFOUND THEN IF SQL%NOTFOUND THEN RAISE e_invalid_product; RAISE e_invalid_product; 2 END IF; END IF; COMMIT; COMMIT; EXCEPTION EXCEPTION e_invalid_product WHEN e_invalid_product THEN WHEN e_invalid_product THEN 3 DBMS_OUTPUT.PUT_LINE(Invalid product number.); DBMS_OUTPUT.PUT_LINE(Invalid product number.); END; END;Copyright © 2004, Oracle. All rights reserved.
  • 310. Functions for Trapping Exceptions – – SQLCODE SQLCODE Returns the numeric value for the error code Returns the numeric value for the error code – – SQLERRM SQLERRM Returns the message associated with the error number Returns the message associated with the error numberCopyright © 2004, Oracle. All rights reserved.
  • 311. Functions for Trapping Exceptions Example Example DECLARE v_error_code NUMBER; v_error_message VARCHAR2(255); BEGIN ... EXCEPTION ... WHEN OTHERS THEN ROLLBACK; v_error_code := SQLCODE ; v_error_message := SQLERRM ; INSERT INTO errors VALUES(v_error_code, v_error_message); END;Copyright © 2004, Oracle. All rights reserved.
  • 312. Calling Environments SQL*Plus Displays error number and message to screen Procedure Displays error number and message Builder to screen Accesses error number and message Oracle in a trigger by means of the Developer ERROR_CODE and ERROR_TEXT Forms packaged functions Precompiler Accesses exception number through application the SQLCA data structure An enclosing Traps exception in exception- PL/SQL block handling routine of enclosing blockCopyright © 2004, Oracle. All rights reserved.
  • 313. Copyright © 2004, Oracle. All rights reserved.
  • 314. RAISE_APPLICATION_ERROR Procedure Syntax Syntax raise_application_error (error_number, raise_application_error (error_number, message[, {TRUE | FALSE}]); message[, {TRUE | FALSE}]); – – A procedure that lets you issue user-defined error A procedure that lets you issue user-defined error messages from stored subprograms messages from stored subprograms – – Called only from an executing stored subprogram Called only from an executing stored subprogramCopyright © 2004, Oracle. All rights reserved.
  • 315. RAISE_APPLICATION_ERROR Procedure – – Used in two different places: Used in two different places: Executable section Executable section Exception section Exception section – – Returns error conditions to the user in a manner Returns error conditions to the user in a manner consistent with other Oracle Server errors consistent with other Oracle Server errorsCopyright © 2004, Oracle. All rights reserved.
  • 316. Copyright © 2004, Oracle. All rights reserved.
  • 317. Procedure and FunctionCopyright © 2004, Oracle. All rights reserved.
  • 318. Copyright © 2004, Oracle. All rights reserved.
  • 319. Copyright © 2004, Oracle. All rights reserved.
  • 320. Copyright © 2004, Oracle. All rights reserved.
  • 321. Copyright © 2004, Oracle. All rights reserved.
  • 322. Copyright © 2004, Oracle. All rights reserved.
  • 323. Copyright © 2004, Oracle. All rights reserved.
  • 324. Copyright © 2004, Oracle. All rights reserved.
  • 325. Copyright © 2004, Oracle. All rights reserved.
  • 326. Copyright © 2004, Oracle. All rights reserved.
  • 327. Copyright © 2004, Oracle. All rights reserved.
  • 328. Copyright © 2004, Oracle. All rights reserved.
  • 329. Copyright © 2004, Oracle. All rights reserved.
  • 330. Copyright © 2004, Oracle. All rights reserved.
  • 331. Copyright © 2004, Oracle. All rights reserved.
  • 332. Copyright © 2004, Oracle. All rights reserved.
  • 333. Copyright © 2004, Oracle. All rights reserved.
  • 334. Copyright © 2004, Oracle. All rights reserved.
  • 335. Copyright © 2004, Oracle. All rights reserved.
  • 336. Copyright © 2004, Oracle. All rights reserved.
  • 337. Copyright © 2004, Oracle. All rights reserved.
  • 338. Copyright © 2004, Oracle. All rights reserved.
  • 339. Copyright © 2004, Oracle. All rights reserved.
  • 340. Copyright © 2004, Oracle. All rights reserved.
  • 341. Copyright © 2004, Oracle. All rights reserved.
  • 342. Copyright © 2004, Oracle. All rights reserved.
  • 343. Copyright © 2004, Oracle. All rights reserved.
  • 344. Copyright © 2004, Oracle. All rights reserved.
  • 345. Copyright © 2004, Oracle. All rights reserved.
  • 346. Copyright © 2004, Oracle. All rights reserved.
  • 347. Copyright © 2004, Oracle. All rights reserved.
  • 348. Copyright © 2004, Oracle. All rights reserved.
  • 349. Copyright © 2004, Oracle. All rights reserved.
  • 350. PackageCopyright © 2004, Oracle. All rights reserved.
  • 351. Copyright © 2004, Oracle. All rights reserved.
  • 352. Copyright © 2004, Oracle. All rights reserved.
  • 353. Copyright © 2004, Oracle. All rights reserved.
  • 354. Copyright © 2004, Oracle. All rights reserved.
  • 355. Copyright © 2004, Oracle. All rights reserved.
  • 356. Copyright © 2004, Oracle. All rights reserved.
  • 357. Copyright © 2004, Oracle. All rights reserved.
  • 358. Copyright © 2004, Oracle. All rights reserved.
  • 359. Copyright © 2004, Oracle. All rights reserved.
  • 360. Copyright © 2004, Oracle. All rights reserved.
  • 361. Copyright © 2004, Oracle. All rights reserved.
  • 362. Copyright © 2004, Oracle. All rights reserved.
  • 363. Copyright © 2004, Oracle. All rights reserved.
  • 364. Copyright © 2004, Oracle. All rights reserved.
  • 365. Copyright © 2004, Oracle. All rights reserved.
  • 366. Copyright © 2004, Oracle. All rights reserved.
  • 367. Copyright © 2004, Oracle. All rights reserved.
  • 368. Copyright © 2004, Oracle. All rights reserved.
  • 369. Copyright © 2004, Oracle. All rights reserved.
  • 370. Copyright © 2004, Oracle. All rights reserved.
  • 371. Copyright © 2004, Oracle. All rights reserved.
  • 372. Copyright © 2004, Oracle. All rights reserved.
  • 373. Copyright © 2004, Oracle. All rights reserved.
  • 374. Copyright © 2004, Oracle. All rights reserved.
  • 375. Copyright © 2004, Oracle. All rights reserved.
  • 376. Copyright © 2004, Oracle. All rights reserved.
  • 377. Copyright © 2004, Oracle. All rights reserved.
  • 378. Copyright © 2004, Oracle. All rights reserved.
  • 379. Copyright © 2004, Oracle. All rights reserved.
  • 380. Copyright © 2004, Oracle. All rights reserved.
  • 381. Copyright © 2004, Oracle. All rights reserved.
  • 382. Copyright © 2004, Oracle. All rights reserved.
  • 383. Copyright © 2004, Oracle. All rights reserved.
  • 384. Copyright © 2004, Oracle. All rights reserved.
  • 385. Copyright © 2004, Oracle. All rights reserved.
  • 386. Copyright © 2004, Oracle. All rights reserved.
  • 387. Copyright © 2004, Oracle. All rights reserved.
  • 388. Copyright © 2004, Oracle. All rights reserved.
  • 389. TriggerCopyright © 2004, Oracle. All rights reserved.
  • 390. Copyright © 2004, Oracle. All rights reserved.
  • 391. Copyright © 2004, Oracle. All rights reserved.
  • 392. Copyright © 2004, Oracle. All rights reserved.
  • 393. Copyright © 2004, Oracle. All rights reserved.
  • 394. Copyright © 2004, Oracle. All rights reserved.
  • 395. Copyright © 2004, Oracle. All rights reserved.
  • 396. Copyright © 2004, Oracle. All rights reserved.
  • 397. Copyright © 2004, Oracle. All rights reserved.
  • 398. Copyright © 2004, Oracle. All rights reserved.
  • 399. Copyright © 2004, Oracle. All rights reserved.
  • 400. Copyright © 2004, Oracle. All rights reserved.
  • 401. Copyright © 2004, Oracle. All rights reserved.
  • 402. Copyright © 2004, Oracle. All rights reserved.
  • 403. Copyright © 2004, Oracle. All rights reserved.
  • 404. Copyright © 2004, Oracle. All rights reserved.
  • 405. Copyright © 2004, Oracle. All rights reserved.
  • 406. Copyright © 2004, Oracle. All rights reserved.
  • 407. Managing DependenciesCopyright © 2004, Oracle. All rights reserved.
  • 408. Copyright © 2004, Oracle. All rights reserved.
  • 409. Copyright © 2004, Oracle. All rights reserved.
  • 410. Copyright © 2004, Oracle. All rights reserved.
  • 411. Copyright © 2004, Oracle. All rights reserved.
  • 412. Q U E S T I O N S A N S W E R SCopyright © 2004, Oracle. All rights reserved.