132
Introduction to Oracle as a RDBMS

1 Rdbms SQL Pl SQL

Embed Size (px)

Citation preview

Page 1: 1 Rdbms SQL Pl SQL

Introduction to Oracle as a RDBMS

Page 2: 1 Rdbms SQL Pl SQL

- 2 -Copyright Infogain Corporation, 2007

Database Modeling ConceptsDatabase Modeling Concepts

Conceptual Modeling. Entity Relationship Modeling. Database Types. Normalization & Denormalization. Relationships & Constraints. Entity Relationship Diagram. Mapping ER Model.

Page 3: 1 Rdbms SQL Pl SQL

- 3 -Copyright Infogain Corporation, 2007

Entity Relationship ModelEntity Relationship Model

Key Components• Entity: A thing about which information needs to be known.• Attribute: Something that describes or qualifies an entity.• Relationship: A named association between entities showing

cardinalities.

Benefits of ER Modeling• Documents information for the organization in a precise format.• Scope of the information requirement.• Pictorial map for the database design.

Page 4: 1 Rdbms SQL Pl SQL

Introduction to SQL

Page 5: 1 Rdbms SQL Pl SQL

- 5 -Copyright Infogain Corporation, 2007

SQLSQL

Structured Query Language (SQL), contains set of commands which provide an access to a relational database such as Oracle

SQL statements are instructions to the database.

The strengths of SQL benefit all types of users, including application programmers, database administrators, management, and end users.

SQL provides statements for a variety of tasks, including:

Querying data • Inserting, Updating, and Deleting rows in a table • Creating, Replacing, Altering, and Dropping objects • Controlling access to the database and its objects

Page 6: 1 Rdbms SQL Pl SQL

- 6 -Copyright Infogain Corporation, 2007

A Simple Select StatementA Simple Select Statement

Select *| { (Distinct) column | expression [alias], …}

From table

