Introduction
Lesson Objectives <ul><li>After completing this lesson, you should be able to do the following:  </li></ul><ul><ul><li>Lis...
Retrieving Data Using  the SQL  SELECT  Statement
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>List the ca...
Capabilities of SQL  SELECT  Statements Selection Projection Table 1 Table 2 Table 1 Table 1 Join
Basic  SELECT  Statement <ul><ul><li>SELECT  identifies the columns to be displayed. </li></ul></ul><ul><ul><li>FROM  iden...
Selecting All Columns SELECT * FROM  departments;
Selecting Specific Columns SELECT department_id, location_id FROM  departments;
Writing SQL Statements <ul><ul><li>SQL statements are not case sensitive.  </li></ul></ul><ul><ul><li>SQL statements can b...
Column Heading Defaults <ul><ul><li>i SQL*Plus: </li></ul></ul><ul><ul><ul><li>Default heading alignment: Center </li></ul...
Arithmetic Expressions <ul><li>Create expressions with number and date data by using arithmetic operators. </li></ul>Multi...
Using Arithmetic Operators SELECT last_name, salary, salary + 300 FROM  employees; …
Operator Precedence SELECT last_name, salary, 12*salary+100 FROM  employees; SELECT last_name, salary, 12*(salary+100)‏ FR...
Defining a Null Value <ul><ul><li>A null is a value that is unavailable, unassigned, unknown, or inapplicable. </li></ul><...
Null Values  in Arithmetic Expressions <ul><li>Arithmetic expressions containing a null value evaluate to null. </li></ul>...
Defining a Column Alias <ul><li>A column alias: </li></ul><ul><ul><li>Renames a column heading </li></ul></ul><ul><ul><li>...
Using Column Aliases SELECT last_name &quot;Name&quot; , salary*12 &quot;Annual Salary&quot; FROM  employees; SELECT last_...
Concatenation Operator <ul><li>A concatenation operator: </li></ul><ul><ul><li>Links columns or character strings to other...
Literal Character Strings <ul><ul><li>A literal is a character, a number, or a date that is included in the  SELECT  state...
Using Literal Character Strings … SELECT last_name ||' is a '||job_id  AS &quot;Employee Details&quot; FROM  employees;
Alternative Quote ( q ) Operator <ul><ul><li>Specify your own quotation mark delimiter </li></ul></ul><ul><ul><li>Choose a...
Duplicate Rows <ul><li>The default display of queries is all rows, including duplicate rows. </li></ul>SELECT department_i...
Displaying Table Structure <ul><li>Use the  i SQL*Plus  DESCRIBE  command to display the structure of a table: </li></ul>D...
Displaying Table Structure DESCRIBE employees
Summary <ul><li>In this lesson, you should have learned how to:  </li></ul><ul><ul><li>Write a  SELECT  statement that: </...
Restricting and Sorting Data
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Limit the r...
Limiting Rows Using a Selection “ retrieve all employees in department 90” EMPLOYEES …
Limiting the Rows That Are Selected <ul><ul><li>Restrict the rows that are returned by using the  WHERE  clause: </li></ul...
Using the  WHERE  Clause SELECT employee_id, last_name, job_id, department_id FROM  employees WHERE  department_id = 90 ;
Character Strings and Dates <ul><ul><li>Character strings and date values are enclosed in single quotation marks. </li></u...
Comparison Conditions Not equal to <ul><ul><li><> </li></ul></ul>Between two values (inclusive)‏ BETWEEN ...AND... Match a...
Using Comparison Conditions SELECT last_name, salary FROM  employees WHERE  salary <= 3000 ;
Using the  BETWEEN  Condition <ul><li>Use the  BETWEEN  condition to display rows based on a range of values: </li></ul>SE...
Using the  IN  Condition <ul><li>Use the  IN  membership condition to test for values in a list: </li></ul>SELECT employee...
Using the  LIKE  Condition <ul><ul><li>Use the  LIKE  condition to perform wildcard searches of valid search string values...
<ul><ul><li>You can combine pattern-matching characters: </li></ul></ul><ul><ul><li>You can use the  ESCAPE  identifier to...
Using the  NULL  Conditions <ul><li>Test for nulls with the  IS NULL  operator. </li></ul>SELECT last_name, manager_id FRO...
Logical Conditions Returns  TRUE  if the following condition is false NOT Returns  TRUE  if  either  component condition i...
Using the  AND  Operator SELECT employee_id, last_name, job_id, salary FROM  employees WHERE  salary >=10000 AND  job_id L...
Using the  OR  Operator SELECT employee_id, last_name, job_id, salary FROM  employees WHERE  salary >= 10000 OR  job_id LI...
Using the  NOT  Operator SELECT last_name, job_id FROM  employees WHERE  job_id  NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
Rules of Precedence You can use parentheses to override rules of precedence. Not equal to <ul><ul><li>6 </li></ul></ul>NOT...
Rules of Precedence SELECT last_name, job_id, salary FROM  employees WHERE  job_id = 'SA_REP' OR  job_id = 'AD_PRES' AND  ...
Using the  ORDER BY  Clause <ul><ul><li>Sort retrieved rows with the  ORDER BY  clause: </li></ul></ul><ul><ul><ul><li>ASC...
Sorting <ul><ul><li>Sorting in descending order: </li></ul></ul><ul><ul><li>Sorting by column alias: </li></ul></ul><ul><u...
Summary <ul><li>In this lesson, you should have learned how to:  </li></ul><ul><ul><li>Use the  WHERE  clause to restrict ...
Displaying Data  from Multiple Tables
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Write  SELE...
Obtaining Data from Multiple Tables EMPLOYEES   DEPARTMENTS  … …
Types of Joins <ul><li>Joins that are compliant with the SQL:1999 standard include the following: </li></ul><ul><ul><li>Cr...
Joining Tables Using SQL:1999 Syntax <ul><li>Use a join to query data from more than one table: </li></ul>SELECT table1.co...
Creating Natural Joins <ul><ul><li>The  NATURAL   JOIN  clause is based on all columns in the two tables that have the sam...
Retrieving Records with Natural Joins SELECT department_id, department_name, location_id, city FROM  departments NATURAL J...
Creating Joins with the  USING  Clause <ul><ul><li>If several columns have the same names but the data types do not match,...
Joining Column Names EMPLOYEES   DEPARTMENTS  Foreign key Primary key … …
Retrieving Records with the  USING  Clause SELECT employees.employee_id, employees.last_name,  departments.location_id, de...
Qualifying Ambiguous  Column Names <ul><ul><li>Use table prefixes to qualify column names that are in multiple tables. </l...
Using Table Aliases <ul><ul><li>Use table aliases to simplify queries. </li></ul></ul><ul><ul><li>Use table aliases to imp...
Creating Joins with the  ON  Clause <ul><ul><li>The join condition for the natural join is basically an equijoin of all co...
Retrieving Records with the  ON  Clause SELECT e.employee_id, e.last_name, e.department_id,  d.department_id, d.location_i...
Self-Joins Using the  ON  Clause MANAGER_ID  in the  WORKER  table is equal to  EMPLOYEE_ID  in the  MANAGER  table. EMPLO...
Self-Joins Using the  ON  Clause SELECT e.last_name emp, m.last_name mgr FROM  employees e JOIN employees m ON  (e.manager...
Applying Additional Conditions to a Join SELECT e.employee_id, e.last_name, e.department_id,  d.department_id, d.location_...
Creating Three-Way Joins with the  ON  Clause SELECT employee_id, city, department_name FROM  employees e  JOIN  departmen...
Nonequijoins EMPLOYEES JOB_GRADES Salary in the  EMPLOYEES   table must be between  lowest salary and highest  salary in t...
Retrieving Records  with Nonequijoins SELECT e.last_name, e.salary, j.grade_level FROM  employees e JOIN job_grades j ON  ...
Outer Joins EMPLOYEES DEPARTMENTS There are no employees in department 190.  …
INNER  Versus  OUTER  Joins <ul><ul><li>In SQL:1999, the join of two tables returning only matched rows is called an inner...
LEFT OUTER JOIN SELECT e.last_name, e.department_id, d.department_name FROM  employees e LEFT OUTER JOIN departments d ON ...
RIGHT OUTER JOIN SELECT e.last_name, e.department_id, d.department_name FROM  employees e RIGHT OUTER JOIN departments d O...
FULL OUTER JOIN SELECT e.last_name, d.department_id, d.department_name FROM  employees e FULL OUTER JOIN departments d ON ...
Cartesian Products <ul><ul><li>A Cartesian product is formed when: </li></ul></ul><ul><ul><ul><li>A join condition is omit...
Generating a Cartesian Product Cartesian product:  20 x 8 = 160 rows EMPLOYEES   (20 rows) DEPARTMENTS   (8 rows) … …
Creating   Cross   Joins <ul><ul><li>The  CROSS   JOIN  clause produces the cross-product of two tables.  </li></ul></ul><...
Summary <ul><li>In this lesson, you should have learned how to use joins to display data from multiple tables by using: </...
Manipulating Data
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Describe ea...
Data Manipulation Language <ul><ul><li>A DML statement is executed when you: </li></ul></ul><ul><ul><ul><li>Add new rows t...
Adding a New Row to a Table DEPARTMENTS  New  row Insert new row into the DEPARTMENTS   table
INSERT  Statement Syntax <ul><ul><li>Add new rows to a table by using the  INSERT  statement: </li></ul></ul><ul><ul><li>W...
Inserting New Rows <ul><ul><li>Insert a new row containing values for each column. </li></ul></ul><ul><ul><li>List values ...
Inserting Rows with Null Values <ul><ul><li>Implicit method: Omit the column from the  column list. </li></ul></ul>INSERT ...
Inserting Special Values <ul><li>The  SYSDATE  function records the current date and time. </li></ul>INSERT INTO employees...
<ul><ul><li>Add a new employee. </li></ul></ul><ul><ul><li>Verify your addition. </li></ul></ul>Inserting Specific Date Va...
Copying Rows  from Another Table <ul><ul><li>Write your  INSERT  statement with a subquery: </li></ul></ul><ul><ul><li>Do ...
Changing Data in a Table EMPLOYEES Update rows in the  EMPLOYEES  table:
<ul><ul><li>Modify existing rows with the  UPDATE  statement: </li></ul></ul><ul><ul><li>Update more than one row at a tim...
<ul><ul><li>Specific row or rows are modified if you specify the  WHERE  clause: </li></ul></ul><ul><ul><li>All rows in th...
Removing a Row from a Table  Delete a row from the  DEPARTMENTS  table: DEPARTMENTS
DELETE  Statement <ul><li>You can remove existing rows from a table by using the  DELETE  statement: </li></ul>DELETE [FRO...
Deleting Rows from a Table <ul><ul><li>Specific rows are deleted if you specify the  WHERE  clause: </li></ul></ul><ul><ul...
Database Transactions <ul><li>A database transaction consists of one of the following: </li></ul><ul><ul><li>DML statement...
Database Transactions <ul><ul><li>Begin when the first DML SQL statement is executed </li></ul></ul><ul><ul><li>End with o...
Advantages of  COMMIT   and  ROLLBACK  Statements <ul><li>With  COMMIT  and  ROLLBACK  statements, you can:  </li></ul><ul...
Controlling Transactions SAVEPOINT   B SAVEPOINT   A DELETE INSERT UPDATE INSERT COMMIT Time Transaction ROLLBACK  to SAVE...
Rolling Back Changes to a Marker <ul><ul><li>Create a marker in a current transaction by using the  SAVEPOINT  statement. ...
Implicit Transaction Processing <ul><ul><li>An automatic commit occurs under the following circumstances: </li></ul></ul><...
 
State of the Data  Before  COMMIT  or  ROLLBACK <ul><ul><li>The previous state of the data can be recovered. </li></ul></u...
State of the Data After  COMMIT <ul><ul><li>Data changes are made permanent in the database. </li></ul></ul><ul><ul><li>Th...
Committing Data <ul><ul><li>Make the changes: </li></ul></ul><ul><ul><li>Commit the changes: </li></ul></ul>COMMIT; Commit...
State of the Data After  ROLLBACK <ul><li>Discard all pending changes by using the  ROLLBACK  statement: </li></ul><ul><ul...
State of the Data After  ROLLBACK DELETE FROM test; 25,000 rows deleted. ROLLBACK; Rollback complete. DELETE FROM test WHE...
Statement-Level Rollback <ul><ul><li>If a single DML statement fails during execution, only that statement is rolled back....
Summary <ul><li>In this lesson, you should have learned how to use the following statements: </li></ul>Adds a new row to t...
Using DDL Statements to Create and Manage Tables
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Categorize ...
Database Objects Logically represents subsets of data from one or more tables  View  Generates numeric values Sequence  Ba...
Naming Rules <ul><li>Table names and column names: </li></ul><ul><ul><li>Must begin with a letter </li></ul></ul><ul><ul><...
<ul><ul><li>You must have: </li></ul></ul><ul><ul><ul><li>CREATE TABLE  privilege </li></ul></ul></ul><ul><ul><ul><li>A st...
Referencing Another User’s Tables <ul><ul><li>Tables belonging to other users are not in the user’s schema. </li></ul></ul...
<ul><ul><li>Specify a default value for a column during an insert. </li></ul></ul><ul><ul><li>Literal values, expressions,...
Creating Tables <ul><ul><li>Create the table. </li></ul></ul><ul><ul><li>Confirm table creation. </li></ul></ul>DESCRIBE d...
Data Types Raw binary data RAW and LONG RAW   Binary data (up to 4 GB) BLOB Binary data stored in an external file (up to ...
 
Datetime Data Types <ul><li>You can use several datetime data types: </li></ul>Stored as an interval of years and months I...
Datetime Data Types <ul><ul><li>The  TIMESTAMP  data type is an extension of the  DATE  data type. </li></ul></ul><ul><ul>...
 
Datetime Data Types <ul><ul><li>The  INTERVAL   YEAR   TO   MONTH  data type stores a period of time using the  YEAR  and ...
 
INTERVAL DAY TO SECOND  Data Type <ul><li>INTERVAL DAY TO SECOND  stores a period of time in terms of days, hours, minutes...
Including Constraints <ul><ul><li>Constraints enforce rules at the table level. </li></ul></ul><ul><ul><li>Constraints pre...
Constraint Guidelines <ul><ul><li>You can name a constraint, or the Oracle server generates a name by using the  SYS_C n  ...
<ul><ul><li>Syntax: </li></ul></ul><ul><ul><li>Column-level constraint: </li></ul></ul><ul><ul><li>Table-level constraint:...
Defining Constraints <ul><ul><li>Column-level constraint:  </li></ul></ul><ul><ul><li>Table-level constraint: </li></ul></...
NOT NULL  Constraint <ul><li>Ensures that null values are not permitted for the column: </li></ul>NOT NULL  constraint (No...
UNIQUE  Constraint EMPLOYEES  UNIQUE  constraint INSERT INTO Not allowed: already exists Allowed …
UNIQUE  Constraint <ul><li>Defined at either the table level or the column level:  </li></ul>CREATE TABLE employees( emplo...
PRIMARY KEY  Constraint DEPARTMENTS   PRIMARY KEY INSERT INTO Not allowed (null value) Not allowed  (50 already exists) …
FOREIGN KEY  Constraint DEPARTMENTS   EMPLOYEES FOREIGN KEY INSERT INTO Not allowed (9 does not exist) Allowed PRIMARY KEY...
FOREIGN KEY  Constraint <ul><li>Defined at either the table level or the column level: </li></ul>CREATE TABLE employees( e...
FOREIGN KEY  Constraint: Keywords <ul><ul><li>FOREIGN KEY : Defines the column in the child table at the table-constraint ...
CHECK  Constraint <ul><ul><li>Defines a condition that each row must satisfy </li></ul></ul><ul><ul><li>The following expr...
CREATE TABLE : Example CREATE TABLE employees ( employee_id  NUMBER(6) CONSTRAINT  emp_employee_id  PRIMARY KEY , first_na...
Violating Constraints  <ul><li>Department 55 does not exist. </li></ul>UPDATE employees * ERROR at line 1: ORA-02291: inte...
Violating Constraints <ul><li>You cannot delete a row that contains a primary key that is used as a foreign key in another...
Creating a Table by Using a Subquery <ul><ul><li>Create a table and insert rows by combining the  CREATE TABLE  statement ...
Creating a Table by Using a Subquery CREATE TABLE  dept80 AS    SELECT  employee_id, last_name,  salary*12 ANNSAL,  hire_d...
ALTER TABLE  Statement <ul><li>Use the  ALTER   TABLE  statement to: </li></ul><ul><ul><li>Add a new column </li></ul></ul...
Dropping a Table <ul><ul><li>All data and structure in the table are deleted. </li></ul></ul><ul><ul><li>Any pending trans...
Summary <ul><li>In this lesson, you should have learned how to use the  CREATE TABLE  statement to create a table and incl...
Introduction to PL/SQL
Lesson Objectives <ul><li>After completing this lesson, you should be able to do the following:  </li></ul><ul><ul><li>Exp...
What Is PL/SQL? <ul><li>PL/SQL: </li></ul><ul><ul><li>Stands for Procedural Language extension to SQL </li></ul></ul><ul><...
About PL/SQL <ul><li>PL/SQL: </li></ul><ul><ul><li>Provides a block structure for executable units of code. Maintenance of...
PL/SQL Environment PL/SQL Engine Oracle Database Server SQL Statement  Executor Procedural  Statement  Executor procedural...
Benefits of PL/SQL SQL IF...THEN SQL ELSE SQL END IF; SQL <ul><ul><li>Integration of procedural constructs with SQL </li><...
Benefits of PL/SQL <ul><ul><li>Modularized program development </li></ul></ul><ul><ul><li>Integration with Oracle tools </...
Benefits of PL/SQL
PL/SQL Block Structure <ul><li>DECLARE  (Optional) </li></ul><ul><ul><li>Variables, cursors, user-defined exceptions </li>...
PL/SQL Block Structure
Block Types <ul><li>Anonymous Procedure Function </li></ul>[DECLARE] BEGIN --statements [EXCEPTION] END; PROCEDURE name IS...
Block Types
Program Constructs Application triggers Application packages Application procedures or functions Anonymous blocks Tools Co...
Program Constructs
Create an Anonymous Block <ul><li>Type the anonymous block in the  i SQL*Plus workspace: </li></ul>
Execute an Anonymous Block <ul><li>Click the Execute button to execute the anonymous block: </li></ul>PLSQL procedure succ...
Test the Output of a PL/SQL Block <ul><ul><li>Enable output in  i SQL*Plus with the command SET SERVEROUTPUT ON </li></ul>...
Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Integrate SQL statements with PL/SQL...
Declaring PL/SQL Variables
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Identify va...
Use of Variables <ul><li>Variables can be used for: </li></ul><ul><ul><li>Temporary storage of data </li></ul></ul><ul><ul...
Identifiers <ul><li>Identifiers are used for: </li></ul><ul><ul><li>Naming a variable </li></ul></ul><ul><ul><li>Providing...
Handling Variables in PL/SQL <ul><li>Variables are: </li></ul><ul><ul><li>Declared and initialized in the declarative sect...
Declaring and Initializing PL/SQL Variables Syntax: Examples: identifier  [CONSTANT]  datatype  [NOT NULL]  [:= | DEFAULT ...
Declaring and Initializing PL/SQL Variables SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20); BEGIN   DBMS_OUTPUT.PUT_LINE(...
Delimiters in String Literals SET SERVEROUTPUT ON DECLARE event VARCHAR2(15); BEGIN event := q'!Father's day!'; DBMS_OUTPU...
Types of Variables <ul><ul><li>PL/SQL variables: </li></ul></ul><ul><ul><ul><li>Scalar </li></ul></ul></ul><ul><ul><ul><li...
Types of Variables TRUE 25-JAN-01 Atlanta 256120.08 The soul of the lazy man   desires, and has nothing;   but the soul of...
Guidelines for Declaring and Initializing PL/SQL Variables <ul><ul><li>Follow naming conventions. </li></ul></ul><ul><ul><...
Guidelines for Declaring PL/SQL Variables <ul><ul><li>Avoid using column names as identifiers. </li></ul></ul>DECLARE empl...
Scalar Data Types <ul><ul><li>Hold a single value </li></ul></ul><ul><ul><li>Have no internal components </li></ul></ul>At...
Base Scalar Data Types <ul><ul><li>CHAR [(maximum_length)] </li></ul></ul><ul><ul><li>VARCHAR2 (maximum_length) </li></ul>...
 
Base Scalar Data Types <ul><ul><li>DATE </li></ul></ul><ul><ul><li>TIMESTAMP </li></ul></ul><ul><ul><li>TIMESTAMP WITH TIM...
 
BINARY_FLOAT  and  BINARY_DOUBLE <ul><ul><li>Represent floating point numbers in IEEE (Institute of Electrical and Electro...
BINARY_FLOAT  and  BINARY_DOUBLE
Declaring Scalar Variables  <ul><li>Examples: </li></ul>DECLARE emp_job VARCHAR2(9); count_loop   BINARY_INTEGER := 0; dep...
The  %TYPE  Attribute <ul><li>The  %TYPE  attribute </li></ul><ul><ul><li>Is used to declare a variable according to:  </l...
The  %TYPE  Attribute
Declaring Variables  with the  %TYPE  Attribute <ul><li>Syntax: </li></ul><ul><li>Examples: </li></ul>... emp_lname  emplo...
Declaring Boolean Variables <ul><ul><li>Only the values  TRUE ,   FALSE , and  NULL  can be assigned to a Boolean variable...
Bind Variables <ul><li>Bind variables are: </li></ul><ul><ul><li>Created in the environment  </li></ul></ul><ul><ul><li>Al...
 
Printing Bind Variables <ul><li>Example: </li></ul>VARIABLE emp_salary NUMBER BEGIN SELECT salary  INTO :emp_salary  FROM ...
Printing Bind Variables <ul><li>Example: </li></ul>VARIABLE emp_salary NUMBER SET AUTOPRINT ON BEGIN SELECT salary  INTO :...
Substitution Variables <ul><ul><li>Are used to get user input at run time  </li></ul></ul><ul><ul><li>Are referenced withi...
Substitution Variables 1 2 3
Prompt for Substitution Variables SET VERIFY OFF VARIABLE emp_salary NUMBER ACCEPT empno PROMPT 'Please enter a valid empl...
Using  DEFINE  for User Variable <ul><li>Example: </li></ul>SET VERIFY OFF DEFINE lname= Urman DECLARE fname VARCHAR2(25);...
Composite Data Types  TRUE  23-DEC-98 ATLANTA  1 5000  2 2345  3 12  4 3456 1 SMITH  2 JONES  3 NANCY  4 TIM PL/SQL table ...
LOB  Data Type Variables Book ( CLOB ) Photo ( BLOB ) Movie ( BFILE ) NCLOB
Summary <ul><li>In this lesson, you should have learned how to:  </li></ul><ul><ul><li>Identify valid and invalid identifi...
Interacting with the Oracle Server
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Decide whic...
SQL Statements in PL/SQL <ul><ul><li>Retrieve a row from the database by using the  SELECT  command.  </li></ul></ul><ul><...
SQL Statements in PL/SQL
SELECT  Statements in PL/SQL <ul><li>Retrieve data from the database with a  SELECT   statement. </li></ul><ul><li>Syntax:...
 
SELECT  Statements in PL/SQL <ul><ul><li>The  INTO  clause is required. </li></ul></ul><ul><ul><li>Queries must return onl...
SELECT  Statements in PL/SQL
Retrieving Data in PL/SQL <ul><li>Retrieve the  hire_date  and the  salary  for the specified employee. </li></ul><ul><li>...
Retrieving Data in PL/SQL <ul><li>Return the sum of the salaries for all the employees in the specified department. </li><...
Naming Conventions <ul><li>DECLARE </li></ul><ul><li>hire_date  employees.hire_date%TYPE; </li></ul><ul><li>sysdate  hire_...
Naming Conventions <ul><ul><li>Use a naming convention to avoid ambiguity in the  WHERE  clause. </li></ul></ul><ul><ul><l...
Manipulating Data Using PL/SQL <ul><li>Make changes to database tables by using DML commands: </li></ul><ul><ul><li>INSERT...
Inserting Data <ul><li>Add new employee information to the  EMPLOYEES  table. </li></ul><ul><li>Example: </li></ul>BEGIN I...
Updating Data <ul><li>Increase the salary of all employees who are stock clerks. </li></ul><ul><li>Example: </li></ul>DECL...
Deleting Data <ul><li>Delete rows that belong to department 10 from the  employees  table. </li></ul><ul><li>Example: </li...
Merging Rows <ul><li>Insert or update rows in the  copy_emp  table to match the  employees  table. </li></ul>DECLARE empno...
 
SQL Cursor <ul><ul><li>A cursor is a pointer to the private memory area allocated by the Oracle server. </li></ul></ul><ul...
 
SQL Cursor Attributes for Implicit Cursors <ul><li>Using SQL cursor attributes, you can test the outcome of your SQL state...
SQL Cursor Attributes for Implicit Cursors <ul><li>Delete rows that have the specified employee ID from the  employees  ta...
Summary <ul><li>In this lesson, you should have learned how to:  </li></ul><ul><ul><li>Embed DML statements, transaction c...
Writing Control Structures
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Identify th...
Controlling Flow of Execution for loop while
IF  Statements <ul><li>Syntax: </li></ul>IF  condition  THEN statements ; [ELSIF  condition  THEN  statements ;] [ELSE  st...
IF  Statements
Simple  IF  Statement DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child ');  END IF; ...
IF   THEN   ELSE  Statement SET SERVEROUTPUT ON DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' ...
IF ELSIF ELSE  Clause DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSIF mya...
NULL  Values   in  IF  Statements DECLARE myage number; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child ');  ...
CASE  Expressions <ul><ul><li>A  CASE  expression selects a result and returns it.  </li></ul></ul><ul><ul><li>To select t...
CASE  Expressions: Example SET SERVEROUTPUT ON SET VERIFY OFF DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2...
Searched  CASE  Expressions DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal :=  CASE  WH...
CASE  Statement DECLARE deptid NUMBER; deptname VARCHAR2(20); emps NUMBER; mngid NUMBER:= 108;  BEGIN CASE  mngid WHEN  10...
Handling Nulls <ul><li>When working with nulls, you can avoid some common mistakes by keeping in mind the following rules:...
Logic Tables <ul><li>Build a simple Boolean condition with a comparison operator. </li></ul>AND TRUE FALSE NULL TRUE FALSE...
Boolean Conditions <ul><li>What is the value of  flag  in each case? </li></ul>REORDER_FLAG AVAILABLE_FLAG FLAG TRUE    TR...
Iterative Control:  LOOP  Statements <ul><ul><li>Loops repeat a statement or sequence of statements multiple times. </li><...
Basic Loops <ul><li>Syntax: </li></ul>LOOP  statement1 ; . . . EXIT [WHEN  condition ]; END LOOP;
Basic Loops <ul><li>Example: </li></ul>DECLARE countryid  locations.country_id%TYPE := 'CA'; loc_id  locations.location_id...
WHILE  Loops <ul><li>Syntax: </li></ul><ul><li>Use the  WHILE  loop to repeat statements while a condition is  TRUE . </li...
WHILE  Loops <ul><li>Example: </li></ul>DECLARE countryid  locations.country_id%TYPE := 'CA'; loc_id  locations.location_i...
FOR  Loops <ul><ul><li>Use a  FOR  loop to shortcut the test for the number of iterations. </li></ul></ul><ul><ul><li>Do n...
FOR  Loops
FOR  Loops <ul><li>Example: </li></ul>DECLARE countryid  locations.country_id%TYPE := 'CA'; loc_id  locations.location_id%...
FOR  Loops <ul><li>Guidelines </li></ul><ul><ul><li>Reference the counter within the loop only; it is undefined outside th...
Guidelines While Using Loops <ul><ul><li>Use the basic loop when the statements inside the loop must execute at least once...
Nested Loops and Labels <ul><ul><li>Nest loops to multiple levels. </li></ul></ul><ul><ul><li>Use labels to distinguish be...
Nested Loops and Labels ... BEGIN <<Outer_loop>>   LOOP counter := counter+1; EXIT WHEN counter>10; <<Inner_loop>>   LOOP ...
Summary <ul><li>In this lesson, you should have learned how to:  </li></ul><ul><li>Change the logical flow of statements b...
Working with Composite  Data Types
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Create user...
Composite Data Types <ul><ul><li>Can hold multiple values, unlike scalar types </li></ul></ul><ul><ul><li>Are of two types...
Composite Data Types <ul><ul><li>Use PL/SQL records when you want to store values of different data types but only one occ...
PL/SQL Records <ul><ul><li>Must contain one or more components of any scalar,  RECORD , or  INDEX BY  table data type, cal...
Creating a PL/SQL Record <ul><li>Syntax: </li></ul>TYPE  type_name  IS RECORD ( field_declaration[, field_declaration]…); ...
Creating a PL/SQL Record <ul><li>Declare variables to store the name, job, and salary of a new employee. </li></ul><ul><li...
PL/SQL Record Structure Example: 100  King  AD_PRES employee_id  number(6) last_name  varchar2(25) job_id  varchar2(10) Fi...
The  %ROWTYPE  Attribute <ul><ul><li>Declare a variable according to a collection of columns in a database table or view. ...
The  %ROWTYPE  Attribute <ul><ul><li>Declare a variable according to a collection of columns in a database table or view. ...
Advantages of Using  %ROWTYPE <ul><ul><li>The number and data types of the underlying database columns need not be known. ...
The  %ROWTYPE  Attribute ... DEFINE employee_number = 124  DECLARE   emp_rec  employees%ROWTYPE;  BEGIN   SELECT * INTO em...
Inserting a Record Using  %ROWTYPE ... DEFINE employee_number = 124 DECLARE emp_rec  retired_emps%ROWTYPE; BEGIN SELECT em...
Updating a Row in a Table Using a Record SET SERVEROUTPUT ON SET VERIFY OFF DEFINE employee_number = 124 DECLARE emp_rec r...
INDEX   BY  Tables or Associative Arrays <ul><ul><li>Are PL/SQL structures with two columns: </li></ul></ul><ul><ul><ul><l...
Creating an  INDEX   BY  Table <ul><li>Syntax: </li></ul>TYPE  type_name  IS TABLE OF  {column_type | variable%TYPE | tabl...
Creating an  INDEX   BY  Table
INDEX   BY  Table Structure Unique Key Value ... ... 1 Jones 5 Smith 3 Maduro ... ... PLS_INTEGER Scalar
Creating an  INDEX   BY  Table <ul><li>DECLARE </li></ul><ul><li>TYPE ename_table_type IS TABLE OF </li></ul><ul><li>emplo...
Using  INDEX   BY  Table Methods <ul><li>The following methods make  INDEX   BY  tables easier to use: </li></ul><ul><ul><...
INDEX   BY  Table of Records <ul><li>Define an  INDEX   BY   table variable to hold an entire row from a table. </li></ul>...
INDEX   BY  Table of Records
Example of  INDEX   BY  Table of Records SET SERVEROUTPUT ON DECLARE TYPE emp_table_type IS TABLE OF employees%ROWTYPE IND...
Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Define and reference PL/SQL variable...
Using Explicit Cursors
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Distinguish...
About Cursors <ul><li>Every SQL statement executed by the Oracle Server has an individual cursor associated with it: </li>...
Explicit Cursor Operations Active set Table 100 King  AD_PRES 101 Kochhar AD_VP 102 De Haan AD_VP .  .  . .  .  . .  .  . ...
Controlling Explicit Cursors <ul><li>Load the current row into variables </li></ul>FETCH <ul><li>Test for existing rows </...
Controlling Explicit Cursors Fetch a row. Close the cursor. Cursor  pointer Open the cursor. 1 2 3 Cursor  pointer Cursor ...
Declaring the Cursor <ul><li>Syntax: </li></ul>CURSOR  cursor_name  IS select_statement; Examples: DECLARE CURSOR emp_curs...
Declaring the Cursor
Opening the Cursor DECLARE CURSOR emp_cursor IS  SELECT employee_id, last_name FROM employees   WHERE department_id =30; ....
Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS  SELECT employee_id, last_name FROM employe...
Fetching Data from the Cursor
Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS  SELECT employee_id, last_name FROM employe...
Closing the Cursor ...  LOOP FETCH emp_cursor INTO empno, lname; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE( empn...
Cursors and Records <ul><li>Process the rows of the active set by fetching values into a PL/SQL  RECORD . </li></ul>DECLAR...
Cursor  FOR  Loops <ul><li>Syntax: </li></ul><ul><ul><li>The cursor  FOR  loop is a shortcut to process explicit cursors. ...
Cursor  FOR  Loops SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS  SELECT employee_id, last_name FROM employees WHERE de...
Explicit Cursor Attributes <ul><li>Obtain status information about a cursor. </li></ul>Boolean Evaluates to  TRUE  if the ...
The  %ISOPEN  Attribute <ul><ul><li>Fetch rows only when the cursor is open.  </li></ul></ul><ul><ul><li>Use the  %ISOPEN ...
Example of  %ROWCOUNT  and  %NOTFOUND SET SERVEROUTPUT ON DECLARE empno employees.employee_id%TYPE; ename employees.last_n...
Cursor  FOR  Loops Using Subqueries <ul><li>No need to declare the cursor. </li></ul><ul><li>Example: </li></ul>SET SERVER...
Cursors with Parameters <ul><li>Syntax: </li></ul><ul><ul><li>Pass parameter values to a cursor when the cursor is opened ...
Cursors with Parameters SET SERVEROUTPUT ON DECLARE CURSOR  emp_cursor (deptno NUMBER) IS SELECT  employee_id, last_name F...
The  FOR   UPDATE  Clause <ul><li>Syntax: </li></ul><ul><ul><li>Use explicit locking to deny access to other sessions for ...
The  FOR   UPDATE  Clause
The  WHERE   CURRENT   OF  Clause <ul><li>Syntax: </li></ul><ul><ul><li>Use cursors to update or delete the current row. <...
Cursors with Subqueries DECLARE CURSOR my_cursor IS SELECT t1.department_id, t1.department_name,  t2.staff FROM  departmen...
Summary <ul><li>In this lesson you should have learned how to:  </li></ul><ul><ul><li>Distinguish cursor types: </li></ul>...
Handling Exceptions
Objectives <ul><li>After completing this lesson, you should be able to do the following:  </li></ul><ul><ul><li>Define PL/...
Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE  first_name...
Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE  first_name...
Handling Exceptions with PL/SQL <ul><ul><li>An exception is an error PL/SQL that is raised during program execution. </li>...
Handling Exceptions Exception  raised Is the exception  trapped?  yes Execute statements in the  EXCEPTION section Termina...
Exception Types <ul><ul><li>Predefined Oracle Server </li></ul></ul><ul><ul><li>Non-predefined Oracle Server </li></ul></u...
Trapping Exceptions <ul><li>Syntax: </li></ul>EXCEPTION WHEN  exception1  [OR  exception2  . . .] THEN statement1 ; statem...
Trapping Exceptions
Guidelines for Trapping Exceptions <ul><ul><li>The  EXCEPTION  keyword starts the exception handling section. </li></ul></...
Trapping Predefined Oracle Server Errors <ul><ul><li>Reference the predefined name in the exception handling routine. </li...
 
 
Trapping Non-Predefined Oracle  Server Errors Declarative section Name the exception Code  PRAGMA EXCEPTION_INIT EXCEPTION...
Non-Predefined Error <ul><li>Trap Oracle server error number –01400, cannot insert  NULL . </li></ul>SET SERVEROUTPUT ON D...
Functions for Trapping Exceptions <ul><ul><li>SQLCODE : Returns the numeric value for the error code </li></ul></ul><ul><u...
Functions for Trapping Exceptions <ul><li>Example: </li></ul>DECLARE error_code  NUMBER; error_message  VARCHAR2(255); BEG...
Trapping User-Defined Exceptions Declarative section Name the exception. Executable section Explicitly raise the exception...
Trapping User-Defined Exceptions ... ACCEPT deptno PROMPT 'Please enter the department number:' ACCEPT name  PROMPT 'Pleas...
Calling Environments Traps exception in exception-handling routine of enclosing block An enclosing PL/SQL block Accesses e...
Propagating Exceptions in a Subblock DECLARE . . . no_rows exception; integrity exception; PRAGMA EXCEPTION_INIT (integrit...
The  RAISE_APPLICATION_ERROR Procedure <ul><li>Syntax: </li></ul><ul><ul><li>You can use this procedure to issue user-defi...
The  RAISE_APPLICATION_ERROR Procedure <ul><ul><li>Used in two different places: </li></ul></ul><ul><ul><ul><li>Executable...
RAISE_APPLICATION_ERROR <ul><li>Exception section: </li></ul>BEGIN ... DELETE FROM employees WHERE  manager_id = v_mgr; IF...
Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Define PL/SQL exceptions </li></ul><...
Creating Stored Procedures and Functions
Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Differentia...
Procedures and Functions <ul><ul><li>Are named PL/SQL blocks </li></ul></ul><ul><ul><li>Are called PL/SQL subprograms </li...
Differences Between Anonymous Blocks and Subprograms Can take parameters Cannot take parameters Subprograms called functio...
Procedure: Syntax CREATE [OR REPLACE] PROCEDURE  procedure_name [( argument1  [ mode1 ]  datatype1, argument2  [ mode2 ]  ...
Procedure: Example ... CREATE TABLE dept AS SELECT * FROM departments; CREATE PROCEDURE  add_dept  IS dept_id dept.departm...
Procedure: Example
Invoking the Procedure BEGIN add_dept; END; / SELECT department_id, department_name FROM dept WHERE department_id=280;
Function: Syntax C REATE [OR REPLACE] FUNCTION  function_name [( argument1  [ mode1 ]  datatype1, argument2  [ mode2 ]  da...
Function: Example CREATE FUNCTION  check_sal  RETURN Boolean IS dept_id employees.department_id%TYPE; empno  employees.emp...
Invoking the Function SET SERVEROUTPUT ON BEGIN IF (check_sal IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned   ...
Passing Parameter to the Function DROP FUNCTION check_sal; / CREATE FUNCTION check_sal (empno employees.employee_id%TYPE) ...
Invoking the Function with a Parameter BEGIN DBMS_OUTPUT.PUT_LINE('Checking for employee with id 205'); IF (check_sal(205)...
Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Create a simple procedure </li></ul>...
Goals of the Course <ul><li>After completing this course, you should be able to do the following:  </li></ul><ul><ul><li>I...
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Chinabankppt
Upcoming SlideShare
Loading in …5
×

Chinabankppt

1,977 views

Published on

PL SQL topics

Published in: Education, Technology, Business
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,977
On SlideShare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
0
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide
  • Chinabankppt

    1. 1. Introduction
    2. 2. Lesson Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>List the features of Oracle10 g </li></ul></ul><ul><ul><li>Discuss the theoretical and physical aspects of a relational database </li></ul></ul><ul><ul><li>Describe the Oracle implementation of RDBMS and ORDBMS </li></ul></ul><ul><ul><li>Understand the goals of the course </li></ul></ul>
    3. 3. Retrieving Data Using the SQL SELECT Statement
    4. 4. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>List the capabilities of SQL SELECT statements </li></ul></ul><ul><ul><li>Execute a basic SELECT statement </li></ul></ul><ul><ul><li>Differentiate between SQL statements and i SQL*Plus commands </li></ul></ul>
    5. 5. Capabilities of SQL SELECT Statements Selection Projection Table 1 Table 2 Table 1 Table 1 Join
    6. 6. Basic SELECT Statement <ul><ul><li>SELECT identifies the columns to be displayed. </li></ul></ul><ul><ul><li>FROM identifies the table containing those columns. </li></ul></ul>SELECT *|{[DISTINCT] column | expression [ alias ],...} FROM table;
    7. 7. Selecting All Columns SELECT * FROM departments;
    8. 8. Selecting Specific Columns SELECT department_id, location_id FROM departments;
    9. 9. Writing SQL Statements <ul><ul><li>SQL statements are not case sensitive. </li></ul></ul><ul><ul><li>SQL statements can be on one or more lines. </li></ul></ul><ul><ul><li>Keywords cannot be abbreviated or split across lines. </li></ul></ul><ul><ul><li>Clauses are usually placed on separate lines. </li></ul></ul><ul><ul><li>Indents are used to enhance readability. </li></ul></ul><ul><ul><li>In i SQL*Plus, SQL statements can optionally be terminated by a semicolon (;). Semicolons are required if you execute multiple SQL statements. </li></ul></ul><ul><ul><li>In SQL*Plus, you are required to end each SQL statement with a semicolon (;). </li></ul></ul>
    10. 10. Column Heading Defaults <ul><ul><li>i SQL*Plus: </li></ul></ul><ul><ul><ul><li>Default heading alignment: Center </li></ul></ul></ul><ul><ul><ul><li>Default heading display: Uppercase </li></ul></ul></ul><ul><ul><li>SQL*Plus: </li></ul></ul><ul><ul><ul><li>Character and Date column headings are left-aligned </li></ul></ul></ul><ul><ul><ul><li>Number column headings are right-aligned </li></ul></ul></ul><ul><ul><ul><li>Default heading display: Uppercase </li></ul></ul></ul>
    11. 11. Arithmetic Expressions <ul><li>Create expressions with number and date data by using arithmetic operators. </li></ul>Multiply * Divide <ul><ul><li>/ </li></ul></ul>Subtract <ul><ul><li>- </li></ul></ul>Add <ul><ul><li>+ </li></ul></ul>Description Operator
    12. 12. Using Arithmetic Operators SELECT last_name, salary, salary + 300 FROM employees; …
    13. 13. Operator Precedence SELECT last_name, salary, 12*salary+100 FROM employees; SELECT last_name, salary, 12*(salary+100)‏ FROM employees; 1 2 … …
    14. 14. Defining a Null Value <ul><ul><li>A null is a value that is unavailable, unassigned, unknown, or inapplicable. </li></ul></ul><ul><ul><li>A null is not the same as a zero or a blank space. </li></ul></ul>SELECT last_name, job_id, salary, commission_pct FROM employees; … …
    15. 15. Null Values in Arithmetic Expressions <ul><li>Arithmetic expressions containing a null value evaluate to null. </li></ul>SELECT last_name, 12*salary*commission_pct FROM employees; … …
    16. 16. Defining a Column Alias <ul><li>A column alias: </li></ul><ul><ul><li>Renames a column heading </li></ul></ul><ul><ul><li>Is useful with calculations </li></ul></ul><ul><ul><li>Immediately follows the column name (There can also be the optional AS keyword between the column name and alias.)‏ </li></ul></ul><ul><ul><li>Requires double quotation marks if it contains spaces or special characters or if it is case sensitive </li></ul></ul>
    17. 17. Using Column Aliases SELECT last_name &quot;Name&quot; , salary*12 &quot;Annual Salary&quot; FROM employees; SELECT last_name AS name, commission_pct comm FROM employees; … …
    18. 18. Concatenation Operator <ul><li>A concatenation operator: </li></ul><ul><ul><li>Links columns or character strings to other columns </li></ul></ul><ul><ul><li>Is represented by two vertical bars (||)‏ </li></ul></ul><ul><ul><li>Creates a resultant column that is a character expression </li></ul></ul>SELECT last_name||job_id AS &quot;Employees&quot; FROM employees; …
    19. 19. Literal Character Strings <ul><ul><li>A literal is a character, a number, or a date that is included in the SELECT statement. </li></ul></ul><ul><ul><li>Date and character literal values must be enclosed by single quotation marks. </li></ul></ul><ul><ul><li>Each character string is output once for each row returned. </li></ul></ul>
    20. 20. Using Literal Character Strings … SELECT last_name ||' is a '||job_id AS &quot;Employee Details&quot; FROM employees;
    21. 21. Alternative Quote ( q ) Operator <ul><ul><li>Specify your own quotation mark delimiter </li></ul></ul><ul><ul><li>Choose any delimiter </li></ul></ul><ul><ul><li>Increase readability and usability </li></ul></ul>SELECT department_name || q'[, it's assigned Manager Id: ]' || manager_id AS &quot;Department and Manager&quot; FROM departments; …
    22. 22. Duplicate Rows <ul><li>The default display of queries is all rows, including duplicate rows. </li></ul>SELECT department_id FROM employees; SELECT DISTINCT department_id FROM employees; … 1 2 …
    23. 23. Displaying Table Structure <ul><li>Use the i SQL*Plus DESCRIBE command to display the structure of a table: </li></ul>DESC[RIBE] tablename
    24. 24. Displaying Table Structure DESCRIBE employees
    25. 25. Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Write a SELECT statement that: </li></ul></ul><ul><ul><ul><li>Returns all rows and columns from a table </li></ul></ul></ul><ul><ul><ul><li>Returns specified columns from a table </li></ul></ul></ul><ul><ul><ul><li>Uses column aliases to display more descriptive column headings </li></ul></ul></ul><ul><ul><li>Use the i SQL*Plus environment to write, save, and execute SQL statements and i SQL*Plus commands </li></ul></ul>SELECT *|{[DISTINCT] column|expression [ alias ],...} FROM table;
    26. 26. Restricting and Sorting Data
    27. 27. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Limit the rows that are retrieved by a query </li></ul></ul><ul><ul><li>Sort the rows that are retrieved by a query </li></ul></ul><ul><ul><li>Use ampersand substitution in i SQL*Plus to restrict and sort output at run time </li></ul></ul>
    28. 28. Limiting Rows Using a Selection “ retrieve all employees in department 90” EMPLOYEES …
    29. 29. Limiting the Rows That Are Selected <ul><ul><li>Restrict the rows that are returned by using the WHERE clause: </li></ul></ul><ul><ul><li>The WHERE clause follows the FROM clause. </li></ul></ul>SELECT *|{[DISTINCT] column|expression [ alias ],...} FROM table [WHERE condition(s) ];
    30. 30. Using the WHERE Clause SELECT employee_id, last_name, job_id, department_id FROM employees WHERE department_id = 90 ;
    31. 31. Character Strings and Dates <ul><ul><li>Character strings and date values are enclosed in single quotation marks. </li></ul></ul><ul><ul><li>Character values are case sensitive, and date values are format sensitive. </li></ul></ul><ul><ul><li>The default date format is DD-MON-RR. </li></ul></ul>SELECT last_name, job_id, department_id FROM employees WHERE last_name = 'Whalen' ;
    32. 32. Comparison Conditions Not equal to <ul><ul><li><> </li></ul></ul>Between two values (inclusive)‏ BETWEEN ...AND... Match any of a list of values IN(set)‏ Match a character pattern LIKE Is a null value IS NULL Less than <ul><ul><li>< </li></ul></ul>Less than or equal to <ul><ul><li><= </li></ul></ul>Greater than or equal to >= Greater than <ul><ul><li>> </li></ul></ul>Equal to <ul><ul><li>= </li></ul></ul>Meaning Operator
    33. 33. Using Comparison Conditions SELECT last_name, salary FROM employees WHERE salary <= 3000 ;
    34. 34. Using the BETWEEN Condition <ul><li>Use the BETWEEN condition to display rows based on a range of values: </li></ul>SELECT last_name, salary FROM employees WHERE salary BETWEEN 2500 AND 3500 ; Lower limit Upper limit
    35. 35. Using the IN Condition <ul><li>Use the IN membership condition to test for values in a list: </li></ul>SELECT employee_id, last_name, salary, manager_id FROM employees WHERE manager_id IN (100, 101, 201) ;
    36. 36. Using the LIKE Condition <ul><ul><li>Use the LIKE condition to perform wildcard searches of valid search string values. </li></ul></ul><ul><ul><li>Search conditions can contain either literal characters or numbers: </li></ul></ul><ul><ul><ul><li>% denotes zero or many characters. </li></ul></ul></ul><ul><ul><ul><li>_ denotes one character. </li></ul></ul></ul>SELECT first_name FROM employees WHERE first_name LIKE 'S%' ;
    37. 37. <ul><ul><li>You can combine pattern-matching characters: </li></ul></ul><ul><ul><li>You can use the ESCAPE identifier to search for the actual % and _ symbols. </li></ul></ul>Using the LIKE Condition SELECT last_name FROM employees WHERE last_name LIKE '_o%' ;
    38. 38. Using the NULL Conditions <ul><li>Test for nulls with the IS NULL operator. </li></ul>SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL ;
    39. 39. Logical Conditions Returns TRUE if the following condition is false NOT Returns TRUE if either component condition is true <ul><ul><li>OR </li></ul></ul>Returns TRUE if both component conditions are true <ul><ul><li>AND </li></ul></ul>Meaning Operator
    40. 40. Using the AND Operator SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >=10000 AND job_id LIKE '%MAN%' ; AND requires both conditions to be true:
    41. 41. Using the OR Operator SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >= 10000 OR job_id LIKE '%MAN%' ; <ul><ul><li>OR requires either condition to be true: </li></ul></ul>
    42. 42. Using the NOT Operator SELECT last_name, job_id FROM employees WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;
    43. 43. Rules of Precedence You can use parentheses to override rules of precedence. Not equal to <ul><ul><li>6 </li></ul></ul>NOT logical condition <ul><ul><li>7 </li></ul></ul>AND logical condition <ul><ul><li>8 </li></ul></ul>OR logical condition <ul><ul><li>9 </li></ul></ul>IS [NOT] NULL , LIKE , [NOT] IN <ul><ul><li>4 </li></ul></ul>[NOT] BETWEEN <ul><ul><li>5 </li></ul></ul>Comparison conditions <ul><ul><li>3 </li></ul></ul>Concatenation operator <ul><ul><li>2 </li></ul></ul>Arithmetic operators <ul><ul><li>1 </li></ul></ul>Meaning Operator
    44. 44. Rules of Precedence SELECT last_name, job_id, salary FROM employees WHERE job_id = 'SA_REP' OR job_id = 'AD_PRES' AND salary > 15000; SELECT last_name, job_id, salary FROM employees WHERE ( job_id = 'SA_REP' OR job_id = 'AD_PRES' )‏ AND salary > 15000; 1 2
    45. 45. Using the ORDER BY Clause <ul><ul><li>Sort retrieved rows with the ORDER BY clause: </li></ul></ul><ul><ul><ul><li>ASC : ascending order, default </li></ul></ul></ul><ul><ul><ul><li>DESC : descending order </li></ul></ul></ul><ul><ul><li>The ORDER BY clause comes last in the SELECT statement: </li></ul></ul>SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date ; …
    46. 46. Sorting <ul><ul><li>Sorting in descending order: </li></ul></ul><ul><ul><li>Sorting by column alias: </li></ul></ul><ul><ul><li>Sorting by multiple columns: </li></ul></ul>SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date DESC ; 1 SELECT employee_id, last_name, salary*12 annsal FROM employees ORDER BY annsal ; 2 SELECT last_name, department_id, salary FROM employees ORDER BY department_id, salary DESC; 3
    47. 47. Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Use the WHERE clause to restrict rows of output: </li></ul></ul><ul><ul><ul><li>Use the comparison conditions </li></ul></ul></ul><ul><ul><ul><li>Use the BETWEEN , IN , LIKE , and NULL conditions </li></ul></ul></ul><ul><ul><ul><li>Apply the logical AND , OR , and NOT operators </li></ul></ul></ul><ul><ul><li>Use the ORDER BY clause to sort rows of output: </li></ul></ul><ul><ul><li>Use ampersand substitution in i SQL*Plus to restrict and sort output at run time </li></ul></ul>SELECT *|{[DISTINCT] column|expression [ alias ],...} FROM table [WHERE condition(s) ] [ORDER BY { column, expr, alias } [ASC|DESC]] ;
    48. 48. Displaying Data from Multiple Tables
    49. 49. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Write SELECT statements to access data from more than one table using equijoins and nonequijoins </li></ul></ul><ul><ul><li>Join a table to itself by using a self-join </li></ul></ul><ul><ul><li>View data that generally does not meet a join condition by using outer joins </li></ul></ul><ul><ul><li>Generate a Cartesian product of all rows from two or more tables </li></ul></ul>
    50. 50. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … …
    51. 51. Types of Joins <ul><li>Joins that are compliant with the SQL:1999 standard include the following: </li></ul><ul><ul><li>Cross joins </li></ul></ul><ul><ul><li>Natural joins </li></ul></ul><ul><ul><li>USING clause </li></ul></ul><ul><ul><li>Full (or two-sided) outer joins </li></ul></ul><ul><ul><li>Arbitrary join conditions for outer joins </li></ul></ul>
    52. 52. Joining Tables Using SQL:1999 Syntax <ul><li>Use a join to query data from more than one table: </li></ul>SELECT table1.column, table2.column FROM table1 [NATURAL JOIN table2 ] | [JOIN table2 USING ( column_name )] | [JOIN table2 ON ( table1.column_name = table2.column_name )]| [LEFT|RIGHT|FULL OUTER JOIN table2 ON ( table1.column_name = table2.column_name )]| [CROSS JOIN table2 ];
    53. 53. Creating Natural Joins <ul><ul><li>The NATURAL JOIN clause is based on all columns in the two tables that have the same name. </li></ul></ul><ul><ul><li>It selects rows from the two tables that have equal values in all matched columns. </li></ul></ul><ul><ul><li>If the columns having the same names have different data types, an error is returned. </li></ul></ul>
    54. 54. Retrieving Records with Natural Joins SELECT department_id, department_name, location_id, city FROM departments NATURAL JOIN locations ;
    55. 55. Creating Joins with the USING Clause <ul><ul><li>If several columns have the same names but the data types do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an equijoin. </li></ul></ul><ul><ul><li>Use the USING clause to match only one column when more than one column matches. </li></ul></ul><ul><ul><li>Do not use a table name or alias in the referenced columns. </li></ul></ul><ul><ul><li>The NATURAL JOIN and USING clauses are mutually exclusive. </li></ul></ul>
    56. 56. Joining Column Names EMPLOYEES DEPARTMENTS Foreign key Primary key … …
    57. 57. Retrieving Records with the USING Clause SELECT employees.employee_id, employees.last_name, departments.location_id, department_id FROM employees JOIN departments USING (department_id) ; …
    58. 58. Qualifying Ambiguous Column Names <ul><ul><li>Use table prefixes to qualify column names that are in multiple tables. </li></ul></ul><ul><ul><li>Use table prefixes to improve performance. </li></ul></ul><ul><ul><li>Use column aliases to distinguish columns that have identical names but reside in different tables. </li></ul></ul><ul><ul><li>Do not use aliases on columns that are identified in the USING clause and listed elsewhere in the SQL statement. </li></ul></ul>
    59. 59. Using Table Aliases <ul><ul><li>Use table aliases to simplify queries. </li></ul></ul><ul><ul><li>Use table aliases to improve performance. </li></ul></ul>SELECT e.employee_id, e.last_name, d.location_id, department_id FROM employees e JOIN departments d USING (department_id) ;
    60. 60. Creating Joins with the ON Clause <ul><ul><li>The join condition for the natural join is basically an equijoin of all columns with the same name. </li></ul></ul><ul><ul><li>Use the ON clause to specify arbitrary conditions or specify columns to join. </li></ul></ul><ul><ul><li>The join condition is separated from other search conditions. </li></ul></ul><ul><ul><li>The ON clause makes code easy to understand. </li></ul></ul>
    61. 61. Retrieving Records with the ON Clause SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id); …
    62. 62. Self-Joins Using the ON Clause MANAGER_ID in the WORKER table is equal to EMPLOYEE_ID in the MANAGER table. EMPLOYEES (WORKER) EMPLOYEES (MANAGER) … …
    63. 63. Self-Joins Using the ON Clause SELECT e.last_name emp, m.last_name mgr FROM employees e JOIN employees m ON (e.manager_id = m.employee_id); …
    64. 64. Applying Additional Conditions to a Join SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id) AND e.manager_id = 149 ;
    65. 65. Creating Three-Way Joins with the ON Clause SELECT employee_id, city, department_name FROM employees e JOIN departments d ON d.department_id = e.department_id JOIN locations l ON d.location_id = l.location_id; …
    66. 66. Nonequijoins EMPLOYEES JOB_GRADES Salary in the EMPLOYEES table must be between lowest salary and highest salary in the JOB_GRADES table. …
    67. 67. Retrieving Records with Nonequijoins SELECT e.last_name, e.salary, j.grade_level FROM employees e JOIN job_grades j ON e.salary BETWEEN j.lowest_sal AND j.highest_sal; …
    68. 68. Outer Joins EMPLOYEES DEPARTMENTS There are no employees in department 190. …
    69. 69. INNER Versus OUTER Joins <ul><ul><li>In SQL:1999, the join of two tables returning only matched rows is called an inner join. </li></ul></ul><ul><ul><li>A join between two tables that returns the results of the inner join as well as the unmatched rows from the left (or right) tables is called a left (or right) outer join. </li></ul></ul><ul><ul><li>A join between two tables that returns the results of an inner join as well as the results of a left and right join is a full outer join. </li></ul></ul>
    70. 70. LEFT OUTER JOIN SELECT e.last_name, e.department_id, d.department_name FROM employees e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id) ; …
    71. 71. RIGHT OUTER JOIN SELECT e.last_name, e.department_id, d.department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id) ; …
    72. 72. FULL OUTER JOIN SELECT e.last_name, d.department_id, d.department_name FROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id) ; …
    73. 73. Cartesian Products <ul><ul><li>A Cartesian product is formed when: </li></ul></ul><ul><ul><ul><li>A join condition is omitted </li></ul></ul></ul><ul><ul><ul><li>A join condition is invalid </li></ul></ul></ul><ul><ul><ul><li>All rows in the first table are joined to all rows in the second table </li></ul></ul></ul><ul><ul><li>To avoid a Cartesian product, always include a valid join condition. </li></ul></ul>
    74. 74. Generating a Cartesian Product Cartesian product: 20 x 8 = 160 rows EMPLOYEES (20 rows) DEPARTMENTS (8 rows) … …
    75. 75. Creating Cross Joins <ul><ul><li>The CROSS JOIN clause produces the cross-product of two tables. </li></ul></ul><ul><ul><li>This is also called a Cartesian product between the two tables. </li></ul></ul>SELECT last_name, department_name FROM employees CROSS JOIN departments ; …
    76. 76. Summary <ul><li>In this lesson, you should have learned how to use joins to display data from multiple tables by using: </li></ul><ul><ul><li>Equijoins </li></ul></ul><ul><ul><li>Nonequijoins </li></ul></ul><ul><ul><li>Outer joins </li></ul></ul><ul><ul><li>Self-joins </li></ul></ul><ul><ul><li>Cross joins </li></ul></ul><ul><ul><li>Natural joins </li></ul></ul><ul><ul><li>Full (or two-sided) outer joins </li></ul></ul>
    77. 77. Manipulating Data
    78. 78. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Describe each data manipulation language (DML) statement </li></ul></ul><ul><ul><li>Insert rows into a table </li></ul></ul><ul><ul><li>Update rows in a table </li></ul></ul><ul><ul><li>Delete rows from a table </li></ul></ul><ul><ul><li>Control transactions </li></ul></ul>
    79. 79. Data Manipulation Language <ul><ul><li>A DML statement is executed when you: </li></ul></ul><ul><ul><ul><li>Add new rows to a table </li></ul></ul></ul><ul><ul><ul><li>Modify existing rows in a table </li></ul></ul></ul><ul><ul><ul><li>Remove existing rows from a table </li></ul></ul></ul><ul><ul><li>A transaction consists of a collection of DML statements that form a logical unit of work. </li></ul></ul>
    80. 80. Adding a New Row to a Table DEPARTMENTS New row Insert new row into the DEPARTMENTS table
    81. 81. INSERT Statement Syntax <ul><ul><li>Add new rows to a table by using the INSERT statement: </li></ul></ul><ul><ul><li>With this syntax, only one row is inserted at a time. </li></ul></ul>INSERT INTO table [( column [ , column... ])] VALUES (value [ , value... ]);
    82. 82. Inserting New Rows <ul><ul><li>Insert a new row containing values for each column. </li></ul></ul><ul><ul><li>List values in the default order of the columns in the table. </li></ul></ul><ul><ul><li>Optionally, list the columns in the INSERT clause. </li></ul></ul><ul><ul><li>Enclose character and date values in single quotation marks. </li></ul></ul>INSERT INTO departments(department_id, department_name, manager_id, location_id) VALUES (70, 'Public Relations', 100, 1700); 1 row created.
    83. 83. Inserting Rows with Null Values <ul><ul><li>Implicit method: Omit the column from the column list. </li></ul></ul>INSERT INTO departments VALUES (100, 'Finance', NULL, NULL); 1 row created. INSERT INTO departments (department_id, department_name ) VALUES (30, 'Purchasing'); 1 row created. <ul><li>Explicit method: Specify the NULL keyword in the VALUES clause. </li></ul>
    84. 84. Inserting Special Values <ul><li>The SYSDATE function records the current date and time. </li></ul>INSERT INTO employees (employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_pct, manager_id, department_id) VALUES (113, 'Louis', 'Popp', 'LPOPP', '515.124.4567', SYSDATE, 'AC_ACCOUNT', 6900, NULL, 205, 100); 1 row created.
    85. 85. <ul><ul><li>Add a new employee. </li></ul></ul><ul><ul><li>Verify your addition. </li></ul></ul>Inserting Specific Date Values INSERT INTO employees VALUES (114, 'Den', 'Raphealy', 'DRAPHEAL', '515.127.4561', TO_DATE('FEB 3, 1999', 'MON DD, YYYY'), 'AC_ACCOUNT', 11000, NULL, 100, 30); 1 row created.
    86. 86. Copying Rows from Another Table <ul><ul><li>Write your INSERT statement with a subquery: </li></ul></ul><ul><ul><li>Do not use the VALUES clause. </li></ul></ul><ul><ul><li>Match the number of columns in the INSERT clause to those in the subquery. </li></ul></ul>INSERT INTO sales_reps(id, name, salary, commission_pct) SELECT employee_id, last_name, salary, commission_pct FROM employees WHERE job_id LIKE '%REP%'; 4 rows created.
    87. 87. Changing Data in a Table EMPLOYEES Update rows in the EMPLOYEES table:
    88. 88. <ul><ul><li>Modify existing rows with the UPDATE statement: </li></ul></ul><ul><ul><li>Update more than one row at a time (if required). </li></ul></ul>UPDATE Statement Syntax UPDATE table SET column = value [, column = value, ... ] [WHERE condition ];
    89. 89. <ul><ul><li>Specific row or rows are modified if you specify the WHERE clause: </li></ul></ul><ul><ul><li>All rows in the table are modified if you omit the WHERE clause: </li></ul></ul>Updating Rows in a Table UPDATE employees SET department_id = 70 WHERE employee_id = 113; 1 row updated. UPDATE copy_emp SET department_id = 110; 22 rows updated.
    90. 90. Removing a Row from a Table Delete a row from the DEPARTMENTS table: DEPARTMENTS
    91. 91. DELETE Statement <ul><li>You can remove existing rows from a table by using the DELETE statement: </li></ul>DELETE [FROM] table [WHERE condition ];
    92. 92. Deleting Rows from a Table <ul><ul><li>Specific rows are deleted if you specify the WHERE clause: </li></ul></ul><ul><ul><li>All rows in the table are deleted if you omit the WHERE clause: </li></ul></ul>DELETE FROM departments WHERE department_name = 'Finance'; 1 row deleted. DELETE FROM copy_emp; 22 rows deleted.
    93. 93. Database Transactions <ul><li>A database transaction consists of one of the following: </li></ul><ul><ul><li>DML statements that constitute one consistent change to the data </li></ul></ul><ul><ul><li>One DDL statement </li></ul></ul><ul><ul><li>One data control language (DCL) statement </li></ul></ul>
    94. 94. Database Transactions <ul><ul><li>Begin when the first DML SQL statement is executed </li></ul></ul><ul><ul><li>End with one of the following events: </li></ul></ul><ul><ul><ul><li>A COMMIT or ROLLBACK statement is issued. </li></ul></ul></ul><ul><ul><ul><li>A DDL or DCL statement executes (automatic commit). </li></ul></ul></ul><ul><ul><ul><li>The user exits i SQL*Plus. </li></ul></ul></ul><ul><ul><ul><li>The system crashes. </li></ul></ul></ul>
    95. 95. Advantages of COMMIT and ROLLBACK Statements <ul><li>With COMMIT and ROLLBACK statements, you can: </li></ul><ul><ul><li>Ensure data consistency </li></ul></ul><ul><ul><li>Preview data changes before making changes permanent </li></ul></ul><ul><ul><li>Group logically related operations </li></ul></ul>
    96. 96. Controlling Transactions SAVEPOINT B SAVEPOINT A DELETE INSERT UPDATE INSERT COMMIT Time Transaction ROLLBACK to SAVEPOINT B ROLLBACK to SAVEPOINT A ROLLBACK
    97. 97. Rolling Back Changes to a Marker <ul><ul><li>Create a marker in a current transaction by using the SAVEPOINT statement. </li></ul></ul><ul><ul><li>Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement. </li></ul></ul>UPDATE... SAVEPOINT update_done; Savepoint created. INSERT... ROLLBACK TO update_done; Rollback complete.
    98. 98. Implicit Transaction Processing <ul><ul><li>An automatic commit occurs under the following circumstances: </li></ul></ul><ul><ul><ul><li>DDL statement is issued </li></ul></ul></ul><ul><ul><ul><li>DCL statement is issued </li></ul></ul></ul><ul><ul><ul><li>Normal exit from i SQL*Plus, without explicitly issuing COMMIT or ROLLBACK statements </li></ul></ul></ul><ul><ul><li>An automatic rollback occurs under an abnormal termination of i SQL*Plus or a system failure. </li></ul></ul>
    99. 100. State of the Data Before COMMIT or ROLLBACK <ul><ul><li>The previous state of the data can be recovered. </li></ul></ul><ul><ul><li>The current user can review the results of the DML operations by using the SELECT statement. </li></ul></ul><ul><ul><li>Other users cannot view the results of the DML statements by the current user. </li></ul></ul><ul><ul><li>The affected rows are locked ; other users cannot change the data in the affected rows. </li></ul></ul>
    100. 101. State of the Data After COMMIT <ul><ul><li>Data changes are made permanent in the database. </li></ul></ul><ul><ul><li>The previous state of the data is permanently lost. </li></ul></ul><ul><ul><li>All users can view the results. </li></ul></ul><ul><ul><li>Locks on the affected rows are released; those rows are available for other users to manipulate. </li></ul></ul><ul><ul><li>All savepoints are erased. </li></ul></ul>
    101. 102. Committing Data <ul><ul><li>Make the changes: </li></ul></ul><ul><ul><li>Commit the changes: </li></ul></ul>COMMIT; Commit complete. DELETE FROM employees WHERE employee_id = 99999; 1 row deleted. INSERT INTO departments VALUES (290, 'Corporate Tax', NULL, 1700); 1 row created.
    102. 103. State of the Data After ROLLBACK <ul><li>Discard all pending changes by using the ROLLBACK statement: </li></ul><ul><ul><li>Data changes are undone. </li></ul></ul><ul><ul><li>Previous state of the data is restored. </li></ul></ul><ul><ul><li>Locks on the affected rows are released. </li></ul></ul>DELETE FROM copy_emp; 20 rows deleted. ROLLBACK ; Rollback complete.
    103. 104. State of the Data After ROLLBACK DELETE FROM test; 25,000 rows deleted. ROLLBACK; Rollback complete. DELETE FROM test WHERE id = 100; 1 row deleted. SELECT * FROM test WHERE id = 100; No rows selected. COMMIT; Commit complete.
    104. 105. Statement-Level Rollback <ul><ul><li>If a single DML statement fails during execution, only that statement is rolled back. </li></ul></ul><ul><ul><li>The Oracle server implements an implicit savepoint. </li></ul></ul><ul><ul><li>All other changes are retained. </li></ul></ul><ul><ul><li>The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK statement. </li></ul></ul>
    105. 106. Summary <ul><li>In this lesson, you should have learned how to use the following statements: </li></ul>Adds a new row to the table INSERT Modifies existing rows in the table UPDATE Removes existing rows from the table DELETE Makes all pending changes permanent COMMIT Discards all pending data changes ROLLBACK Is used to roll back to the savepoint marker SAVEPOINT Description Function
    106. 107. Using DDL Statements to Create and Manage Tables
    107. 108. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Categorize the main database objects </li></ul></ul><ul><ul><li>Review the table structure </li></ul></ul><ul><ul><li>List the data types that are available for columns </li></ul></ul><ul><ul><li>Create a simple table </li></ul></ul><ul><ul><li>Explain how constraints are created at the time of table creation </li></ul></ul><ul><ul><li>Describe how schema objects work </li></ul></ul>
    108. 109. Database Objects Logically represents subsets of data from one or more tables View Generates numeric values Sequence Basic unit of storage; composed of rows Table Gives alternative names to objects Synonym Improves the performance of some queries Index Description Object
    109. 110. Naming Rules <ul><li>Table names and column names: </li></ul><ul><ul><li>Must begin with a letter </li></ul></ul><ul><ul><li>Must be 1–30 characters long </li></ul></ul><ul><ul><li>Must contain only A–Z, a–z, 0–9, _, $, and # </li></ul></ul><ul><ul><li>Must not duplicate the name of another object owned by the same user </li></ul></ul><ul><ul><li>Must not be an Oracle server – reserved word </li></ul></ul>
    110. 111. <ul><ul><li>You must have: </li></ul></ul><ul><ul><ul><li>CREATE TABLE privilege </li></ul></ul></ul><ul><ul><ul><li>A storage area </li></ul></ul></ul><ul><ul><li>You specify: </li></ul></ul><ul><ul><ul><li>Table name </li></ul></ul></ul><ul><ul><ul><li>Column name, column data type, and column size </li></ul></ul></ul>CREATE TABLE Statement CREATE TABLE [ schema .] table ( column datatype [DEFAULT expr ][, ...]);
    111. 112. Referencing Another User’s Tables <ul><ul><li>Tables belonging to other users are not in the user’s schema. </li></ul></ul><ul><ul><li>You should use the owner’s name as a prefix to those tables. </li></ul></ul>USERB USERA SELECT * FROM userB.employees; SELECT * FROM userA.employees;
    112. 113. <ul><ul><li>Specify a default value for a column during an insert. </li></ul></ul><ul><ul><li>Literal values, expressions, or SQL functions are legal values. </li></ul></ul><ul><ul><li>Another column’s name or a pseudocolumn are illegal values. </li></ul></ul><ul><ul><li>The default data type must match the column data type. </li></ul></ul>DEFAULT Option ... hire_date DATE DEFAULT SYSDATE, ... CREATE TABLE hire_dates (id NUMBER(8), hire_date DATE DEFAULT SYSDATE ); Table created.
    113. 114. Creating Tables <ul><ul><li>Create the table. </li></ul></ul><ul><ul><li>Confirm table creation. </li></ul></ul>DESCRIBE dept CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13), create_date DATE DEFAULT SYSDATE ); Table created.
    114. 115. Data Types Raw binary data RAW and LONG RAW Binary data (up to 4 GB) BLOB Binary data stored in an external file (up to 4 GB) BFILE Date and time values DATE Variable-length character data (up to 2 GB) LONG Character data (up to 4 GB) CLOB A base-64 number system representing the unique address of a row in its table ROWID Fixed-length character data CHAR( size ) Variable-length numeric data NUMBER( p , s) Variable-length character data VARCHAR2( size ) Description Data Type
    115. 117. Datetime Data Types <ul><li>You can use several datetime data types: </li></ul>Stored as an interval of years and months INTERVAL YEAR TO MONTH Stored as an interval of days, hours, minutes, and seconds INTERVAL DAY TO SECOND Date with fractional seconds TIMESTAMP Description Data Type
    116. 118. Datetime Data Types <ul><ul><li>The TIMESTAMP data type is an extension of the DATE data type. </li></ul></ul><ul><ul><li>It stores the year, month, and day of the DATE data type plus hour, minute, and second values as well as the fractional second value. </li></ul></ul><ul><ul><li>You can optionally specify the time zone. </li></ul></ul>TIMESTAMP[(fractional_seconds_precision)] TIMESTAMP[(fractional_seconds_precision)] WITH TIME ZONE TIMESTAMP[(fractional_seconds_precision)] WITH LOCAL TIME ZONE
    117. 120. Datetime Data Types <ul><ul><li>The INTERVAL YEAR TO MONTH data type stores a period of time using the YEAR and MONTH datetime fields: </li></ul></ul><ul><ul><li>The INTERVAL DAY TO SECOND data type stores a period of time in terms of days, hours, minutes, and seconds: </li></ul></ul>INTERVAL YEAR [(year_precision)] TO MONTH INTERVAL DAY [(day_precision)] TO SECOND [(fractional_seconds_precision)]
    118. 122. INTERVAL DAY TO SECOND Data Type <ul><li>INTERVAL DAY TO SECOND stores a period of time in terms of days, hours, minutes, and seconds. </li></ul>INTERVAL '4 5:12:10.222' DAY TO SECOND(3) Indicates 4 days, 5 hours, 12 minutes, 10 seconds, and 222 thousandths of a second. INTERVAL '4 5:12' DAY TO MINUTE Indicates 4 days, 5 hours and 12 minutes. INTERVAL '400 5' DAY(3) TO HOUR Indicates 400 days 5 hours. INTERVAL '11:12:10.2222222' HOUR TO SECOND(7) indicates 11 hours, 12 minutes, and 10.2222222 seconds.
    119. 123. Including Constraints <ul><ul><li>Constraints enforce rules at the table level. </li></ul></ul><ul><ul><li>Constraints prevent the deletion of a table if there are dependencies. </li></ul></ul><ul><ul><li>The following constraint types are valid: </li></ul></ul><ul><ul><ul><li>NOT NULL </li></ul></ul></ul><ul><ul><ul><li>UNIQUE </li></ul></ul></ul><ul><ul><ul><li>PRIMARY KEY </li></ul></ul></ul><ul><ul><ul><li>FOREIGN KEY </li></ul></ul></ul><ul><ul><ul><li>CHECK </li></ul></ul></ul>
    120. 124. Constraint Guidelines <ul><ul><li>You can name a constraint, or the Oracle server generates a name by using the SYS_C n format. </li></ul></ul><ul><ul><li>Create a constraint at either of the following times: </li></ul></ul><ul><ul><ul><li>At the same time as the table is created </li></ul></ul></ul><ul><ul><ul><li>After the table has been created </li></ul></ul></ul><ul><ul><li>Define a constraint at the column or table level. </li></ul></ul><ul><ul><li>View a constraint in the data dictionary. </li></ul></ul>
    121. 125. <ul><ul><li>Syntax: </li></ul></ul><ul><ul><li>Column-level constraint: </li></ul></ul><ul><ul><li>Table-level constraint: </li></ul></ul>Defining Constraints CREATE TABLE [ schema .] table ( column datatype [DEFAULT expr ] [ column_constraint ], ... [ table_constraint ][,...] ); column,... [CONSTRAINT constraint_name ] constraint_type ( column , ...), column [CONSTRAINT constraint_name ] constraint_type ,
    122. 126. Defining Constraints <ul><ul><li>Column-level constraint: </li></ul></ul><ul><ul><li>Table-level constraint: </li></ul></ul>CREATE TABLE employees( employee_id NUMBER(6) CONSTRAINT emp_emp_id_pk PRIMARY KEY, first_name VARCHAR2(20), ...); CREATE TABLE employees( employee_id NUMBER(6), first_name VARCHAR2(20), ... job_id VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID) ); 1 2
    123. 127. NOT NULL Constraint <ul><li>Ensures that null values are not permitted for the column: </li></ul>NOT NULL constraint (No row can contain a null value for this column.) Absence of NOT NULL constraint (Any row can contain a null value for this column.) NOT NULL constraint …
    124. 128. UNIQUE Constraint EMPLOYEES UNIQUE constraint INSERT INTO Not allowed: already exists Allowed …
    125. 129. UNIQUE Constraint <ul><li>Defined at either the table level or the column level: </li></ul>CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... CONSTRAINT emp_email_uk UNIQUE(email));
    126. 130. PRIMARY KEY Constraint DEPARTMENTS PRIMARY KEY INSERT INTO Not allowed (null value) Not allowed (50 already exists) …
    127. 131. FOREIGN KEY Constraint DEPARTMENTS EMPLOYEES FOREIGN KEY INSERT INTO Not allowed (9 does not exist) Allowed PRIMARY KEY … …
    128. 132. FOREIGN KEY Constraint <ul><li>Defined at either the table level or the column level: </li></ul>CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (department_id) REFERENCES departments(department_id), CONSTRAINT emp_email_uk UNIQUE(email));
    129. 133. FOREIGN KEY Constraint: Keywords <ul><ul><li>FOREIGN KEY : Defines the column in the child table at the table-constraint level </li></ul></ul><ul><ul><li>REFERENCES : Identifies the table and column in the parent table </li></ul></ul><ul><ul><li>ON DELETE CASCADE : Deletes the dependent rows in the child table when a row in the parent table is deleted </li></ul></ul><ul><ul><li>ON DELETE SET NULL : Converts dependent foreign key values to null </li></ul></ul>
    130. 134. CHECK Constraint <ul><ul><li>Defines a condition that each row must satisfy </li></ul></ul><ul><ul><li>The following expressions are not allowed: </li></ul></ul><ul><ul><ul><li>References to CURRVAL , NEXTVAL , LEVEL , and ROWNUM pseudocolumns </li></ul></ul></ul><ul><ul><ul><li>Calls to SYSDATE , UID , USER , and USERENV functions </li></ul></ul></ul><ul><ul><ul><li>Queries that refer to other values in other rows </li></ul></ul></ul>..., salary NUMBER(2) CONSTRAINT emp_salary_min CHECK (salary > 0),...
    131. 135. CREATE TABLE : Example CREATE TABLE employees ( employee_id NUMBER(6) CONSTRAINT emp_employee_id PRIMARY KEY , first_name VARCHAR2(20) , last_name VARCHAR2(25) CONSTRAINT emp_last_name_nn NOT NULL , email VARCHAR2(25) CONSTRAINT emp_email_nn NOT NULL CONSTRAINT emp_email_uk UNIQUE , phone_number VARCHAR2(20) , hire_date DATE CONSTRAINT emp_hire_date_nn NOT NULL , job_id VARCHAR2(10) CONSTRAINT emp_job_nn NOT NULL , salary NUMBER(8,2) CONSTRAINT emp_salary_ck CHECK (salary>0) , commission_pct NUMBER(2,2) , manager_id NUMBER(6) , department_id NUMBER(4) CONSTRAINT emp_dept_fk REFERENCES departments (department_id));
    132. 136. Violating Constraints <ul><li>Department 55 does not exist. </li></ul>UPDATE employees * ERROR at line 1: ORA-02291: integrity constraint (HR.EMP_DEPT_FK) violated - parent key not found UPDATE employees SET department_id = 55 WHERE department_id = 110;
    133. 137. Violating Constraints <ul><li>You cannot delete a row that contains a primary key that is used as a foreign key in another table. </li></ul>DELETE FROM departments WHERE department_id = 60; DELETE FROM departments * ERROR at line 1: ORA-02292: integrity constraint (HR.EMP_DEPT_FK) violated - child record found
    134. 138. Creating a Table by Using a Subquery <ul><ul><li>Create a table and insert rows by combining the CREATE TABLE statement and the AS subquery option. </li></ul></ul><ul><ul><li>Match the number of specified columns to the number of subquery columns. </li></ul></ul><ul><ul><li>Define columns with column names and default values. </li></ul></ul>CREATE TABLE table [( column , column ...)] AS subquery;
    135. 139. Creating a Table by Using a Subquery CREATE TABLE dept80 AS SELECT employee_id, last_name, salary*12 ANNSAL, hire_date FROM employees WHERE department_id = 80; Table created. DESCRIBE dept80
    136. 140. ALTER TABLE Statement <ul><li>Use the ALTER TABLE statement to: </li></ul><ul><ul><li>Add a new column </li></ul></ul><ul><ul><li>Modify an existing column </li></ul></ul><ul><ul><li>Define a default value for the new column </li></ul></ul><ul><ul><li>Drop a column </li></ul></ul>
    137. 141. Dropping a Table <ul><ul><li>All data and structure in the table are deleted. </li></ul></ul><ul><ul><li>Any pending transactions are committed. </li></ul></ul><ul><ul><li>All indexes are dropped. </li></ul></ul><ul><ul><li>All constraints are dropped. </li></ul></ul><ul><ul><li>You cannot roll back the DROP TABLE statement. </li></ul></ul>DROP TABLE dept80; Table dropped.
    138. 142. Summary <ul><li>In this lesson, you should have learned how to use the CREATE TABLE statement to create a table and include constraints. </li></ul><ul><ul><li>Categorize the main database objects </li></ul></ul><ul><ul><li>Review the table structure </li></ul></ul><ul><ul><li>List the data types that are available for columns </li></ul></ul><ul><ul><li>Create a simple table </li></ul></ul><ul><ul><li>Explain how constraints are created at the time of table creation </li></ul></ul><ul><ul><li>Describe how schema objects work </li></ul></ul>
    139. 143. Introduction to PL/SQL
    140. 144. Lesson Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Explain the need for PL/SQL </li></ul></ul><ul><ul><li>Explain the benefits of PL/SQL </li></ul></ul><ul><ul><li>Identify the different types of PL/SQL blocks </li></ul></ul><ul><ul><li>Use i SQL*Plus as a development environment for PL/SQL </li></ul></ul><ul><ul><li>Output messages in PL/SQL </li></ul></ul>
    141. 145. What Is PL/SQL? <ul><li>PL/SQL: </li></ul><ul><ul><li>Stands for Procedural Language extension to SQL </li></ul></ul><ul><ul><li>Is Oracle Corporation’s standard data access language for relational databases </li></ul></ul><ul><ul><li>Seamlessly integrates procedural constructs with SQL </li></ul></ul>
    142. 146. About PL/SQL <ul><li>PL/SQL: </li></ul><ul><ul><li>Provides a block structure for executable units of code. Maintenance of code is made easier with such a well-defined structure. </li></ul></ul><ul><ul><li>Provides procedural constructs such as: </li></ul></ul><ul><ul><ul><li>Variables, constants, and types </li></ul></ul></ul><ul><ul><ul><li>Control structures such as conditional statements and loops </li></ul></ul></ul><ul><ul><ul><li>Reusable program units that are written once and executed many times </li></ul></ul></ul>
    143. 147. PL/SQL Environment PL/SQL Engine Oracle Database Server SQL Statement Executor Procedural Statement Executor procedural SQL PL/SQL Block
    144. 148. Benefits of PL/SQL SQL IF...THEN SQL ELSE SQL END IF; SQL <ul><ul><li>Integration of procedural constructs with SQL </li></ul></ul><ul><ul><li>Improved performance </li></ul></ul>SQL 1 SQL 2 …
    145. 149. Benefits of PL/SQL <ul><ul><li>Modularized program development </li></ul></ul><ul><ul><li>Integration with Oracle tools </li></ul></ul><ul><ul><li>Portability </li></ul></ul><ul><ul><li>Exception handling </li></ul></ul>
    146. 150. Benefits of PL/SQL
    147. 151. PL/SQL Block Structure <ul><li>DECLARE (Optional) </li></ul><ul><ul><li>Variables, cursors, user-defined exceptions </li></ul></ul><ul><li>BEGIN (Mandatory) </li></ul><ul><ul><li>- SQL statements </li></ul></ul><ul><ul><li>- PL/SQL statements </li></ul></ul><ul><li>EXCEPTION (Optional) </li></ul><ul><ul><li>Actions to perform when errors occur </li></ul></ul><ul><li>END ; (Mandatory) </li></ul>
    148. 152. PL/SQL Block Structure
    149. 153. Block Types <ul><li>Anonymous Procedure Function </li></ul>[DECLARE] BEGIN --statements [EXCEPTION] END; PROCEDURE name IS BEGIN --statements [EXCEPTION] END; FUNCTION name RETURN datatype IS BEGIN --statements RETURN value; [EXCEPTION] END;
    150. 154. Block Types
    151. 155. Program Constructs Application triggers Application packages Application procedures or functions Anonymous blocks Tools Constructs Object types Database triggers Stored packages Stored procedures or functions Anonymous blocks Database Server Constructs Object types
    152. 156. Program Constructs
    153. 157. Create an Anonymous Block <ul><li>Type the anonymous block in the i SQL*Plus workspace: </li></ul>
    154. 158. Execute an Anonymous Block <ul><li>Click the Execute button to execute the anonymous block: </li></ul>PLSQL procedure successfully completed.
    155. 159. Test the Output of a PL/SQL Block <ul><ul><li>Enable output in i SQL*Plus with the command SET SERVEROUTPUT ON </li></ul></ul><ul><ul><li>Use a predefined Oracle package and its procedure: </li></ul></ul><ul><ul><ul><li>DBMS_OUTPUT.PUT_LINE </li></ul></ul></ul>SET SERVEROUTPUT ON … DBMS_OUTPUT.PUT_LINE( ' The First Name of the Employee is ' || f_name); …
    156. 160. Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Integrate SQL statements with PL/SQL program constructs </li></ul></ul><ul><ul><li>Identify the benefits of PL/SQL </li></ul></ul><ul><ul><li>Differentiate different PL/SQL block types </li></ul></ul><ul><ul><li>Use i SQL*Plus as the programming environment for PL/SQL </li></ul></ul><ul><ul><li>Output messages in PL/SQL </li></ul></ul>
    157. 161. Declaring PL/SQL Variables
    158. 162. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Identify valid and invalid identifiers </li></ul></ul><ul><ul><li>List the uses of variables </li></ul></ul><ul><ul><li>Declare and initialize variables </li></ul></ul><ul><ul><li>List and describe various data types </li></ul></ul><ul><ul><li>Identify the benefits of using %TYPE attribute </li></ul></ul><ul><ul><li>Declare, use, and print bind variables </li></ul></ul>
    159. 163. Use of Variables <ul><li>Variables can be used for: </li></ul><ul><ul><li>Temporary storage of data </li></ul></ul><ul><ul><li>Manipulation of stored values </li></ul></ul><ul><ul><li>Reusability </li></ul></ul>SELECT first_name, department_id INTO emp_fname, emp_deptno FROM … emp_fname emp_deptno Jennifer 10
    160. 164. Identifiers <ul><li>Identifiers are used for: </li></ul><ul><ul><li>Naming a variable </li></ul></ul><ul><ul><li>Providing a convention for variable names: </li></ul></ul><ul><ul><ul><li>Must start with a letter </li></ul></ul></ul><ul><ul><ul><li>Can include letters or numbers </li></ul></ul></ul><ul><ul><ul><li>Can include special characters such as dollar sign, underscore, and pound sign </li></ul></ul></ul><ul><ul><ul><li>Must limit the length to 30 characters </li></ul></ul></ul><ul><ul><ul><li>Must not be reserved words </li></ul></ul></ul>
    161. 165. Handling Variables in PL/SQL <ul><li>Variables are: </li></ul><ul><ul><li>Declared and initialized in the declarative section </li></ul></ul><ul><ul><li>Used and assigned new values in the executable section </li></ul></ul><ul><ul><li>Passed as parameters to PL/SQL subprograms </li></ul></ul><ul><ul><li>Used to hold the output of a PL/SQL subprogram </li></ul></ul>
    162. 166. Declaring and Initializing PL/SQL Variables Syntax: Examples: identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr ]; DECLARE emp_hiredate DATE; emp_deptno NUMBER(2) NOT NULL := 10; location VARCHAR2(13) := 'Atlanta'; c_comm CONSTANT NUMBER := 1400;
    163. 167. Declaring and Initializing PL/SQL Variables SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20); BEGIN DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); Myname := 'John'; DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); END; / SET SERVEROUTPUT ON DECLARE Myname VARCHAR2(20):= 'John'; BEGIN Myname := 'Steven'; DBMS_OUTPUT.PUT_LINE('My name is: '||Myname); END; / 1 2
    164. 168. Delimiters in String Literals SET SERVEROUTPUT ON DECLARE event VARCHAR2(15); BEGIN event := q'!Father's day!'; DBMS_OUTPUT.PUT_LINE('3rd Sunday in June is : '||event); event := q'[Mother's day]'; DBMS_OUTPUT.PUT_LINE('2nd Sunday in May is : '||event); END; /
    165. 169. Types of Variables <ul><ul><li>PL/SQL variables: </li></ul></ul><ul><ul><ul><li>Scalar </li></ul></ul></ul><ul><ul><ul><li>Composite </li></ul></ul></ul><ul><ul><ul><li>Reference </li></ul></ul></ul><ul><ul><ul><li>Large objects (LOB) </li></ul></ul></ul><ul><ul><li>Non-PL/SQL variables: Bind variables </li></ul></ul>
    166. 170. Types of Variables TRUE 25-JAN-01 Atlanta 256120.08 The soul of the lazy man desires, and has nothing; but the soul of the diligent shall be made rich.
    167. 171. Guidelines for Declaring and Initializing PL/SQL Variables <ul><ul><li>Follow naming conventions. </li></ul></ul><ul><ul><li>Use meaningful names for variables. </li></ul></ul><ul><ul><li>Initialize variables designated as NOT NULL and CONSTANT . </li></ul></ul><ul><ul><li>Initialize variables with the assignment operator (:=) or the DEFAULT keyword: </li></ul></ul><ul><ul><li>Declare one identifier per line for better readability and code maintenance. </li></ul></ul>Myname VARCHAR2(20):='John'; Myname VARCHAR2(20) DEFAULT 'John';
    168. 172. Guidelines for Declaring PL/SQL Variables <ul><ul><li>Avoid using column names as identifiers. </li></ul></ul>DECLARE employee_id NUMBER(6); BEGIN SELECT employee_id INTO employee_id FROM employees WHERE last_name = 'Kochhar'; END; / <ul><ul><li>Use the NOT NULL constraint when the variable must hold a value. </li></ul></ul>
    169. 173. Scalar Data Types <ul><ul><li>Hold a single value </li></ul></ul><ul><ul><li>Have no internal components </li></ul></ul>Atlanta TRUE 25-JAN-01 256120.08 The soul of the lazy man desires, and has nothing; but the soul of the diligent shall be made rich.
    170. 174. Base Scalar Data Types <ul><ul><li>CHAR [(maximum_length)] </li></ul></ul><ul><ul><li>VARCHAR2 (maximum_length) </li></ul></ul><ul><ul><li>LONG </li></ul></ul><ul><ul><li>LONG RAW </li></ul></ul><ul><ul><li>NUMBER [(precision, scale)] </li></ul></ul><ul><ul><li>BINARY_INTEGER </li></ul></ul><ul><ul><li>PLS_INTEGER </li></ul></ul><ul><ul><li>BOOLEAN </li></ul></ul><ul><ul><li>BINARY_FLOAT </li></ul></ul><ul><ul><li>BINARY_DOUBLE </li></ul></ul>
    171. 176. Base Scalar Data Types <ul><ul><li>DATE </li></ul></ul><ul><ul><li>TIMESTAMP </li></ul></ul><ul><ul><li>TIMESTAMP WITH TIME ZONE </li></ul></ul><ul><ul><li>TIMESTAMP WITH LOCAL TIME ZONE </li></ul></ul><ul><ul><li>INTERVAL YEAR TO MONTH </li></ul></ul><ul><ul><li>INTERVAL DAY TO SECOND </li></ul></ul>
    172. 178. BINARY_FLOAT and BINARY_DOUBLE <ul><ul><li>Represent floating point numbers in IEEE (Institute of Electrical and Electronics Engineers) 754 format </li></ul></ul><ul><ul><li>Offer better interoperability and operational speed </li></ul></ul><ul><ul><li>Store values beyond the values that the data type NUMBER can store </li></ul></ul><ul><ul><li>Offer benefits of closed arithmetic operations and transparent rounding </li></ul></ul>
    173. 179. BINARY_FLOAT and BINARY_DOUBLE
    174. 180. Declaring Scalar Variables <ul><li>Examples: </li></ul>DECLARE emp_job VARCHAR2(9); count_loop BINARY_INTEGER := 0; dept_total_sal NUMBER(9,2) := 0; orderdate DATE := SYSDATE + 7; c_tax_rate CONSTANT NUMBER(3,2) := 8.25; valid BOOLEAN NOT NULL := TRUE; ...
    175. 181. The %TYPE Attribute <ul><li>The %TYPE attribute </li></ul><ul><ul><li>Is used to declare a variable according to: </li></ul></ul><ul><ul><ul><li>A database column definition </li></ul></ul></ul><ul><ul><ul><li>Another declared variable </li></ul></ul></ul><ul><ul><li>Is prefixed with: </li></ul></ul><ul><ul><ul><li>The database table and column </li></ul></ul></ul><ul><ul><ul><li>The name of the declared variable </li></ul></ul></ul>
    176. 182. The %TYPE Attribute
    177. 183. Declaring Variables with the %TYPE Attribute <ul><li>Syntax: </li></ul><ul><li>Examples: </li></ul>... emp_lname employees.last_name%TYPE; balance NUMBER(7,2); min_balance balance%TYPE := 1000; ... identifier table.column_name%TYPE;
    178. 184. Declaring Boolean Variables <ul><ul><li>Only the values TRUE , FALSE , and NULL can be assigned to a Boolean variable. </li></ul></ul><ul><ul><li>Conditional expressions use logical operators AND , OR , and unary operator NOT to check the variable values. </li></ul></ul><ul><ul><li>The variables always yield TRUE , FALSE , or NULL . </li></ul></ul><ul><ul><li>Arithmetic, character, and date expressions can be used to return a Boolean value. </li></ul></ul>
    179. 185. Bind Variables <ul><li>Bind variables are: </li></ul><ul><ul><li>Created in the environment </li></ul></ul><ul><ul><li>Also called host variables </li></ul></ul><ul><ul><li>Created with the VARIABLE keyword </li></ul></ul><ul><ul><li>Used in SQL statements and PL/SQL blocks </li></ul></ul><ul><ul><li>Accessed even after the PL/SQL block is executed </li></ul></ul><ul><ul><li>Referenced with a preceding colon </li></ul></ul>
    180. 187. Printing Bind Variables <ul><li>Example: </li></ul>VARIABLE emp_salary NUMBER BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = 178; END; / PRINT emp_salary SELECT first_name, last_name FROM employees WHERE salary=:emp_salary;
    181. 188. Printing Bind Variables <ul><li>Example: </li></ul>VARIABLE emp_salary NUMBER SET AUTOPRINT ON BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = 178; END; /
    182. 189. Substitution Variables <ul><ul><li>Are used to get user input at run time </li></ul></ul><ul><ul><li>Are referenced within a PL/SQL block with a preceding ampersand </li></ul></ul><ul><ul><li>Are used to avoid hard coding values that can be obtained at run time </li></ul></ul>VARIABLE emp_salary NUMBER SET AUTOPRINT ON DECLARE empno NUMBER(6):=&empno; BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = empno; END; /
    183. 190. Substitution Variables 1 2 3
    184. 191. Prompt for Substitution Variables SET VERIFY OFF VARIABLE emp_salary NUMBER ACCEPT empno PROMPT 'Please enter a valid employee number: ' SET AUTOPRINT ON DECLARE empno NUMBER(6):= &empno; BEGIN SELECT salary INTO :emp_salary FROM employees WHERE employee_id = empno; END; /
    185. 192. Using DEFINE for User Variable <ul><li>Example: </li></ul>SET VERIFY OFF DEFINE lname= Urman DECLARE fname VARCHAR2(25); BEGIN SELECT first_name INTO fname FROM employees WHERE last_name='&lname'; END; /
    186. 193. Composite Data Types TRUE 23-DEC-98 ATLANTA 1 5000 2 2345 3 12 4 3456 1 SMITH 2 JONES 3 NANCY 4 TIM PL/SQL table structure PL/SQL table structure PLS_INTEGER VARCHAR2 PLS_INTEGER NUMBER
    187. 194. LOB Data Type Variables Book ( CLOB ) Photo ( BLOB ) Movie ( BFILE ) NCLOB
    188. 195. Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Identify valid and invalid identifiers </li></ul></ul><ul><ul><li>Declare variables in the declarative section of a PL/SQL block </li></ul></ul><ul><ul><li>Initialize variables and utilize them in the executable section </li></ul></ul><ul><ul><li>Differentiate between scalar and composite data types </li></ul></ul><ul><ul><li>Use the %TYPE attribute </li></ul></ul><ul><ul><li>Make use of bind variables </li></ul></ul>
    189. 196. Interacting with the Oracle Server
    190. 197. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Decide which SQL statements can be directly included in a PL/SQL executable block </li></ul></ul><ul><ul><li>Manipulate data with DML statements in PL/SQL </li></ul></ul><ul><ul><li>Use transaction control statements in PL/SQL </li></ul></ul><ul><ul><li>Make use of the INTO clause to hold the values returned by a SQL statement </li></ul></ul><ul><ul><li>Differentiate between implicit cursors and explicit cursors </li></ul></ul><ul><ul><li>Use SQL cursor attributes </li></ul></ul>
    191. 198. SQL Statements in PL/SQL <ul><ul><li>Retrieve a row from the database by using the SELECT command. </li></ul></ul><ul><ul><li>Make changes to rows in the database by using DML commands. </li></ul></ul><ul><ul><li>Control a transaction with the COMMIT , ROLLBACK , or SAVEPOINT command. </li></ul></ul>
    192. 199. SQL Statements in PL/SQL
    193. 200. SELECT Statements in PL/SQL <ul><li>Retrieve data from the database with a SELECT statement. </li></ul><ul><li>Syntax: </li></ul>SELECT select_list INTO { variable_name [, variable_name ] ... | record_name } FROM table [WHERE condition ];
    194. 202. SELECT Statements in PL/SQL <ul><ul><li>The INTO clause is required. </li></ul></ul><ul><ul><li>Queries must return only one row. </li></ul></ul><ul><li>Example: </li></ul>SET SERVEROUTPUT ON DECLARE fname VARCHAR2(25); BEGIN SELECT first_name INTO fname FROM employees WHERE employee_id=200; DBMS_OUTPUT.PUT_LINE(' First Name is : '||fname); END; /
    195. 203. SELECT Statements in PL/SQL
    196. 204. Retrieving Data in PL/SQL <ul><li>Retrieve the hire_date and the salary for the specified employee. </li></ul><ul><li>Example: </li></ul>DECLARE emp_hiredate employees.hire_date%TYPE; emp_salary employees.salary%TYPE; BEGIN SELECT hire_date, salary INTO emp_hiredate, emp_salary FROM employees WHERE employee_id = 100; END; /
    197. 205. Retrieving Data in PL/SQL <ul><li>Return the sum of the salaries for all the employees in the specified department. </li></ul><ul><li>Example: </li></ul>SET SERVEROUTPUT ON DECLARE sum_sal NUMBER(10,2); deptno NUMBER NOT NULL := 60; BEGIN SELECT SUM(salary) -- group function INTO sum_sal FROM employees WHERE department_id = deptno; DBMS_OUTPUT.PUT_LINE ('The sum of salary is ' || sum_sal); END; /
    198. 206. Naming Conventions <ul><li>DECLARE </li></ul><ul><li>hire_date employees.hire_date%TYPE; </li></ul><ul><li>sysdate hire_date%TYPE; </li></ul><ul><li>employee_id employees.employee_id%TYPE := 176; </li></ul><ul><li>BEGIN </li></ul><ul><li>SELECT hire_date, sysdate </li></ul><ul><li>INTO hire_date, sysdate </li></ul><ul><li>FROM employees </li></ul><ul><li>WHERE employee_id = employee_id; </li></ul><ul><li>END; </li></ul><ul><li>/ </li></ul>
    199. 207. Naming Conventions <ul><ul><li>Use a naming convention to avoid ambiguity in the WHERE clause. </li></ul></ul><ul><ul><li>Avoid using database column names as identifiers. </li></ul></ul><ul><ul><li>Syntax errors can arise because PL/SQL checks the database first for a column in the table. </li></ul></ul><ul><ul><li>The names of local variables and formal parameters take precedence over the names of database tables . </li></ul></ul><ul><ul><li>The names of database table columns take precedence over the names of local variables. </li></ul></ul>
    200. 208. Manipulating Data Using PL/SQL <ul><li>Make changes to database tables by using DML commands: </li></ul><ul><ul><li>INSERT </li></ul></ul><ul><ul><li>UPDATE </li></ul></ul><ul><ul><li>DELETE </li></ul></ul><ul><ul><li>MERGE </li></ul></ul>INSERT UPDATE DELETE MERGE
    201. 209. Inserting Data <ul><li>Add new employee information to the EMPLOYEES table. </li></ul><ul><li>Example: </li></ul>BEGIN INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, job_id, salary) VALUES(employees_seq.NEXTVAL, 'Ruth', 'Cores', 'RCORES',sysdate, 'AD_ASST', 4000); END; /
    202. 210. Updating Data <ul><li>Increase the salary of all employees who are stock clerks. </li></ul><ul><li>Example: </li></ul>DECLARE sal_increase employees.salary%TYPE := 800; BEGIN UPDATE employees SET salary = salary + sal_increase WHERE job_id = 'ST_CLERK'; END; /
    203. 211. Deleting Data <ul><li>Delete rows that belong to department 10 from the employees table. </li></ul><ul><li>Example: </li></ul>DECLARE deptno employees.department_id%TYPE := 10; BEGIN DELETE FROM employees WHERE department_id = deptno; END; /
    204. 212. Merging Rows <ul><li>Insert or update rows in the copy_emp table to match the employees table. </li></ul>DECLARE empno employees.employee_id%TYPE := 100; BEGIN MERGE INTO copy_emp c USING employees e ON (e.employee_id = empno) WHEN MATCHED THEN UPDATE SET c.first_name = e.first_name, c.last_name = e.last_name, c.email = e.email, . . . WHEN NOT MATCHED THEN INSERT VALUES(e.employee_id, e.first_name, e.last_name, . . .,e.department_id); END; /
    205. 214. SQL Cursor <ul><ul><li>A cursor is a pointer to the private memory area allocated by the Oracle server. </li></ul></ul><ul><ul><li>There are two types of cursors: </li></ul></ul><ul><ul><ul><li>Implicit cursors: Created and managed internally by the Oracle server to process SQL statements </li></ul></ul></ul><ul><ul><ul><li>Explicit cursors: Explicitly declared by the programmer </li></ul></ul></ul>
    206. 216. SQL Cursor Attributes for Implicit Cursors <ul><li>Using SQL cursor attributes, you can test the outcome of your SQL statements. </li></ul>Boolean attribute that evaluates to TRUE if the most recent SQL statement did not return even one row. SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement returned at least one row. SQL%FOUND An integer value that represents number of rows affected by the most recent SQL statement. SQL%ROWCOUNT
    207. 217. SQL Cursor Attributes for Implicit Cursors <ul><li>Delete rows that have the specified employee ID from the employees table. Print the number of rows deleted. </li></ul><ul><li>Example: </li></ul>VARIABLE rows_deleted VARCHAR2(30) DECLARE empno employees.employee_id%TYPE := 176; BEGIN DELETE FROM employees WHERE employee_id = empno; :rows_deleted := (SQL%ROWCOUNT || ' row deleted.'); END; / PRINT rows_deleted
    208. 218. Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Embed DML statements, transaction control statements, and DDL statements in PL/SQL </li></ul></ul><ul><ul><li>Use the INTO clause, which is mandatory for all SELECT statements in PL/SQL </li></ul></ul><ul><ul><li>Differentiate between implicit cursors and explicit cursors </li></ul></ul><ul><ul><li>Use SQL cursor attributes to determine the outcome of SQL statements </li></ul></ul>
    209. 219. Writing Control Structures
    210. 220. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Identify the uses and types of control structures </li></ul></ul><ul><ul><li>Construct an IF statement </li></ul></ul><ul><ul><li>Use CASE statements and CASE expressions </li></ul></ul><ul><ul><li>Construct and identify different loop statements </li></ul></ul><ul><ul><li>Make use of guidelines while using the conditional control structures </li></ul></ul>
    211. 221. Controlling Flow of Execution for loop while
    212. 222. IF Statements <ul><li>Syntax: </li></ul>IF condition THEN statements ; [ELSIF condition THEN statements ;] [ELSE statements ;] END IF;
    213. 223. IF Statements
    214. 224. Simple IF Statement DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); END IF; END; /
    215. 225. IF THEN ELSE Statement SET SERVEROUTPUT ON DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; /
    216. 226. IF ELSIF ELSE Clause DECLARE myage number:=31; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSIF myage < 20 THEN DBMS_OUTPUT.PUT_LINE(' I am young '); ELSIF myage < 30 THEN DBMS_OUTPUT.PUT_LINE(' I am in my twenties'); ELSIF myage < 40 THEN DBMS_OUTPUT.PUT_LINE(' I am in my thirties'); ELSE DBMS_OUTPUT.PUT_LINE(' I am always young '); END IF; END; /
    217. 227. NULL Values in IF Statements DECLARE myage number; BEGIN IF myage < 11 THEN DBMS_OUTPUT.PUT_LINE(' I am a child '); ELSE DBMS_OUTPUT.PUT_LINE(' I am not a child '); END IF; END; /
    218. 228. CASE Expressions <ul><ul><li>A CASE expression selects a result and returns it. </li></ul></ul><ul><ul><li>To select the result, the C ASE expression uses expressions. The value returned by these expressions is used to select one of several alternatives. </li></ul></ul>CASE selector WHEN expression1 THEN result1 WHEN expression2 THEN result2 ... WHEN expressionN THEN resultN [ELSE resultN+1] END; /
    219. 229. CASE Expressions: Example SET SERVEROUTPUT ON SET VERIFY OFF DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal := CASE grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| grade || ' Appraisal ' || appraisal); END; /
    220. 230. Searched CASE Expressions DECLARE grade CHAR(1) := UPPER('&grade'); appraisal VARCHAR2(20); BEGIN appraisal := CASE WHEN grade = 'A' THEN 'Excellent' WHEN grade IN ('B','C') THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| grade || ' Appraisal ' || appraisal); END; /
    221. 231. CASE Statement DECLARE deptid NUMBER; deptname VARCHAR2(20); emps NUMBER; mngid NUMBER:= 108; BEGIN CASE mngid WHEN 108 THEN SELECT department_id, department_name INTO deptid, deptname FROM departments WHERE manager_id=108; SELECT count(*) INTO emps FROM employees WHERE department_id=deptid; WHEN 200 THEN ... END CASE; DBMS_OUTPUT.PUT_LINE ('You are working in the '|| deptname|| ' department. There are '||emps ||' employees in this department'); END; /
    222. 232. Handling Nulls <ul><li>When working with nulls, you can avoid some common mistakes by keeping in mind the following rules: </li></ul><ul><ul><li>Simple comparisons involving nulls always yield NULL . </li></ul></ul><ul><ul><li>Applying the logical operator NOT to a null yields NULL . </li></ul></ul><ul><ul><li>In conditional control statements, if the condition yields NULL , its associated sequence of statements is not executed. </li></ul></ul>
    223. 233. Logic Tables <ul><li>Build a simple Boolean condition with a comparison operator. </li></ul>AND TRUE FALSE NULL TRUE FALSE NULL TRUE NULL NULL NULL FALSE FALSE FALSE FALSE FALSE NOT TRUE FALSE NULL FALSE TRUE NULL TRUE NULL OR TRUE FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSE NULL NULL NULL FALSE
    224. 234. Boolean Conditions <ul><li>What is the value of flag in each case? </li></ul>REORDER_FLAG AVAILABLE_FLAG FLAG TRUE TRUE TRUE FALSE NULL TRUE NULL FALSE flag := reorder_flag AND available_flag; ? ? ? ?
    225. 235. Iterative Control: LOOP Statements <ul><ul><li>Loops repeat a statement or sequence of statements multiple times. </li></ul></ul><ul><ul><li>There are three loop types: </li></ul></ul><ul><ul><ul><li>Basic loop </li></ul></ul></ul><ul><ul><ul><li>FOR loop </li></ul></ul></ul><ul><ul><ul><li>WHILE loop </li></ul></ul></ul>
    226. 236. Basic Loops <ul><li>Syntax: </li></ul>LOOP statement1 ; . . . EXIT [WHEN condition ]; END LOOP;
    227. 237. Basic Loops <ul><li>Example: </li></ul>DECLARE countryid locations.country_id%TYPE := 'CA'; loc_id locations.location_id%TYPE; counter NUMBER(2) := 1; new_city locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid; LOOP INSERT INTO locations(location_id, city, country_id) VALUES((loc_id + counter), new_city, countryid); counter := counter + 1; EXIT WHEN counter > 3; END LOOP; END; /
    228. 238. WHILE Loops <ul><li>Syntax: </li></ul><ul><li>Use the WHILE loop to repeat statements while a condition is TRUE . </li></ul>WHILE condition LOOP statement1; statement2; . . . END LOOP;
    229. 239. WHILE Loops <ul><li>Example: </li></ul>DECLARE countryid locations.country_id%TYPE := 'CA'; loc_id locations.location_id%TYPE; new_city locations.city%TYPE := 'Montreal'; counter NUMBER := 1; BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid; WHILE counter <= 3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((loc_id + counter), new_city, countryid); counter := counter + 1; END LOOP; END; /
    230. 240. FOR Loops <ul><ul><li>Use a FOR loop to shortcut the test for the number of iterations. </li></ul></ul><ul><ul><li>Do not declare the counter; it is declared implicitly. </li></ul></ul><ul><ul><li>' lower_bound .. upper_bound ' is required syntax. </li></ul></ul>FOR counter IN [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . . END LOOP;
    231. 241. FOR Loops
    232. 242. FOR Loops <ul><li>Example: </li></ul>DECLARE countryid locations.country_id%TYPE := 'CA'; loc_id locations.location_id%TYPE; new_city locations.city%TYPE := 'Montreal'; BEGIN SELECT MAX(location_id) INTO loc_id FROM locations WHERE country_id = countryid; FOR i IN 1..3 LOOP INSERT INTO locations(location_id, city, country_id) VALUES((loc_id + i), new_city, countryid ); END LOOP; END; /
    233. 243. FOR Loops <ul><li>Guidelines </li></ul><ul><ul><li>Reference the counter within the loop only; it is undefined outside the loop. </li></ul></ul><ul><ul><li>Do not reference the counter as the target of an assignment. </li></ul></ul><ul><ul><li>Neither loop bound should be NULL . </li></ul></ul>
    234. 244. Guidelines While Using Loops <ul><ul><li>Use the basic loop when the statements inside the loop must execute at least once. </li></ul></ul><ul><ul><li>Use the WHILE loop if the condition has to be evaluated at the start of each iteration. </li></ul></ul><ul><ul><li>Use a FOR loop if the number of iterations is known. </li></ul></ul>
    235. 245. Nested Loops and Labels <ul><ul><li>Nest loops to multiple levels. </li></ul></ul><ul><ul><li>Use labels to distinguish between blocks and loops. </li></ul></ul><ul><ul><li>Exit the outer loop with the EXIT statement that references the label. </li></ul></ul>
    236. 246. Nested Loops and Labels ... BEGIN <<Outer_loop>> LOOP counter := counter+1; EXIT WHEN counter>10; <<Inner_loop>> LOOP ... EXIT Outer_loop WHEN total_done = 'YES'; -- Leave both loops EXIT WHEN inner_ done = 'YES'; -- Leave inner loop only ... END LOOP Inner_loop ; ... END LOOP Outer_loop ; END; /
    237. 247. Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><li>Change the logical flow of statements by using the following control structures. </li></ul><ul><ul><li>Conditional ( IF statement) </li></ul></ul><ul><ul><li>CASE expressions and CASE statements </li></ul></ul><ul><ul><li>Loops: </li></ul></ul><ul><ul><ul><li>Basic loop </li></ul></ul></ul><ul><ul><ul><li>FOR loop </li></ul></ul></ul><ul><ul><ul><li>WHILE loop </li></ul></ul></ul><ul><ul><li>EXIT statements </li></ul></ul>
    238. 248. Working with Composite Data Types
    239. 249. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Create user-defined PL/SQL records </li></ul></ul><ul><ul><li>Create a record with the %ROWTYPE attribute </li></ul></ul><ul><ul><li>Create an INDEX BY table </li></ul></ul><ul><ul><li>Create an INDEX BY table of records </li></ul></ul><ul><ul><li>Describe the difference between records, tables, and tables of records </li></ul></ul>
    240. 250. Composite Data Types <ul><ul><li>Can hold multiple values, unlike scalar types </li></ul></ul><ul><ul><li>Are of two types: </li></ul></ul><ul><ul><ul><li>PL/SQL records </li></ul></ul></ul><ul><ul><ul><li>PL/SQL collections </li></ul></ul></ul><ul><ul><ul><ul><ul><li>INDEX BY tables or associative arrays </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>Nested table </li></ul></ul></ul></ul></ul><ul><ul><ul><ul><ul><li>VARRAY </li></ul></ul></ul></ul></ul>
    241. 251. Composite Data Types <ul><ul><li>Use PL/SQL records when you want to store values of different data types but only one occurrence at a time. </li></ul></ul><ul><ul><li>Use PL/SQL collections when you want to store values of same data type. </li></ul></ul>
    242. 252. PL/SQL Records <ul><ul><li>Must contain one or more components of any scalar, RECORD , or INDEX BY table data type, called fields </li></ul></ul><ul><ul><li>Are similar to structures in most 3GL languages including C and C++ </li></ul></ul><ul><ul><li>Are user defined and can be a subset of a row in a table </li></ul></ul><ul><ul><li>Treat a collection of fields as a logical unit </li></ul></ul><ul><ul><li>Are convenient for fetching a row of data from a table for processing </li></ul></ul>
    243. 253. Creating a PL/SQL Record <ul><li>Syntax: </li></ul>TYPE type_name IS RECORD ( field_declaration[, field_declaration]…); field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr ] identifier type_name; 1 2 field_declaration :
    244. 254. Creating a PL/SQL Record <ul><li>Declare variables to store the name, job, and salary of a new employee. </li></ul><ul><li>Example: </li></ul>... TYPE emp_record_type IS RECORD (last_name VARCHAR2(25), job_id VARCHAR2(10), salary NUMBER(8,2)); emp_record emp_record_type; ...
    245. 255. PL/SQL Record Structure Example: 100 King AD_PRES employee_id number(6) last_name varchar2(25) job_id varchar2(10) Field2 (data type) Field3 (data type) Field1 (data type) Field2 (data type) Field3 (data type) Field1 (data type)
    246. 256. The %ROWTYPE Attribute <ul><ul><li>Declare a variable according to a collection of columns in a database table or view. </li></ul></ul><ul><ul><li>Prefix %ROWTYPE with the database table or view. </li></ul></ul><ul><ul><li>Fields in the record take their names and data types from the columns of the table or view. </li></ul></ul>DECLARE identifier reference%ROWTYPE; Syntax:
    247. 257. The %ROWTYPE Attribute <ul><ul><li>Declare a variable according to a collection of columns in a database table or view. </li></ul></ul><ul><ul><li>Prefix %ROWTYPE with the database table. </li></ul></ul><ul><ul><li>Fields in the record take their names and data types from the columns of the table or view. </li></ul></ul>
    248. 258. Advantages of Using %ROWTYPE <ul><ul><li>The number and data types of the underlying database columns need not be known. </li></ul></ul><ul><ul><li>The number and data types of the underlying database column may change at run time. </li></ul></ul><ul><ul><li>The attribute is useful when retrieving a row with the SELECT * statement. </li></ul></ul>
    249. 259. The %ROWTYPE Attribute ... DEFINE employee_number = 124 DECLARE emp_rec employees%ROWTYPE; BEGIN SELECT * INTO emp_rec FROM employees WHERE employee_id = &employee_number; INSERT INTO retired_emps(empno, ename, job, mgr, hiredate, leavedate, sal, comm, deptno) VALUES (emp_rec.employee_id, emp_rec.last_name, emp_rec.job_id,emp_rec.manager_id, emp_rec.hire_date, SYSDATE, emp_rec.salary, emp_rec.commission_pct, emp_rec.department_id); END; /
    250. 260. Inserting a Record Using %ROWTYPE ... DEFINE employee_number = 124 DECLARE emp_rec retired_emps%ROWTYPE; BEGIN SELECT employee_id, last_name, job_id, manager_id, hire_date, hire_date, salary, commission_pct, department_id INTO emp_rec FROM employees WHERE employee_id = &employee_number; INSERT INTO retired_emps VALUES emp_rec; END; / SELECT * FROM retired_emps;
    251. 261. Updating a Row in a Table Using a Record SET SERVEROUTPUT ON SET VERIFY OFF DEFINE employee_number = 124 DECLARE emp_rec retired_emps%ROWTYPE; BEGIN SELECT * INTO emp_rec FROM retired_emps; emp_rec.leavedate:=SYSDATE; UPDATE retired_emps SET ROW = emp_rec WHERE empno=&employee_number; END; / SELECT * FROM retired_emps;
    252. 262. INDEX BY Tables or Associative Arrays <ul><ul><li>Are PL/SQL structures with two columns: </li></ul></ul><ul><ul><ul><li>Primary key type integer or string </li></ul></ul></ul><ul><ul><ul><li>Column of scalar or record data type </li></ul></ul></ul><ul><ul><li>Are unconstrained in size. However the size depends on the values the key data type can hold. </li></ul></ul>
    253. 263. Creating an INDEX BY Table <ul><li>Syntax: </li></ul>TYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] | table%ROWTYPE [INDEX BY PLS_INTEGER | BINARY_INTEGER | VARCHAR2(< size >)]; identifier type_name; ... TYPE ename_table_type IS TABLE OF employees.last_name%TYPE INDEX BY PLS_INTEGER; ... ename_table ename_table_type; Declare an INDEX BY table to store the last names of employees.
    254. 264. Creating an INDEX BY Table
    255. 265. INDEX BY Table Structure Unique Key Value ... ... 1 Jones 5 Smith 3 Maduro ... ... PLS_INTEGER Scalar
    256. 266. Creating an INDEX BY Table <ul><li>DECLARE </li></ul><ul><li>TYPE ename_table_type IS TABLE OF </li></ul><ul><li>employees.last_name%TYPE </li></ul><ul><li>INDEX BY PLS_INTEGER; </li></ul><ul><li>TYPE hiredate_table_type IS TABLE OF DATE </li></ul><ul><li>INDEX BY PLS_INTEGER; </li></ul><ul><li>ename_table ename_table_type; </li></ul><ul><li>hiredate_table hiredate_table_type; </li></ul><ul><li>BEGIN </li></ul><ul><li>ename_table(1) := 'CAMERON'; </li></ul><ul><li>hiredate_table(8) := SYSDATE + 7; </li></ul><ul><li>IF ename_table.EXISTS(1) THEN </li></ul><ul><li>INSERT INTO ... </li></ul><ul><li>... </li></ul><ul><li>END; </li></ul><ul><li>/ </li></ul>
    257. 267. Using INDEX BY Table Methods <ul><li>The following methods make INDEX BY tables easier to use: </li></ul><ul><ul><li>NEXT </li></ul></ul><ul><ul><li>TRIM </li></ul></ul><ul><ul><li>DELETE </li></ul></ul><ul><ul><li>EXISTS </li></ul></ul><ul><ul><li>COUNT </li></ul></ul><ul><ul><li>FIRST and LAST </li></ul></ul><ul><ul><li>PRIOR </li></ul></ul>
    258. 268. INDEX BY Table of Records <ul><li>Define an INDEX BY table variable to hold an entire row from a table. </li></ul><ul><li>Example: </li></ul>DECLARE TYPE dept_table_type IS TABLE OF departments%ROWTYPE INDEX BY PLS_INTEGER; dept_table dept_table_type; -- Each element of dept_table is a record
    259. 269. INDEX BY Table of Records
    260. 270. Example of INDEX BY Table of Records SET SERVEROUTPUT ON DECLARE TYPE emp_table_type IS TABLE OF employees%ROWTYPE INDEX BY PLS_INTEGER; my_emp_table emp_table_type; max_count NUMBER(3):= 104; BEGIN FOR i IN 100..max_count LOOP SELECT * INTO my_emp_table(i) FROM employees WHERE employee_id = i; END LOOP; FOR i IN my_emp_table.FIRST..my_emp_table.LAST LOOP DBMS_OUTPUT.PUT_LINE(my_emp_table(i).last_name); END LOOP; END; /
    261. 271. Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Define and reference PL/SQL variables of composite data types: </li></ul></ul><ul><ul><ul><li>PL/SQL records </li></ul></ul></ul><ul><ul><ul><li>INDEX BY tables </li></ul></ul></ul><ul><ul><ul><li>INDEX BY table of records </li></ul></ul></ul><ul><ul><li>Define a PL/SQL record by using the %ROWTYPE attribute </li></ul></ul>
    262. 272. Using Explicit Cursors
    263. 273. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Distinguish between an implicit and an explicit cursor </li></ul></ul><ul><ul><li>Discuss when and why to use an explicit cursor </li></ul></ul><ul><ul><li>Declare and control explicit cursors </li></ul></ul><ul><ul><li>Use simple loop and cursor FOR loop to fetch data </li></ul></ul><ul><ul><li>Declare and use cursors with parameters </li></ul></ul><ul><ul><li>Lock rows using the FOR UPDATE clause </li></ul></ul><ul><ul><li>Reference the current row with the WHERE CURRENT clause </li></ul></ul>
    264. 274. About Cursors <ul><li>Every SQL statement executed by the Oracle Server has an individual cursor associated with it: </li></ul><ul><ul><li>Implicit cursors: Declared and managed by PL/SQL for all DML and PL/SQL SELECT statements </li></ul></ul><ul><ul><li>Explicit cursors: Declared and managed by the programmer </li></ul></ul>
    265. 275. Explicit Cursor Operations Active set Table 100 King AD_PRES 101 Kochhar AD_VP 102 De Haan AD_VP . . . . . . . . . 139 Seo ST_CLERK 140 Patel ST_CLERK . . .
    266. 276. Controlling Explicit Cursors <ul><li>Load the current row into variables </li></ul>FETCH <ul><li>Test for existing rows </li></ul>EMPTY? <ul><li>Return to FETCH if rows are found </li></ul>No <ul><li>Release the active set </li></ul>CLOSE Yes <ul><li>Create a named SQL area </li></ul>DECLARE <ul><li>Identify the active set </li></ul>OPEN
    267. 277. Controlling Explicit Cursors Fetch a row. Close the cursor. Cursor pointer Open the cursor. 1 2 3 Cursor pointer Cursor pointer
    268. 278. Declaring the Cursor <ul><li>Syntax: </li></ul>CURSOR cursor_name IS select_statement; Examples: DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; DECLARE locid NUMBER:= 1700; CURSOR dept_cursor IS SELECT * FROM departments WHERE location_id = locid; ...
    269. 279. Declaring the Cursor
    270. 280. Opening the Cursor DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; ... BEGIN OPEN emp_cursor;
    271. 281. Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; empno employees.employee_id%TYPE; lname employees.last_name%TYPE; BEGIN OPEN emp_cursor; FETCH emp_cursor INTO empno, lname; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname); ... END; /
    272. 282. Fetching Data from the Cursor
    273. 283. Fetching Data from the Cursor SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; empno employees.employee_id%TYPE; lname employees.last_name%TYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO empno, lname; EXIT WHEN emp_cursor%NOTFOUND ; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname); END LOOP; ... END; /
    274. 284. Closing the Cursor ... LOOP FETCH emp_cursor INTO empno, lname; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE( empno ||' '||lname); END LOOP; CLOSE emp_cursor; END; /
    275. 285. Cursors and Records <ul><li>Process the rows of the active set by fetching values into a PL/SQL RECORD . </li></ul>DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; emp_record emp_cursor%ROWTYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO emp_record; ...
    276. 286. Cursor FOR Loops <ul><li>Syntax: </li></ul><ul><ul><li>The cursor FOR loop is a shortcut to process explicit cursors. </li></ul></ul><ul><ul><li>Implicit open, fetch, exit, and close occur. </li></ul></ul><ul><ul><li>The record is implicitly declared. </li></ul></ul>FOR record_name IN cursor_name LOOP statement1 ; statement2 ; . . . END LOOP;
    277. 287. Cursor FOR Loops SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees WHERE department_id =30; BEGIN FOR emp_record IN emp_cursor LOOP DBMS_OUTPUT.PUT_LINE( emp_record.employee_id ||' ' || emp_record.last_name ); END LOOP; END; /
    278. 288. Explicit Cursor Attributes <ul><li>Obtain status information about a cursor. </li></ul>Boolean Evaluates to TRUE if the cursor is open Evaluates to TRUE if the most recent fetch does not return a row Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND Evaluates to the total number of rows returned so far Boolean Boolean Number %ISOPEN %NOTFOUND %FOUND %ROWCOUNT Attribute Type Description
    279. 289. The %ISOPEN Attribute <ul><ul><li>Fetch rows only when the cursor is open. </li></ul></ul><ul><ul><li>Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. </li></ul></ul><ul><li>Example: </li></ul>IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; END IF; LOOP FETCH emp_cursor...
    280. 290. Example of %ROWCOUNT and %NOTFOUND SET SERVEROUTPUT ON DECLARE empno employees.employee_id%TYPE; ename employees.last_name%TYPE; CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO empno, ename; EXIT WHEN emp_cursor%ROWCOUNT > 10 OR emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE(TO_CHAR(empno) ||' '|| ename); END LOOP; CLOSE emp_cursor; END ; /
    281. 291. Cursor FOR Loops Using Subqueries <ul><li>No need to declare the cursor. </li></ul><ul><li>Example: </li></ul>SET SERVEROUTPUT ON BEGIN FOR emp_record IN (SELECT employee_id, last_name FROM employees WHERE department_id =30) LOOP DBMS_OUTPUT.PUT_LINE( emp_record.employee_id ||' '||emp_record.last_name); END LOOP; END; /
    282. 292. Cursors with Parameters <ul><li>Syntax: </li></ul><ul><ul><li>Pass parameter values to a cursor when the cursor is opened and the query is executed. </li></ul></ul><ul><ul><li>Open an explicit cursor several times with a different active set each time. </li></ul></ul>CURSOR cursor_name [( parameter_name datatype , ...)] IS select_statement ; OPEN cursor_name(parameter_value ,.....) ;
    283. 293. Cursors with Parameters SET SERVEROUTPUT ON DECLARE CURSOR emp_cursor (deptno NUMBER) IS SELECT employee_id, last_name FROM employees WHERE department_id = deptno; dept_id NUMBER; lname VARCHAR2(15); BEGIN OPEN emp_cursor (10); ... CLOSE emp_cursor; OPEN emp_cursor (20); ...
    284. 294. The FOR UPDATE Clause <ul><li>Syntax: </li></ul><ul><ul><li>Use explicit locking to deny access to other sessions for the duration of a transaction. </li></ul></ul><ul><ul><li>Lock the rows before the update or delete. </li></ul></ul>SELECT ... FROM ... FOR UPDATE [OF column_reference ][NOWAIT | WAIT n ];
    285. 295. The FOR UPDATE Clause
    286. 296. The WHERE CURRENT OF Clause <ul><li>Syntax: </li></ul><ul><ul><li>Use cursors to update or delete the current row. </li></ul></ul><ul><ul><li>Include the FOR UPDATE clause in the cursor query to lock the rows first. </li></ul></ul><ul><ul><li>Use the WHERE CURRENT OF clause to reference the current row from an explicit cursor. </li></ul></ul>WHERE CURRENT OF cursor ; UPDATE employees SET salary = ... WHERE CURRENT OF emp_cursor;
    287. 297. Cursors with Subqueries DECLARE CURSOR my_cursor IS SELECT t1.department_id, t1.department_name, t2.staff FROM departments t1, (SELECT department_id, COUNT(*) AS STAFF FROM employees GROUP BY department_id) t2 WHERE t1.department_id = t2.department_id AND t2.staff >= 3; ... Example:
    288. 298. Summary <ul><li>In this lesson you should have learned how to: </li></ul><ul><ul><li>Distinguish cursor types: </li></ul></ul><ul><ul><ul><li>Implicit cursors: Used for all DML statements and single-row queries </li></ul></ul></ul><ul><ul><ul><li>Explicit cursors: Used for queries of zero, one, or more rows </li></ul></ul></ul><ul><ul><li>Create and handle explicit cursors </li></ul></ul><ul><ul><li>Use simple loops and cursor FOR loops to handle multiple rows in the cursors </li></ul></ul><ul><ul><li>Evaluate the cursor status by using the cursor attributes </li></ul></ul><ul><ul><li>Use the FOR UPDATE and WHERE CURRENT OF clauses to update or delete the current fetched row </li></ul></ul>
    289. 299. Handling Exceptions
    290. 300. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Define PL/SQL exceptions </li></ul></ul><ul><ul><li>Recognize unhandled exceptions </li></ul></ul><ul><ul><li>List and use different types of PL/SQL exception handlers </li></ul></ul><ul><ul><li>Trap unanticipated errors </li></ul></ul><ul><ul><li>Describe the effect of exception propagation in nested blocks </li></ul></ul><ul><ul><li>Customize PL/SQL exception messages </li></ul></ul>
    291. 301. Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE first_name='John'; DBMS_OUTPUT.PUT_LINE ('John''s last name is : ' ||lname); END; /
    292. 302. Example SET SERVEROUTPUT ON DECLARE lname VARCHAR2(15); BEGIN SELECT last_name INTO lname FROM employees WHERE first_name='John'; DBMS_OUTPUT.PUT_LINE ('John''s last name is : ' ||lname); EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE (' Your select statement retrieved multiple rows. Consider using a cursor.'); END; /
    293. 303. Handling Exceptions with PL/SQL <ul><ul><li>An exception is an error PL/SQL that is raised during program execution. </li></ul></ul><ul><ul><li>An exception can be raised: </li></ul></ul><ul><ul><ul><li>Implicitly by the Oracle server </li></ul></ul></ul><ul><ul><ul><li>Explicitly by the program </li></ul></ul></ul><ul><ul><li>An exception can be handled: </li></ul></ul><ul><ul><ul><li>By trapping it with a handler </li></ul></ul></ul><ul><ul><ul><li>By propagating it to the calling environment </li></ul></ul></ul>
    294. 304. Handling Exceptions Exception raised Is the exception trapped? yes Execute statements in the EXCEPTION section Terminate gracefully no Terminate abruptly Propagate the exception
    295. 305. Exception Types <ul><ul><li>Predefined Oracle Server </li></ul></ul><ul><ul><li>Non-predefined Oracle Server </li></ul></ul><ul><ul><li>User-defined </li></ul></ul>} Implicitly raised Explicitly raised
    296. 306. Trapping Exceptions <ul><li>Syntax: </li></ul>EXCEPTION WHEN exception1 [OR exception2 . . .] THEN statement1 ; statement2 ; . . . [WHEN exception3 [OR exception4 . . .] THEN statement1 ; statement2 ; . . .] [WHEN OTHERS THEN statement1 ; statement2 ; . . .]
    297. 307. Trapping Exceptions
    298. 308. Guidelines for Trapping Exceptions <ul><ul><li>The EXCEPTION keyword starts the exception handling section. </li></ul></ul><ul><ul><li>Several exception handlers are allowed. </li></ul></ul><ul><ul><li>Only one handler is processed before leaving the block. </li></ul></ul><ul><ul><li>WHEN OTHERS is the last clause. </li></ul></ul>
    299. 309. Trapping Predefined Oracle Server Errors <ul><ul><li>Reference the predefined name in the exception handling routine. </li></ul></ul><ul><ul><li>Sample predefined exceptions: </li></ul></ul><ul><ul><ul><li>NO_DATA_FOUND </li></ul></ul></ul><ul><ul><ul><li>TOO_MANY_ROWS </li></ul></ul></ul><ul><ul><ul><li>INVALID_CURSOR </li></ul></ul></ul><ul><ul><ul><li>ZERO_DIVIDE </li></ul></ul></ul><ul><ul><ul><li>DUP_VAL_ON_INDEX </li></ul></ul></ul>
    300. 312. Trapping Non-Predefined Oracle Server Errors Declarative section Name the exception Code PRAGMA EXCEPTION_INIT EXCEPTION section Handle the raised exception Associate Reference Declare
    301. 313. Non-Predefined Error <ul><li>Trap Oracle server error number –01400, cannot insert NULL . </li></ul>SET SERVEROUTPUT ON DECLARE insert_excep EXCEPTION; PRAGMA EXCEPTION_INIT (insert_excep, -01400); BEGIN INSERT INTO departments (department_id, department_name) VALUES (280, NULL); EXCEPTION WHEN insert_excep THEN DBMS_OUTPUT.PUT_LINE('INSERT OPERATION FAILED'); DBMS_OUTPUT.PUT_LINE(SQLERRM); END; / 1 2 3
    302. 314. Functions for Trapping Exceptions <ul><ul><li>SQLCODE : Returns the numeric value for the error code </li></ul></ul><ul><ul><li>SQLERRM : Returns the message associated with the error number </li></ul></ul>
    303. 315. Functions for Trapping Exceptions <ul><li>Example: </li></ul>DECLARE error_code NUMBER; error_message VARCHAR2(255); BEGIN ... EXCEPTION ... WHEN OTHERS THEN ROLLBACK; error_code := SQLCODE ; error_message := SQLERRM ; INSERT INTO errors (e_user, e_date, error_code, error_message) VALUES(USER,SYSDATE,error_code, error_message); END; /
    304. 316. Trapping User-Defined Exceptions Declarative section Name the exception. Executable section Explicitly raise the exception by using the RAISE statement. Exception -handling section Handle the raised exception. Raise Reference Declare
    305. 317. Trapping User-Defined Exceptions ... ACCEPT deptno PROMPT 'Please enter the department number:' ACCEPT name PROMPT 'Please enter the department name:' DECLARE invalid_department EXCEPTION; name VARCHAR2(20):='&name'; deptno NUMBER :=&deptno; BEGIN UPDATE departments SET department_name = name WHERE department_id = deptno; IF SQL%NOTFOUND THEN RAISE invalid_department; END IF; COMMIT; EXCEPTION WHEN invalid_department THEN DBMS_OUTPUT.PUT_LINE('No such department id.'); END; / 1 2 3
    306. 318. Calling Environments Traps exception in exception-handling routine of enclosing block An enclosing PL/SQL block Accesses exception number through the SQLCA data structure Precompiler application Accesses error number and message in an ON-ERROR trigger by means of the ERROR_CODE and ERROR_TEXT packaged functions Oracle Developer Forms Displays error number and message to screen Procedure Builder Displays error number and message to screen i SQL*Plus
    307. 319. Propagating Exceptions in a Subblock DECLARE . . . no_rows exception; integrity exception; PRAGMA EXCEPTION_INIT (integrity, -2292); BEGIN FOR c_record IN emp_cursor LOOP BEGIN SELECT ... UPDATE ... IF SQL%NOTFOUND THEN RAISE no_rows; END IF; END; END LOOP; EXCEPTION WHEN integrity THEN ... WHEN no_rows THEN ... END; / Subblocks can handle an exception or pass the exception to the enclosing block.
    308. 320. The RAISE_APPLICATION_ERROR Procedure <ul><li>Syntax: </li></ul><ul><ul><li>You can use this procedure to issue user-defined error messages from stored subprograms. </li></ul></ul><ul><ul><li>You can report errors to your application and avoid returning unhandled exceptions. </li></ul></ul>raise_application_error ( error_number, message [, {TRUE | FALSE}]);
    309. 321. The RAISE_APPLICATION_ERROR Procedure <ul><ul><li>Used in two different places: </li></ul></ul><ul><ul><ul><li>Executable section </li></ul></ul></ul><ul><ul><ul><li>Exception section </li></ul></ul></ul><ul><ul><li>Returns error conditions to the user in a manner consistent with other Oracle server errors. </li></ul></ul>
    310. 322. RAISE_APPLICATION_ERROR <ul><li>Exception section: </li></ul>BEGIN ... DELETE FROM employees WHERE manager_id = v_mgr; IF SQL%NOTFOUND THEN RAISE_APPLICATION_ERROR(-20202, 'This is not a valid manager'); END IF; ... Executable section: ... EXCEPTION WHEN NO_DATA_FOUND THEN RAISE_APPLICATION_ERROR (-20201, 'Manager is not a valid employee.'); END; /
    311. 323. Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Define PL/SQL exceptions </li></ul></ul><ul><ul><li>Add an EXCEPTION section to the PL/SQL block to deal with exceptions at run time </li></ul></ul><ul><ul><li>Handle different types of exceptions: </li></ul></ul><ul><ul><ul><li>Predefined exceptions </li></ul></ul></ul><ul><ul><ul><li>Non-predefined exceptions </li></ul></ul></ul><ul><ul><ul><li>User-defined exceptions </li></ul></ul></ul><ul><ul><li>Propagate exceptions in nested blocks and call applications </li></ul></ul>
    312. 324. Creating Stored Procedures and Functions
    313. 325. Objectives <ul><li>After completing this lesson, you should be able to do the following: </li></ul><ul><ul><li>Differentiate between anonymous blocks and subprograms </li></ul></ul><ul><ul><li>Create a simple procedure and invoke it from an anonymous block </li></ul></ul><ul><ul><li>Create a simple function </li></ul></ul><ul><ul><li>Create a simple function that accepts a parameter </li></ul></ul><ul><ul><li>Differentiate between procedures and functions </li></ul></ul>
    314. 326. Procedures and Functions <ul><ul><li>Are named PL/SQL blocks </li></ul></ul><ul><ul><li>Are called PL/SQL subprograms </li></ul></ul><ul><ul><li>Have block structures similar to anonymous blocks: </li></ul></ul><ul><ul><ul><li>Optional declarative section (without DECLARE keyword) </li></ul></ul></ul><ul><ul><ul><li>Mandatory executable section </li></ul></ul></ul><ul><ul><ul><li>Optional section to handle exceptions </li></ul></ul></ul>
    315. 327. Differences Between Anonymous Blocks and Subprograms Can take parameters Cannot take parameters Subprograms called functions must return values Do not return values They are named and therefore can be invoked by other applications Cannot be invoked by other applications Stored in the database Not stored in the database Compiled only once Compiled every time Named PL/SQL blocks Unnamed PL/SQL blocks Subprograms Anonymous Blocks
    316. 328. Procedure: Syntax CREATE [OR REPLACE] PROCEDURE procedure_name [( argument1 [ mode1 ] datatype1, argument2 [ mode2 ] datatype2, . . . )] IS|AS procedure_body;
    317. 329. Procedure: Example ... CREATE TABLE dept AS SELECT * FROM departments; CREATE PROCEDURE add_dept IS dept_id dept.department_id%TYPE; dept_name dept.department_name%TYPE; BEGIN dept_id:=280; dept_name:= ' ST-Curriculum ' ; INSERT INTO dept(department_id,department_name) VALUES(dept_id,dept_name); DBMS_OUTPUT.PUT_LINE( ' Inserted ' || SQL%ROWCOUNT || ' row ' ); END; /
    318. 330. Procedure: Example
    319. 331. Invoking the Procedure BEGIN add_dept; END; / SELECT department_id, department_name FROM dept WHERE department_id=280;
    320. 332. Function: Syntax C REATE [OR REPLACE] FUNCTION function_name [( argument1 [ mode1 ] datatype1, argument2 [ mode2 ] datatype2, . . . )] RETURN datatype IS|AS function_body;
    321. 333. Function: Example CREATE FUNCTION check_sal RETURN Boolean IS dept_id employees.department_id%TYPE; empno employees.employee_id%TYPE; sal employees.salary%TYPE; avg_sal employees.salary%TYPE; BEGIN empno:=205; SELECT salary,department_id INTO sal,dept_id FROM employees WHERE employee_id= empno; SELECT avg(salary) INTO avg_sal FROM employees WHERE department_id=dept_id; IF sal > avg_sal THEN RETURN TRUE; ELSE RETURN FALSE; END IF; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL; END; /
    322. 334. Invoking the Function SET SERVEROUTPUT ON BEGIN IF (check_sal IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal) THEN DBMS_OUTPUT.PUT_LINE('Salary > average'); ELSE DBMS_OUTPUT.PUT_LINE('Salary < average'); END IF; END; /
    323. 335. Passing Parameter to the Function DROP FUNCTION check_sal; / CREATE FUNCTION check_sal (empno employees.employee_id%TYPE) RETURN Boolean IS dept_id employees.department_id%TYPE; sal employees.salary%TYPE; avg_sal employees.salary%TYPE; BEGIN SELECT salary,department_id INTO sal,dept_id FROM employees WHERE employee_id=empno; SELECT avg(salary) INTO avg_sal FROM employees WHERE department_id=dept_id; IF sal > avg_sal THEN RETURN TRUE; ELSE RETURN FALSE; END IF; EXCEPTION ... ...
    324. 336. Invoking the Function with a Parameter BEGIN DBMS_OUTPUT.PUT_LINE('Checking for employee with id 205'); IF (check_sal(205) IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal(205)) THEN DBMS_OUTPUT.PUT_LINE('Salary > average'); ELSE DBMS_OUTPUT.PUT_LINE('Salary < average'); END IF; DBMS_OUTPUT.PUT_LINE('Checking for employee with id 70'); IF (check_sal(70) IS NULL) THEN DBMS_OUTPUT.PUT_LINE('The function returned NULL due to exception'); ELSIF (check_sal(70)) THEN ... END IF; END; /
    325. 337. Summary <ul><li>In this lesson, you should have learned how to: </li></ul><ul><ul><li>Create a simple procedure </li></ul></ul><ul><ul><li>Invoke the procedure from an anonymous block </li></ul></ul><ul><ul><li>Create a simple function </li></ul></ul><ul><ul><li>Create a simple function that accepts parameters </li></ul></ul><ul><ul><li>Invoke the function from an anonymous block </li></ul></ul>
    326. 338. Goals of the Course <ul><li>After completing this course, you should be able to do the following: </li></ul><ul><ul><li>Identify the major structural components of Oracle Database 10 g </li></ul></ul><ul><ul><li>Retrieve row and column data from tables with the SELECT statement. </li></ul></ul><ul><ul><li>Process database record with DML codes. </li></ul></ul><ul><ul><li>Appreciate that PL/SQL provides programming extensions to SQL </li></ul></ul><ul><ul><li>Write PL/SQL code to interface with the database </li></ul></ul><ul><ul><li>Design PL/SQL program units that execute efficiently </li></ul></ul><ul><ul><li>Use PL/SQL programming constructs and conditional control statements </li></ul></ul><ul><ul><li>

    ×