[Where condition's)]

[Order By asc/desc ];

Select *| { (Distinct) column | expression [alias], …} From table [Where condition (s)] [Order By asc/desc ];

Page 7: 1 Rdbms SQL Pl SQL

- 7 -Copyright Infogain Corporation, 2007

Operators Used in Where ClauseOperators Used in Where Clause

There are three types of Operators: • Common operators:

– =, !=, ^=, <>, <, >, <=, >=, in, not in, not between, like, ‘%tin%’

Arithmetic operators:– +, -, *, /, =, !=, <>, <, >, <=, >=, IS NULL, LIKE, BETWEEN, IN, AND,OR

• Logical operators: – NOT, AND, OR

Page 8: 1 Rdbms SQL Pl SQL

- 8 -Copyright Infogain Corporation, 2007

Single Row FunctionSingle Row Function

Single-row functions return only a single row as a result for every row of a queried table or view

These functions can appear in select lists, WHERE clauses, START WITH clauses, and CONNECT BY clauses

There are four types of Single Row function:• Arithmetic Functions• Character Functions• Date Functions• General Functions

Page 9: 1 Rdbms SQL Pl SQL

- 9 -Copyright Infogain Corporation, 2007

ROUND returns n rounded to m places right of the decimal point. If m is omitted, n is rounded to 0 places. m can be negative to round off digits left of the decimal point. m must be an integer. • SELECT ROUND(15.193,1) FROM DUAL;

EXP returns e raised to the nth power, where e = 2.71828183 ... • SELECT EXP(4) FROM DUAL;

Arithmetic Functions (cont.)Arithmetic Functions (cont.)

Page 10: 1 Rdbms SQL Pl SQL

- 10 -Copyright Infogain Corporation, 2007

Character FunctionsCharacter Functions

CHR returns the character having the binary equivalent to n in either the database character set or the national character set.• SELECT CHR(67) a,CHR(65) b,CHR(84) c FROM DUAL;

LOWER returns char, with all letters lowercase. • SELECT LOWER('MR. SCOTT MCMILLAN') FROM DUAL;

UPPER returns char, with all letters uppercase. • SELECT UPPER('Large') FROM DUAL;

Page 11: 1 Rdbms SQL Pl SQL

- 11 -Copyright Infogain Corporation, 2007

Date FunctionsDate Functions

SYSDATE returns the current date and time. • SELECT sysdate FROM DUAL;

ADD_MONTHS adds or subtracts months to or from a date. Returns a date as result.• SELECT TO_CHAR( ADD_MONTHS( line_status_date,1),'DD-

MM_YYYY') FROM line_item_master WHERE order_number = 'ORD000101‘

ROUND returns d rounded to the unit specified by the format model fmt. If you omit fmt, d is rounded to the nearest day. • SELECT ROUND (TO_DATE ('27-OCT-92'),'YEAR') FROM DUAL;

Page 12: 1 Rdbms SQL Pl SQL

- 12 -Copyright Infogain Corporation, 2007

Date Functions (cont.)Date Functions (cont.)

MONTHS_BETWEEN returns number of months between dates d1 and d2. If d1 is later than d2, result is positive; if earlier, negative. • SELECT MONTHS_BETWEEN (TO_DATE('02-02-1995','MM-DD-

YYYY'), TO_DATE('01-01-1995','MM-DD-YYYY') ) FROM DUAL;

LAST_DAY returns the date of the last day of the month that contains d. You might use this function to determine how many days are left in the current month. • SELECT SYSDATE, LAST_DAY(SYSDATE), LAST_DAY(SYSDATE) -

SYSDATE FROM DUAL;

NEXT_DAY returns the date of next specified day of the week after the ‘date’.• SELECT NEXT_DAY('15-MAR-98','TUESDAY') FROM DUAL;

Page 13: 1 Rdbms SQL Pl SQL

- 13 -Copyright Infogain Corporation, 2007

Date Functions (cont.)Date Functions (cont.)

TRUNC returns d with the time portion of the day truncated to the unit specified by the format model fmt. If you omit fmt, d is truncated to the nearest day. • SELECT TRUNC(TO_DATE('27-OCT-92','DD-MON-YY'), 'YEAR')

FROM DUAL;

TO_CHAR converts the date ‘d’ to character format ‘f’.• SELECT sysdate, TO_CHAR(sysdate,'DAY')FROM DUAL;

TO_DATE converts the character string representing date into a date format according to ‘f’ format specified. If no format is specified the default format is DD-MM-YY.• SELECT TO_CHAR(TO_DATE('20-MAR-98'),'RM') FROM DUAL;

Page 14: 1 Rdbms SQL Pl SQL

- 14 -Copyright Infogain Corporation, 2007

Data-TypeConversion

Implicit data-type Conversion

Explicit data-typeConversion

Conversion FunctionsConversion Functions

Page 15: 1 Rdbms SQL Pl SQL

- 15 -Copyright Infogain Corporation, 2007

From To

VARCHAR2 OR CHAR NUMBER

VARCHAR2 or CHAR DATE

NUMBER VARCHAR2

DATE VARCHAR2

Implicit Data-Type ConversionImplicit Data-Type Conversion

Page 16: 1 Rdbms SQL Pl SQL

- 16 -Copyright Infogain Corporation, 2007

NUMBER CHARACTER DATE

TO_NUMBER TO_DATE

TO_CHAR TO_CHAR

Explicit Data - Type ConversionExplicit Data - Type Conversion

Page 17: 1 Rdbms SQL Pl SQL

- 17 -Copyright Infogain Corporation, 2007

Group FunctionsGroup Functions

Type of group functions• AVG• COUNT• MIN• MAX• SUM• VARIANCE• STDDEV

Page 18: 1 Rdbms SQL Pl SQL

- 18 -Copyright Infogain Corporation, 2007

Group Functions (cont.)Group Functions (cont.)

Group functions are those statistical functions which gives information about a group of value taken as whole

Group functions return based on many rows, as opposed to single row functions, which return one result for each row.

For example COUNT group function returns no of rows returned.

These functions are valid in the select list of a query and the GROUP BY clause only.

Page 19: 1 Rdbms SQL Pl SQL

- 19 -Copyright Infogain Corporation, 2007

JOINSJOINS

One of the most important features of SQL is the ability to define relationships between multiple tables and draw information from them in terms of these relationships, all within a single command.

With joins, the information from any number of tables can be accessed.

Joins are used to combine columns from different tables.

The connection between tables is established through the WHERE clause.

Types of Joins: Equi Joins, Non Equi Joins, Outer Joins, Self Joins.

Page 20: 1 Rdbms SQL Pl SQL

- 20 -Copyright Infogain Corporation, 2007

Equi JoinsEqui Joins

When two tables are joined together using equality of values in one or more columns, they make an Equi Join.

It combines rows that have equivalent values of a specified columns. In this case in WHERE condition we use (=) operator.

Example:• Select cz.price_list_id,cz.customer_name,ra.party_id,• ra.customer_name from cz_imp_customer cz, ra_customer ra where

cz.customer_id = ra.customer_id;

Here, the WHERE clause defines the joining condition i.e., joining the customer_id of cz_imp_customer and ra_customer. Here, it checks for the equality of values in these columns.

Page 21: 1 Rdbms SQL Pl SQL

- 21 -Copyright Infogain Corporation, 2007

Cartesian ProductCartesian Product

When no join condition clause is specified in WHERE clause, each row of one table matches every row of the other table.

This results in a Cartesian Product.• Select cz.price_list_id,cz.customer_name,ra.party_id,• ra.customer_name from cz_imp_customer cz, ra_customer ra;

Page 22: 1 Rdbms SQL Pl SQL

- 22 -Copyright Infogain Corporation, 2007

Outer JoinsOuter Joins

It extends the result of simple joins.

It retrieve records from another table that do not have a matching record in addition to one’s having matching records.• Select

cz.price_list_id,cz.customer_name,ra.party_id,ra.customer_name• From cz_imp_customer cz, ra_customer ra• Where cz.customer_id(+)=ra.customer_id;

Page 23: 1 Rdbms SQL Pl SQL

- 23 -Copyright Infogain Corporation, 2007

Set OperatorsSet Operators

SET Operators are used to combine information of similar type from one or more than one table.

Data type of corresponding columns must be the same.

So Set operators combine two or more queries into one result.

The types of SET operators in ORACLE are:• UNION• INTERSECT• MINUS

Page 24: 1 Rdbms SQL Pl SQL

- 24 -Copyright Infogain Corporation, 2007

Sub queriesSub queries

Sub queries allow a developer to build powerful commands out of simple ones.

A sub query is a SELECT statement that is nested within another SELECT statement and which returns intermediate results.

SQL first evaluates the inner query (sub query) with in WHERE clause.

The inner query generates values that are tested in the predict of the outer query determining when it will be true.

The nested sub query is very powerful when you need to select rows from a table within a condition that depends on the data in the table itself.

Page 25: 1 Rdbms SQL Pl SQL

- 25 -Copyright Infogain Corporation, 2007

Types of Sub queriesTypes of Sub queries

Single-row sub query returns a single row value result

Multiple-row sub query returns many row values as a result

Guidelines for using Sub queries• Enclose sub queries in parentheses.• Place sub queries on the right side of the comparison operator.• Do not add the ORDER BY clause to a sub query.• Use single row operators with single row sub queries• Use multiple row operators with multiple-row sub queries

Page 26: 1 Rdbms SQL Pl SQL

- 26 -Copyright Infogain Corporation, 2007

Substitution VariablesSubstitution Variables

Substitution provides an easier way to enter data into a table

The ‘&’ symbol is used as the substitution operator

Use ‘&&’ if you want to reuse the variable value

When a substitution operator is used, SQL * Plus prompts for the value of the variable, accepts it and then substitutes it in the variable.

Page 27: 1 Rdbms SQL Pl SQL

- 27 -Copyright Infogain Corporation, 2007

Defining Substitution VariablesDefining Substitution Variables

Predefine a variable using the DEFINE command.• DEFINE variable = value

A define variable is available for the session• DEFINE job_title = Clerk

A variable value can be unset with a UNDEFINE command• UNDEFINE job_title = Clerk

Page 28: 1 Rdbms SQL Pl SQL

Producing Readable Output with SQL*Plus

Page 29: 1 Rdbms SQL Pl SQL

- 29 -Copyright Infogain Corporation, 2007

Customizing the SQL*Plus EnvironmentCustomizing the SQL*Plus Environment

SET commands can be used to control current session.• SET {variable} {value}

Use SHOW command to verify what value you have set for a variable.

Example• sql>SET ECHO ON• sql>SHOW ECHO• sql>echo ON

Page 30: 1 Rdbms SQL Pl SQL

- 30 -Copyright Infogain Corporation, 2007

SQL*Plus Format CommandsSQL*Plus Format Commands

The COLUMN Command

COL[UMN] [{column | alias } [option]]

COLUMN command options• FOR[MAT] format: changes the display of column data

– Example: COLUMN customer_salary FORMAT A10

• HEA[DING] text: Sets the column heading– Example: COLUMN customer_salary HEADING ‘SALARY’

• CLE[AR]: Clears any column formats– Example: COLUMN customer_name CLEAR

Page 31: 1 Rdbms SQL Pl SQL

- 31 -Copyright Infogain Corporation, 2007

SQL*Plus Format Commands (cont.)SQL*Plus Format Commands (cont.)

Using TTITLE and BTITLE Commands• Display headers and footers.• Set the Report Header• Set the Report Footer

TTI[TLE] [text | off | on] BTI[TLE] [text | off | on]

Example: TTITLE ‘Salary | Report’ BTITLE ‘END OF REPORT’

Page 32: 1 Rdbms SQL Pl SQL

- 32 -Copyright Infogain Corporation, 2007

Example of Creating a ReportExample of Creating a Report

set feedback off Ttitle 'employee|report' btitle 'end of report' break on customer_id column customer_id heading ‘Customer|ID' column customer_name heading 'Customer|Name' column creation_date heading 'DATE OF JOINING‘ FORMAT A20 select customer_id,customer_name,creation_date from ra_customers order by customer_id; set feedback on clear break column customer_id clear column customer_name clear column creation_date clear

Page 33: 1 Rdbms SQL Pl SQL

- 33 -Copyright Infogain Corporation, 2007

PL/SQLblock

Oracle8 Server

PL/SQLblock

ProceduralStatementExecutor

PL/SQL engine

PL/SQL

SQL

SQL Statement Executor

SQL EnvironmentSQL Environment

Page 34: 1 Rdbms SQL Pl SQL

- 34 -Copyright Infogain Corporation, 2007

SELECT Data retrieval

INSERTUPDATE Data manipulation language (DML)DELETE

CREATEALTERDROP Data definition language (DDL)RENAMETRUNCATE

COMMITROLLBACK Transaction controlSAVEPOINT

GRANT Data Control language (DCL)REVOKE

SQL StatementsSQL Statements

Page 35: 1 Rdbms SQL Pl SQL

SQL DML, DDL Statements

Page 36: 1 Rdbms SQL Pl SQL

- 36 -Copyright Infogain Corporation, 2007

DML – Insert, Update, DeleteDML – Insert, Update, Delete

DML statements are SQL commands that allow you to manipulate the data in the database.

The most common SQL statements are insert, update and delete.

This statements allow you to work with the contents of the database.• INSERT: Insert is used to add rows of data to a table.• UPDATE: Update is used to change data in a table.• DELETE: Delete is used to delete rows of data from a table.

Page 37: 1 Rdbms SQL Pl SQL

- 37 -Copyright Infogain Corporation, 2007

InsertInsert

INSERT command is used to insert rows in the table.

Values can be inserted for all the columns or for the selected columns

To the INSERT INTO command, values can also be given through a query, however, the columns of the table being inserted must match the columns output by the sub query

In place of values, parameter substitution can also be used with INSERT

The syntax for INSERT command is:• INSERT INTO < table-name > VALUES ( < list-of-values>);

Page 38: 1 Rdbms SQL Pl SQL

- 38 -Copyright Infogain Corporation, 2007

ExamplesExamples

To insert values for all columns following command is used:• Insert into customer_data• VALUES (1,‘Hendry','qwerty','Gujrat','india');

To insert only the selected columns the following command is used:• Insert into customer_data• (ID,USERNAME,STATE,COUNTRY)• Values (2,‘Ronaldo’,‘Delhi','india');

Page 39: 1 Rdbms SQL Pl SQL

- 39 -Copyright Infogain Corporation, 2007

Update Update

UPDATE command is used to update the columns in a table

Values of a single column or a group of columns can be updated

Updation can be carried out for all the rows in a table or selected rows

UPDATE command sets specific values for each column required to change

The syntax of UPDATE command is: UPDATE < table-name > SET < column-name > = < value > [,column-name = value,……] [WHERE < condition >]

Page 40: 1 Rdbms SQL Pl SQL

- 40 -Copyright Infogain Corporation, 2007

Delete Delete

DELETE command is used to delete rows from a table The entire row is deleted from the table Specific columns cannot be deleted from a table DELETE command allows you to remove one or more rows from a

table. Where clause allows a set of rows to be deleted from a table by specifying the condition's)

The syntax for DELETE command: DELETE FROM < table-name >

[WHERE < condition >] Delete the records of order number 1: Delete from customer_data

where id = 1;

Page 41: 1 Rdbms SQL Pl SQL

- 41 -Copyright Infogain Corporation, 2007

DDL – Create, Alter, RollbackDDL – Create, Alter, Rollback

DDL is the subset of SQL commands used to create, modify or remove Oracle database structures.

These commands have an immediate effect on the database, and also record information in the Data dictionary.• Create Creates a table.• Alter Adds a column, redefines a column, changes storage

allocation.• Rollback Undo all the changes or all the work the user has done

In the current transaction.

Page 42: 1 Rdbms SQL Pl SQL

- 42 -Copyright Infogain Corporation, 2007

Create Create

Tables are created by using the CREATE TABLE command

Tables are owned by the user who creates them

The names of tables owned by a given user must be unique

The column names in the table must be unique

Column names can be duplicated across tables

The syntax for creating table is:• CREATE TABLE < table-name > (• < column-name > < data type (size) >, ……….) ;

Page 43: 1 Rdbms SQL Pl SQL

- 43 -Copyright Infogain Corporation, 2007

Alter Alter

To change the definition of a table ALTER TABLE command is used.

ALTER TABLE command adds column to the table or change their sizes, changes their data types and can also add or delete constrains.

The syntax for ALTER table command is: Alter table < table-name >

• [ add ( < column- element > | < constraints > …..]• [ modify < column- element > … ]• [ drop < options > ] ;

Page 44: 1 Rdbms SQL Pl SQL

- 44 -Copyright Infogain Corporation, 2007

Transaction processing – Commit, RollbackTransaction processing – Commit, Rollback

Transaction is a logical unit of work. All changes made to the database can be referred as a Transaction.

Commit and Rollback are Transaction Processing languages.

Commit is used to make changes to data (inserts, updates, deletes) permanently and save the data permanently.

Rollback is used to discard parts or all the work the user has done in the current transaction.

Page 45: 1 Rdbms SQL Pl SQL

SQL DML, DDL Statements

Page 46: 1 Rdbms SQL Pl SQL

- 46 -Copyright Infogain Corporation, 2007

View ConceptsView Concepts

Is a stored SELECT statement

Is used to present subsets or combinations of data

Is a virtual table based on a table or another view

The tables on which a view is based are called base tables

Contains no data of its own• Is like a window through which data from tables can be viewed or

changed• Can’t be indexed

Page 47: 1 Rdbms SQL Pl SQL

- 47 -Copyright Infogain Corporation, 2007

Why Use Views?Why Use Views?

To restrict data access• A view can display only selected rows or columns

To make complex queries easy• A view is pre-built query… user can run it without knowing how to:

– Use record selection criteria– Write join expressions– Derive calculated columns– Perform sorting– Perform grouping

To present different views of the same data• E.g.: One view to provide a detailed look at rows, others to present

summaries with grouping in various ways

Page 48: 1 Rdbms SQL Pl SQL

- 48 -Copyright Infogain Corporation, 2007

Creating a ViewCreating a View

CREATE [OR REPLACE] VIEW <view name>AS subquery[WITH CHECK OPTION [CONSTRAINT constraint]][WITH READ ONLY];

OR REPLACE• Overwrites any existing view of the same name• Avoids having to drop the view, recreate it, and re-grant privileges

Sub query• A complete SELECT statement• Can use aliases for the columns• Can involve multiple tables

Page 49: 1 Rdbms SQL Pl SQL

- 49 -Copyright Infogain Corporation, 2007

Create or replace view customer_viewasselect cz.price_list_id, ra.party_id,ra.customer_name from cz_imp_customer cz, ra_customer ra where cz.customer_id = ra.customer_id with read only;

SQL> desc customer_view SQL> select * from customer_view;

View Example #1View Example #1

Create a Read Only View

Use the View

Page 50: 1 Rdbms SQL Pl SQL

- 50 -Copyright Infogain Corporation, 2007

Create a View

Use the View

SQL> create or replace view customer_checkas select * from customer_datawhere salary=10000WITH CHECK OPTION;

SQL> select * from customer_check

SQL> update customer_check set salary = 20000 where id = 1;update customer_check *ERROR at line 1:ORA-01402: view WITH CHECK OPTION where-clause violation

View Example #2View Example #2

Page 51: 1 Rdbms SQL Pl SQL

- 51 -Copyright Infogain Corporation, 2007

DML Using ViewsDML Using Views

For DML, a view must not contain• An expression• An multi-row (aggregate) function• A single-row function• Set operators• DISTINCT• GROUP BY or HAVING• ORDER BY

Since you’re using the view to insert/update/delete rows in a table, the table’s constraints must be satisfied as well

Page 52: 1 Rdbms SQL Pl SQL

- 52 -Copyright Infogain Corporation, 2007

DROP VIEW <viewname>;

Removes the view definition from the database• Has no effect on the base tables• Objects that are based on a deleted view become invalid

Must be the creator or have the DROP ANY VIEW privilege

Modifying a View• Views can’t be modified• Use CREATE OR REPLACE to redefine it

Dropping and Modifying ViewsDropping and Modifying Views

Page 53: 1 Rdbms SQL Pl SQL

- 53 -Copyright Infogain Corporation, 2007

Index ConceptsIndex Concepts

Is a schema object

Can help speed row retrieval using ROWID pointers• ROWID is the unique address of each row in the database• The location of the row can be determined from the ROWID• Analogy: book’s index

– Where in the book is the topic GRANT?

• If you do not have an index on the column, a full table scan will occur

Is automatically used and maintained by Oracle

Can slow DML operations• Oracle must update each index when DML performed

Indexes take up space

Page 54: 1 Rdbms SQL Pl SQL

- 54 -Copyright Infogain Corporation, 2007

Automatically• A unique index is created automatically when you define a PRIMARY

KEY or UNIQUE constraint

Manually• Users can create indexes on columns to speed up access to the rows• E.g.: Index foreign key fields to speed joins• E.g.: Index fields that frequently appear in WHERE clauses to speed

retrieval

When are Indexes Created?When are Indexes Created?

Page 55: 1 Rdbms SQL Pl SQL

- 55 -Copyright Infogain Corporation, 2007

SQL> CREATE INDEX customer_id_idx ON ra_customer(customer_id);Index created.

CREATE [BITMAP] INDEX indexON table (column[, column]...);

You must have CREATE INDEX privilege

Creating an IndexCreating an Index

Page 56: 1 Rdbms SQL Pl SQL

- 56 -Copyright Infogain Corporation, 2007

SQL> CREATE INDEX customer_composite_idx ON customer_data(id, username);Index created.

CREATE INDEX indexON table (column[, column]...);

Creating a Composite IndexCreating a Composite Index

Up to 32 columns per index

What is the leading column of this index?

What WHERE clauses could benefit from this index?

Page 57: 1 Rdbms SQL Pl SQL

- 57 -Copyright Infogain Corporation, 2007

When to Create an IndexWhen to Create an Index

The column is used frequently in the WHERE clause or in a join condition• E.g.: a foreign key (Oracle automatically creates an index for a pk)

The column contains a wide range of values

The column contains a large number of NULL values

Two or more columns are frequently used together in a WHERE clause or a join condition

The table is large and most queries are expected to retrieve less than 2-4% of the rows

Page 58: 1 Rdbms SQL Pl SQL

- 58 -Copyright Infogain Corporation, 2007

When Not to Create an IndexWhen Not to Create an Index

The table is small• Table scan will probably be faster

The column is not often used as a condition

Most queries are expected to retrieve more than 2-4% of the rows

The table is updated frequently• Each DML operation requires that the table’s indexes be updated…

and that takes time!

Page 59: 1 Rdbms SQL Pl SQL

- 59 -Copyright Infogain Corporation, 2007

SQL> DROP INDEX customer_composite_idx;Index dropped.

DROP INDEX indexname;

Removing an IndexRemoving an Index

You must be the owner or have the DROP ANY INDEX privilege

You cannot modify an index… must drop and recreate

When a table is dropped, Oracle automatically drops all of the table’s indexes

Page 60: 1 Rdbms SQL Pl SQL

- 60 -Copyright Infogain Corporation, 2007

Sequence ConceptsSequence Concepts

Generates unique sequential numbers automatically• Can be either ascending or descending

Is typically used to create a primary key value

Is a sharable object

Sequences are independent of tables• Can modify or drop sequence with no effect on table• Can modify or drop table with no effect on the sequence• The same sequence can be used for multiple tables

Page 61: 1 Rdbms SQL Pl SQL

- 61 -Copyright Infogain Corporation, 2007

CREATE SEQUENCE sequence[INCREMENT BY n][START WITH n][{MAXVALUE n | NOMAXVALUE}][{MINVALUE n | NOMINVALUE}][{CYCLE | NOCYCLE}][{CACHE n | NOCACHE}];

SQL> CREATE SEQUENCE customer_seq INCREMENT BY 1 START WITH 1 NOCACHE;

Creating a SequenceCreating a Sequence

The following was in the CreateIssue25 script

Page 62: 1 Rdbms SQL Pl SQL

- 62 -Copyright Infogain Corporation, 2007

NEXTVAL and CURRVAL Pseudo columnsNEXTVAL and CURRVAL Pseudo columns

NEXTVAL• Generates a new sequence number and places it in CURRVAL • You must qualify NEXTVAL with the sequence name

CURRVAL

Obtains the current sequence value• When CURRVAL is referenced, the last value returned to the user’s

own process is displayed – NEXTVAL must be issued for the sequence before CURRVAL contains an initial value

You must qualify CURRVAL with the sequence name

Page 63: 1 Rdbms SQL Pl SQL

- 63 -Copyright Infogain Corporation, 2007

SQL> INSERT INTO customer_data VALUES (customer_seq.NEXTVAL, 'Scott','tiger', 'Mahatastra',’India’,10000);

SQL> select customer_seq.CURRVAL from dual

Sequences are generally used in INSERT and UPDATE statements e.g.:

What customer_id was used for that article?

Using a SequenceUsing a Sequence

Page 64: 1 Rdbms SQL Pl SQL

- 64 -Copyright Infogain Corporation, 2007

Using a Sequence (cont.)Using a Sequence (cont.)

Gaps in sequence values can occur when:• A ROLLBACK occurs

• The system crashes

• A sequence is used in another table

Page 65: 1 Rdbms SQL Pl SQL

- 65 -Copyright Infogain Corporation, 2007

SQL> ALTER SEQUENCE customer_seq 2 INCREMENT BY 1 3 MAXVALUE 9999 4 NOCACHE 5 NOCYCLE;Sequence altered.

Modifying a SequenceModifying a Sequence

You must be the owner or have the ALTER SEQUENCE privilege

Can change the increment value, maximum value, minimum value, cycle option, or cache option • Can’t change the START value… the sequence must be dropped and

re-created

Page 66: 1 Rdbms SQL Pl SQL

- 66 -Copyright Infogain Corporation, 2007

DROP SEQUENCE <sequence name>;

Removing a SequenceRemoving a Sequence

Once removed, the sequence can no longer be referenced

You must be the owner of the sequence or have the DROP ANY SEQUENCE privilege

Page 67: 1 Rdbms SQL Pl SQL

- 67 -Copyright Infogain Corporation, 2007

SynonymsSynonyms

SYNONYMS is a database object which is used as a alias for a table nothing but a alternative name for the table.

Mainly used to simplify SQL statements and hide name and owner of an object.

On a Synonym user can do all the DML operations such as insert, delete & update.

But cannot perform DDL operations on a Synonym set, dropping a Synonym.

The syntax for creating Synonym is:• CREATE SYNONYM synonym name FOR reference;

Page 68: 1 Rdbms SQL Pl SQL

- 68 -Copyright Infogain Corporation, 2007

ExampleExample

To create new synonym:• CREATE SYNONYM customer• FOR cz_imp_customer;

To drop synonym:• DROP SYNONYM customer;

Page 69: 1 Rdbms SQL Pl SQL

- 69 -Copyright Infogain Corporation, 2007

Security – Creating user, Grant, RevokeSecurity – Creating user, Grant, Revoke

ORACLE provides extensive security features in order to safeguard the user’s information from both unauthorized access and intentional damage.

This security is provided by granting or revoking privileges on a user-by user and privilege-by-privilege basis.

Page 70: 1 Rdbms SQL Pl SQL

- 70 -Copyright Infogain Corporation, 2007

Security – Creating user, Grant, Revoke (cont.)Security – Creating user, Grant, Revoke (cont.)

A user can also grant privileges directly to other user, of course restricted only to those privileges that the user has. • Creating USER: Use the CREATE USER statement to create and

configure database user, or an account through which you can log in to the database and establish the means by which Oracle permits access by the user.

• GRANT: A user can grant access to his database object's) to other user's)

• REVOKE: To withdraw a privilege you have granted, the REVOKE command is used.

Page 71: 1 Rdbms SQL Pl SQL

- 71 -Copyright Infogain Corporation, 2007

Examples on User,Grant and RevokeExamples on User,Grant and Revoke

Creating USER:• CREATE USER sidney • IDENTIFIED BY welcome • DEFAULT TABLESPACE cases_ts • QUOTA 10M ON cases_ts• TEMPORARY TABLESPACE temp_ts • QUOTA 5M ON system • PROFILE engineer PASSWORD EXPIRE;

GRANT:• GRANT ALL • ON customer_master• TO PUBLIC;• REVOKE:• REVOKE UPDATE ON customer_master FROM PUBLIC;

Page 72: 1 Rdbms SQL Pl SQL

- 72 -Copyright Infogain Corporation, 2007

Introduction to PL/SQLIntroduction to PL/SQL

PL/SQL is completely portable high performance transaction processing language. It combines data manipulation power of SQL and procedural power of standard procedural languages.

PL/SQL also provides performance improvements through blocking of RDBMS calls. It includes many features and designs of programming language. The PL/SQL engine resides within the Oracle Server so it is available from any application development tool that supports PL/SQL.

PL/SQL engine executes PL/SQL block. PL/SQL engine executes only a procedural statements and sends SQL statements to the SQL executer.

Page 73: 1 Rdbms SQL Pl SQL

- 73 -Copyright Infogain Corporation, 2007

Anonymousblock

Applicationtrigger

Databasetrigger

StoredProcedure /

function

Application Procedure /

function

Packagedprocedure

DECLARE

BEGIN

EXCEPTION

END;

Structure of PL/SQLStructure of PL/SQL

Page 74: 1 Rdbms SQL Pl SQL

- 74 -Copyright Infogain Corporation, 2007

Anonymous BlocksAnonymous Blocks

Anonymous block is block without a name

These blocks are declared at the point in an application where they are to be run, and passed to the PL/SQL engine for execution at run time

Block Structure for Anonymous PL/SQL Blocks:• DECLARE (optional)

– Declare PL/SQL objects to be used within this block

• BEGIN (mandatory)– Define the executable statements

• EXCEPTION (optional)– Define the action that take place if an error arises

END;

Page 75: 1 Rdbms SQL Pl SQL

- 75 -Copyright Infogain Corporation, 2007

Anonymous Blocks (cont.)Anonymous Blocks (cont.)

Declaration Section• Contains all variables, constants, cursors and user-defined exceptions

that will be referenced within the executable section. This section is optional.

Executable Section • Contains SQL statements to manipulate data in the database, and

PL/SQL statement to manipulate data in the block. This section is mandatory.

Exception Handling Section• Specifies the actions to perform when errors and abnormal conditions

arise within the executable section. This section is also optional.

Page 76: 1 Rdbms SQL Pl SQL

- 76 -Copyright Infogain Corporation, 2007

Application Oracle withPL/SQL

SQLIF... THEN

SQLELSESQL

END IF;SQL

Application OTHER DBMSs

SQLSQL

SQLSQL

Improve Performance

Benefits of PL/SQLBenefits of PL/SQL

Page 77: 1 Rdbms SQL Pl SQL

- 77 -Copyright Infogain Corporation, 2007

Variables and ConstantsVariables and Constants

Variables are used to store the result of a query or calculation. Variables must be declared before use

DEFAULT reverse word is used to initialize variables and constants.

Variables can also be declared using the row attributes of a table %ROWTYPE and %TYPE.

To assign a value to a variable, the assignment operator ‘:=‘ is used. Constants are declared by specifying the keyword CONSTANT before the data type.

The general syntax is: • <VAR-NAME> <TYPE> (:= <VALUE>);

Page 78: 1 Rdbms SQL Pl SQL

- 78 -Copyright Infogain Corporation, 2007

Types of VariablesTypes of Variables

PL/SQL Variables• Scalar• Composite• Reference• LOB

Syntax Of Declaring a PL/SQL Variables

Identifier [CONSTANT] data type [NOT NULL] [:= | DEFAULT expr];

Example:• Customer_id NUMBER(4) NOT NULL:= 10;• Customer_name VARCHAR2(15) := ‘ THOMAS ‘;

Page 79: 1 Rdbms SQL Pl SQL

- 79 -Copyright Infogain Corporation, 2007

%TYPE Attribute%TYPE Attribute

Used to declare a variable according to a database column definition

Used to declare a variable according to a previously declared variable

The %TYPE is prefixed with• The database table and column• The previously declared variable name

Example:• x_customer_name ra_customers.customer_name%TYPE;• x_salary NUMBER(7,2);• x_min_salary x_salary%TYPE

Page 80: 1 Rdbms SQL Pl SQL

- 80 -Copyright Infogain Corporation, 2007

Printing Output to the ScreenPrinting Output to the Screen

DBMS_OUTPUT.PUT_LINE• Oracle supplied packaged procedure• You can display data from a PL/SQL block• Requires a command

SET SERVEROUTPUT ON EXAMPLE SET SERVEROUTPUT ON DECLARE salary NUMBER(9,2) := 1000; BEGIN salary:= salary/2; DBMS_OUTPUT.PUT_LINE (‘The monthly salary is ‘||

TO_CHAR(salary)); END;

Page 81: 1 Rdbms SQL Pl SQL

- 81 -Copyright Infogain Corporation, 2007

Operators in PL/SQLOperators in PL/SQL

Logical

Arithmetic

Concatenation

Parentheses to control order of operations

Exponential operator(**)

Page 82: 1 Rdbms SQL Pl SQL

- 82 -Copyright Infogain Corporation, 2007

OPERATOR OPERATION

**, NOT

+, -

*, /

+, -, ||

=, !=, <, >, <=, >=, ISNULL, LIKE,BETWEEN, IN

AND

OR

Exponentiation, logical negation

Identity, negation

Multiplication,division

Addition,subtraction,concatenation

Comparison

Conjunction

Inclusion

Operators in PL/SQL (cont.)Operators in PL/SQL (cont.)

Page 83: 1 Rdbms SQL Pl SQL

- 83 -Copyright Infogain Corporation, 2007

Bind VariablesBind Variables

Bind Variables in PL/SQL can be used using a colon(:) as a prefix.

Example:VARIABLE g_salary NUMBERDECLARE v_salary customer_data.salary%TypeBEGIN SELECTsalary INTO v_salary FROM customer_data WHERE id = 2:g_salary := v_sal;END;/SQL> PRINT g_salary

Page 84: 1 Rdbms SQL Pl SQL

- 84 -Copyright Infogain Corporation, 2007

Determining Variable ScopeDetermining Variable Scope

. . .

x Number;

BEGIN

. . .

DECLARE

y Number;

BEGIN

. . .

END;

. . .

END;

Scope of x

Scope of y

Page 85: 1 Rdbms SQL Pl SQL

- 85 -Copyright Infogain Corporation, 2007

Writing SQL Statements in PL/SQL BlockWriting SQL Statements in PL/SQL Block

The syntax of SQL Statements in the PL/SQL environmentSELECT select_list

INTO { variable_name[, variable_name] …

| record_name }

FROM table | view

WHERE condition;

Page 86: 1 Rdbms SQL Pl SQL

- 86 -Copyright Infogain Corporation, 2007

Retrieving Data in PL/SQLRetrieving Data in PL/SQL

Example:

DECLARE

v_salary number;

BEGIN

select salary INTO v_salary

FROM customer_data

WHERE id = 1;

END;

/

Page 87: 1 Rdbms SQL Pl SQL

- 87 -Copyright Infogain Corporation, 2007

Insert/Update DataInsert/Update Data

Example: INSERTBEGIN

INSERT INTO customer_data (ID, USERNAME, SALARY) VALUES (3,’THOMAS’,12000);

END;

Example: UPDATEDeclare

v_sal_incr customer_data.salary%TYPE:= 13000;Begin

update customer_dataset salary= salary + v_sal_incrwhere state = ‘MAHARASTRA’;

End;

Page 88: 1 Rdbms SQL Pl SQL

- 88 -Copyright Infogain Corporation, 2007

Deleting DataDeleting Data

Declare

v_id customer_data%TYPE:= 3;

Begin

Delete from customer_data

where id=v_id;

End;

Page 89: 1 Rdbms SQL Pl SQL

- 89 -Copyright Infogain Corporation, 2007

Commit and RollbackCommit and Rollback

When a transaction starts with a DML command, COMMIT or ROLLBACK can be used to make the transaction permanent or revoke them.

A Transaction gets saved when COMMIT is issued and terminated when ROLLBACK is used.

Page 90: 1 Rdbms SQL Pl SQL

- 90 -Copyright Infogain Corporation, 2007

Commit and Rollback (cont.)Commit and Rollback (cont.)

Syntax

COMMIT [transaction];

SAVEPOINT savepoint_name ;

ROLLBACK [transaction] ;

ROLLBACK [transaction] TO [SAVEPOINT] savepoint ;

Page 91: 1 Rdbms SQL Pl SQL

- 91 -Copyright Infogain Corporation, 2007

Control Statements – Loops, IfControl Statements – Loops, If

PL/SQL like other third generation languages, has a variety of Control structures that allow you to control the behavior of the block as it runs.

PL/SQL provides a facility for executing statements repeatedly, via loops. Loops are divided into three categories:• Simple loops• WHILE loops• FOR loops.

Page 92: 1 Rdbms SQL Pl SQL

- 92 -Copyright Infogain Corporation, 2007

Control Statements – Loops, If (cont.)Control Statements – Loops, If (cont.)

The IF clause can be used for the conditional processing of statements.

If the condition specified after the IF clause evaluates to true, the statements following the THEN clause are executed until one of the following is encountered: ELSIF, ELSE or END IF.

Page 93: 1 Rdbms SQL Pl SQL

- 93 -Copyright Infogain Corporation, 2007

Simple LoopsSimple Loops

The most basic kind of loops is Simple loops.

Sequence of statements will be executed infinitely, since this loop has no stopping condition.

The syntax is:• LOOP • < statements >• END LOOP;

Page 94: 1 Rdbms SQL Pl SQL

- 94 -Copyright Infogain Corporation, 2007

While LoopsWhile Loops

The condition is evaluated before each iteration of the loop.

If it evaluates to TRUE, sequence of statements is executed.

If condition evaluates to FALSE or NULL the loop is finished and control resumes after the END LOOP statement.

The syntax is:• WHILE < condition > LOOP• < statements >• END LOOP;

Page 95: 1 Rdbms SQL Pl SQL

- 95 -Copyright Infogain Corporation, 2007

Numeric for LoopsNumeric for Loops

The number of interactions for simple loops and WHILE loops is not known in advance.

It depends on the loop condition.

Numeric FOR loops, on the other hand, have a defined number of interactions.

The syntax is:FOR ctr IN 1……20LOOPINSERT INTO temp values (ctr);………..………..END LOOP;

Page 96: 1 Rdbms SQL Pl SQL

Cursors

Page 97: 1 Rdbms SQL Pl SQL

- 97 -Copyright Infogain Corporation, 2007

SQL CursorSQL Cursor

A Cursor is a memory area in which the SQL statement is parsed and executed. This memory area is also called as the Context Area

Cursors are of two types• Implicit Cursors• Explicit Cursors

Implicit Cursors are used by the Oracle Server to parse and execute the SQL statements

Explicit Cursors are declared explicitly by the programmer to handle the context area of the cursor

Page 98: 1 Rdbms SQL Pl SQL

- 98 -Copyright Infogain Corporation, 2007

SQL%ROWCOUNT

SQL%FOUND

SQL%NOTFOUND

SQL%ISOPEN

Number of rows affected by the most recent SQL statement (an Integer value)

Boolean attribute that evaluates to TRUE if the most recent SQL statement affects one or more rows

Boolean attribute that evaluates to TRUE if the most recent SQL statement does not affect any rows

Always evaluates to FALSE because PL/SQL closes implicit cursors immediately after they are executed

Implicit Cursor AttributesImplicit Cursor Attributes

The outcome of the SQL statement can be determined by the implicit cursor attributes.

Page 99: 1 Rdbms SQL Pl SQL

- 99 -Copyright Infogain Corporation, 2007

Implicit Cursor Attribute ExampleImplicit Cursor Attribute Example

Variable rows_deleted varchar2(30)

Declare

v_id customer_data%TYPE:= 3;

Begin

Delete from customer_data

where id=v_id;

:rows_deleted:= (SQL%ROWCOUNT || ‘ rows deleted. ‘);

End;

Print rows_deleted

Page 100: 1 Rdbms SQL Pl SQL

- 100 -Copyright Infogain Corporation, 2007

Explicit CursorExplicit Cursor

Explicit Cursors are declared explicitly by the user, along with other identifiers to be used in a block, and manipulated through specific statements within the block’s executable actions.

Explicit cursors are for queries only, and allow multiple rows to be processed from the query.

The four PL/SQL steps necessary for explicit cursor processing are as follows:• Declare the cursor for a query.• Open the cursor .• Fetch a row from the cursor [continue till all rows are fetched].• Close the cursor.

Page 101: 1 Rdbms SQL Pl SQL

- 101 -Copyright Infogain Corporation, 2007

Declaring a CursorDeclaring a Cursor

SYNTAX• CURSOR cursor_name IS

– select statement;

The INTO clause cannot be used in the select statement of the cursor declaration.

The ORDER BY Clause can be used if a specific sequence is required.

Page 102: 1 Rdbms SQL Pl SQL

- 102 -Copyright Infogain Corporation, 2007

Opening, Fetching and Closing the CursorOpening, Fetching and Closing the Cursor

DECLARE V_ID customer_data.ID%TYPE V_USERNAME customer_data. USERNAME %TYPE V_PASSWD customer_data. PASSWD %TYPE V_STATE customer_data. STATE %TYPE V_COUNTRY customer_data. COUNTRY %TYPE V_SALARY customer_data. SALARY %TYPECURSOR cust_cursor is

select * from customer_data;BEGINOpen cust_cursor;For j in 1 . . 3 Loop

Fetch cust_cursor into V_ID, V_USERNAME, V_PASSWD, V_STATE, V_COUNTRY, V_SALARY ;

. . . .END;

Page 103: 1 Rdbms SQL Pl SQL

- 103 -Copyright Infogain Corporation, 2007

Attribute Type Description

%ISOPEN

%NOTFOUND

%FOUND

%ROWCOUNT

BOOLEAN

BOOLEAN

BOOLEAN

NUMBER

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

Evaluates to the total number of rows returned so far

Explicit Cursor AttributesExplicit Cursor Attributes

Page 104: 1 Rdbms SQL Pl SQL

- 104 -Copyright Infogain Corporation, 2007

The %ISOPEN attribute example

. . .

IF NOT cust_cursor %ISOPEN THEN

OPEN cust_cursor ;

END IF;

LOOP

FETCH cust_cursor;

. . . .

Page 105: 1 Rdbms SQL Pl SQL

- 105 -Copyright Infogain Corporation, 2007

The %ROWTYPE AttributeThe %ROWTYPE Attribute

Used to declare a variable according to a collection of columns in a database table or view.

A database table is prefixed with %ROWTYPE attribute

Fields in the record take their names and data type from the columns of the table or view.

Example:• Declare• customer_record ra_customers%ROWTYPE;…

Page 106: 1 Rdbms SQL Pl SQL

- 106 -Copyright Infogain Corporation, 2007

Advantages of %ROWTYPEAdvantages of %ROWTYPE

The number and datatypes of the underlying database columns may not be known

The number and data types of the underlying database column may change at runtime.

The attribute is useful when retrieving a row with the SELECT statement.

Page 107: 1 Rdbms SQL Pl SQL

- 107 -Copyright Infogain Corporation, 2007

Cursor FOR loopCursor FOR loop

SYNTAX…

Begin

FOR record_name IN cursor_name LOOP

-- Implicit open and fetch occur

statement1;

statement2;

. . .

END LOOP;

Implicit open, fetch and close occurs

The record is implicitly declared

Page 108: 1 Rdbms SQL Pl SQL

- 108 -Copyright Infogain Corporation, 2007

ProceduresProcedures

A Procedure is a subprogram that perform a specific action

A Procedure can be called from any PL/SQL program

Procedures can also be invoked from the SQL prompt

The Procedure has two parts: Specification: A procedure specification begins with keyword

create or replace & ends with parameter list.

Body: A procedure body begins with ‘Is’ and ends with ‘End’.

Page 109: 1 Rdbms SQL Pl SQL

- 109 -Copyright Infogain Corporation, 2007

Calling

environment

Procedure IN parameter

OUT parameter

IN OUT parameter

(DECLARE)

BEGINE

EXCEPTION

END;

Procedural ParametersProcedural Parameters

Page 110: 1 Rdbms SQL Pl SQL

- 110 -Copyright Infogain Corporation, 2007

ExampleExample

CREATE OR REPLACE PROCEDURE raise cost

(m_stockitemno IN stock_item_master.stock_item_number%type)

IS

BEGIN

update stock_item_master

set cost = cost + (cost * 0.5)

where stock_item_number = m_stockitemno;

commit;

END raise_cost;

 

To execute the procedure form the SQL prompt give following command –

EXECUTE get_cost(‘STOCK_ITEM_NO’);

Page 111: 1 Rdbms SQL Pl SQL

- 111 -Copyright Infogain Corporation, 2007

FunctionsFunctions

A function is a named PL/SQL block that returns a value.

A function can be stored in the database, as a database object, for repeated execution.

A function can be called as a part of expression.

In function INSERT, UPDATE, or DELETE commands are not allowed.

Page 112: 1 Rdbms SQL Pl SQL

- 112 -Copyright Infogain Corporation, 2007

ExampleExample

CREATE OR REPLACE FUNCTION get_cost (m_stockitemno IN stock_item_master.stock_item_number%type) RETURN numberIS m_cost stock_item_master.cost%type;BEGIN select cost into m_cost from stock_item_master where stock_item_number = m_stockitemno; RETURN (m_cost);END get_cost;  To run the function form the SQL prompt give following command – Select get_cost(‘STOCK_ITEM_NO’) from dual;

Page 113: 1 Rdbms SQL Pl SQL

- 113 -Copyright Infogain Corporation, 2007

PackagesPackages

A Package is a database object that groups logically related PL/SQL objects.

Packages are groups of procedures, functions, variables, and SQL statements grouped together into a single unit.

There is considerable performance improvement because of this encapsulation.

Page 114: 1 Rdbms SQL Pl SQL

- 114 -Copyright Infogain Corporation, 2007

Packages (cont.)Packages (cont.)

The entire package is located into the memory when a procedure, within the package is called for the first time.

This reduces the unnecessary disk I/O and network traffic.

Packages usually have two parts, a specification and a body.

In Package specification we can declare type, cursor, procedure.

Page 115: 1 Rdbms SQL Pl SQL

- 115 -Copyright Infogain Corporation, 2007

FUNCTION get_cost

(m_stockitemno IN stock_item_master.stock_item_number%type)

RETURN number

IS

m_cost stock_item_master.cost%type;

BEGIN

select cost into m_cost from stock_item_master

where stock_item_number = m_stockitemno;

RETURN (m_cost);

END get_cost;

END comm_package;

Page 116: 1 Rdbms SQL Pl SQL

- 116 -Copyright Infogain Corporation, 2007

Trap the exception Propagate the exception

DECLARE

BEGIN

EXCEPTION

END ;

DECLARE

BEGIN

EXCEPTION

END ;

Exception HandlingException Handling

Page 117: 1 Rdbms SQL Pl SQL

- 117 -Copyright Infogain Corporation, 2007

Exception TypesException Types

Implicitly raised• Predefined Oracle Server• Non-predefined Oracle Server

Explicitly raised• User-defined

Page 118: 1 Rdbms SQL Pl SQL

- 118 -Copyright Infogain Corporation, 2007

Trapping ExceptionsTrapping Exceptions

SyntaxEXCEPTIONS

WHEN exception A [OR exception B . . .] THENstatement1;statement2;. . .

[WHEN exception C [OR exception D . . .] THENstatement1;statement2;. . .

[ WHEN OTHERS THENstatement1;statement2;. . . ]

Page 119: 1 Rdbms SQL Pl SQL

- 119 -Copyright Infogain Corporation, 2007

Predefined Oracle Server ErrorsPredefined Oracle Server Errors

Sample predefined exceptions– NO_DATA_FOUND– TOO_MANY_ROWS– INVALID_CURSOR– ZERO_DIVIDE– DUP_VAL_ON_INDEX

Page 120: 1 Rdbms SQL Pl SQL

- 120 -Copyright Infogain Corporation, 2007

Trapping Non-Predefined ErrorsTrapping Non-Predefined Errors

Declare a user defined exception

Associate it with the Oracle defined error using PRAGMA EXCEPTION INIT

Handle the raised exception.

Page 121: 1 Rdbms SQL Pl SQL

- 121 -Copyright Infogain Corporation, 2007

Functions for Trapping ExceptionsFunctions for Trapping Exceptions

SQLCODE

Returns the numeric value for the error code

SQLERRM

Returns the messages associated with the error number

Page 122: 1 Rdbms SQL Pl SQL

- 122 -Copyright Infogain Corporation, 2007

Trapping User Defined ExceptionTrapping User Defined Exception

Declare the exception

Explicitly raise the exception by using the RAISE statement

Handle the raised exception

Page 123: 1 Rdbms SQL Pl SQL

- 123 -Copyright Infogain Corporation, 2007

The RAISE_APPLICATION_ERROR PROCEDUREThe RAISE_APPLICATION_ERROR PROCEDURE

A procedure that lets you issue user defined error messages from stored subprograms

Called only from an executing stored subprogram

Syntax

raise_application_error (error_number, message[, (TRUE | FALSE]);

Page 124: 1 Rdbms SQL Pl SQL

- 124 -Copyright Infogain Corporation, 2007

PL/SQL TRIGGERSPL/SQL TRIGGERS

A Trigger is defined as an action the database should take when some database related event occurs.

Type Of Triggers• Row-Level Triggers• Statement Level Triggers• BEFORE and AFTER Triggers• INSTEAD OF Triggers• System or User Event Triggers

Page 125: 1 Rdbms SQL Pl SQL

- 125 -Copyright Infogain Corporation, 2007

Trigger SyntaxTrigger Syntax

create [ or replace ] trigger [schema . .] trigger

{ before | after | instead of }

{ dml event cause

| { ddl_event [or ddl_event] . . .

}

on { [ schema . .] schema | database }

}

[ when ( condition ) ]

{ pl/sql_block | call_procedure_statement }

Page 126: 1 Rdbms SQL Pl SQL

- 126 -Copyright Infogain Corporation, 2007

Row Level TriggerRow Level Trigger

A row trigger is fired each time the table is affected by the triggering statement

If an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row affected by the UPDATE statement

If a triggering statement affects no rows, a row trigger is not executed.

Page 127: 1 Rdbms SQL Pl SQL

- 127 -Copyright Infogain Corporation, 2007

Statement Level TriggerStatement Level Trigger

A statement trigger is fired once on behalf of the triggering statement, regardless of the number of rows in the table that the triggering statement affects, even if no rows are affected.

For example, if a DELETE statement deletes several rows from a table, a statement-level DELETE trigger is fired only once.

Page 128: 1 Rdbms SQL Pl SQL

- 128 -Copyright Infogain Corporation, 2007

Before and After TriggerBefore and After Trigger

When defining a trigger, you can specify the trigger timing--whether the trigger action is to be executed before or after the triggering statement.

BEFORE and AFTER triggers fired by DML statements can be defined only on tables, not on views. However, triggers on the base tables of a view are fired if an INSERT, UPDATE, or DELETE statement is issued against the view.

BEFORE and AFTER triggers fired by DDL statements can be defined only on the database or a schema, not on particular tables.

Page 129: 1 Rdbms SQL Pl SQL

- 129 -Copyright Infogain Corporation, 2007

Before and After Trigger CombinationsBefore and After Trigger Combinations

BEFORE statement trigger

BEFORE row trigger

AFTER row trigger

AFTER statement trigger

Page 130: 1 Rdbms SQL Pl SQL

- 130 -Copyright Infogain Corporation, 2007

INSTEAD OF TriggersINSTEAD OF Triggers

These triggers are called INSTEAD OF triggers because, unlike other types of triggers, Oracle fires the trigger instead of executing the triggering statement.

INSTEAD OF triggers provide a transparent way of modifying views that cannot be modified directly through DML statements (INSERT, UPDATE, and DELETE)

You can write normal INSERT, UPDATE, and DELETE statements against the view and the INSTEAD OF trigger is fired to update the underlying tables appropriately

INSTEAD OF triggers are activated for each row of the view that gets modified

Page 131: 1 Rdbms SQL Pl SQL

- 131 -Copyright Infogain Corporation, 2007

System Or User Event TriggerSystem Or User Event Trigger

System events • Database startup and shutdown • Server error message events

User events • User logon and logoff • DDL statements (CREATE, ALTER, and DROP) • DML statements (INSERT, DELETE, and UPDATE)

Page 132: 1 Rdbms SQL Pl SQL

- 132 -Copyright Infogain Corporation, 2007

ExampleExample

CREATE OR REPLACE TRIGGER secure_stock

BEFORE INSERT ON stock_item_master

BEGIN

IF (to_char(sysdate,'DY') IN ('SAT','SUN')) or

(to_char(sysdate,'HH24') NOT BETWEEN '09' and '18') then

raise_application_error(-20500,'You may only insert during normal hours...');

END IF;

END;