Oracle SQL & PL/SQL Training: Click To Edit Master Subtitle Style

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 99

ORACLE SQL & PL/SQL Training

Click to edit Master subtitle style

7/27/12

11

Database Oracle Client Server SQL Contraints Basic Datatypes DDL DML DCL TCL OTHER SQL TERMS STRING FUNCTIONS DATE FUNCTIONS EXISTS STATEMENT

CONTENTS

7/27/12 JOINS

22

Database

A database is a collection of information(data) that is organized so that it can easily be accessed, managed, and updated.

Client Server

Often, the client runs on a different computer than the database server, generally on a PC. Many clients can simultaneously run against one server.

7/27/12

33

Oracle Client Server


Server Gets data requests from clients Adds, Deletes and updates data Sends results to clients NETWORK

Client A Sends data requests to server Receives results from server Sends new data or changes to server

Client B Sends data requests to server Receives results from server Sends new data or changes to server

7/27/12

44

Why Database ?

7/27/12

55

SQL

Structured Query Language (SQL) is a specialized language for updating, deleting, and requesting information from databases.
USER
SQL Query Syntactic and Symantec Analysis SQL Compiler Opt. Mod e Query Plan R E S U L T S

Parser

Row Source Generator


Execution Plan SQL Execution

7/27/12

66

SQL

All SQL Commands can be categorized into four different languages

DDL (Data Definition Language) - used to define the database structure.


CREATE - to create objects in the database ALTER - alters the structure of the database DROP - delete objects from the database TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed

DML (Data Manipulation Language) - used for managing data


SELECT - retrieve data from the a database INSERT - insert data into a table UPDATE - updates existing data within a table DELETE - deletes all records from a table, the space for the records remain

DCL (Data Control Language) used for controlling data

GRANT - gives user's access privileges to database REVOKE - withdraw access privileges given with the GRANT command

7/27/12

77

Contraints

Primary Key : Unique not null column

Foreign Key : A not null column and is referring to a primary key of another table.

Not Null : Which cannot have a null value

Check : (Sal > 1000) Each and every value for SAL column should be greater than 1000

Unique 7/27/12 : It is unique but it can take null value.

88

Basic Data Types Used

VARCHAR2(Size) : Variable Length Character String

NUMBER(P,S) : Number having precision P and scale S

DATE : Valid Date range

CHAR(Size) : Fixed length character data of length size bytes. This should be used for fixed length data. Such as codes A100, B102

7/27/12

99

DDL (Data Definition Language)

CREATE TABLE Statement

CREATE TABLE table_name

( column1 datatype [null/not null], column2 datatype [null/not null], column3 datatype [null/not null], ... );

Example:
employee_number number(10) not null , employee_name varchar2(50) not null , department_id number(10)

CREATE TABLE employees (

7/27/12

, salary number(6)

1010

DDL Contd.

ALTER STATEMENT

ALTER TABLE table_name RENAME TO new_table_name; ALTER TABLE table_name ADD column_name column-definition; ALTER TABLE table_name ADD ( column_1 column-definition, column_2 columndefinition, ... column_n column_definition ); ALTER TABLE table_name MODIFY column_name column_type; ALTER TABLE table_name MODIFY ( column_1 column_type, column_2 column_type, ... column_n column_type ); ALTER TABLE table_name DROP COLUMN column_name; ALTER TABLE table_name RENAME 7/27/12 COLUMN old_name to new_name;

1111

DDL Contd.

DROP Statement

DROP TABLE table_name;

TRUNCATE Statement

TRUNCATE TABLE table_name;

7/27/12

1212

DML (Data Manipulation Language)

SELECT Statement
SELECT columns FROM tables WHERE predicates;

INSERT Statement

INSERT INTO table (column-1, column-2, ... column-n) VALUES (value-1, value-2, ... value-n);

UPDATE Statement
UPDATE table SET column = expression WHERE predicates;

DELETE Statement
WHERE predicates; DELETE 7/27/12 FROM table

1313

DCL Data Control Logic


GRANT grant privileges on object to user; REVOKE revoke privileges on object from user; Privilege Description
Select Insert Update Delete References Alter Index Ability to query the table with a select statement. Ability to add new rows to the table with the insert statement. Ability to update rows in the table with the update statement. Ability to delete rows from the table with the delete statement. Ability to create a constraint that refers to the table. Ability to change the table definition with the alter table statement. Ability to create an index on the table with the create index statement.

7/27/12

1414

TCL (Transaction Control Logic)

SAVEPOINT savepointname(e2); ROLLBACK TO SAVEPOINT e2; COMMIT;

7/27/12

1515

OTHER SQL TERMS

DISTINCT AND/OR Condition LIKE IN/SUBQUERY BETWEEN GROUP BY/AGGREGATE functions (COUNT/SUM/MIN/MAX) HAVING ORDER BY UNION Query UNION ALL Query
7/27/12 INTERSECT Query 1616

STRING Functions

LOWER UPPER INITCAP SUBSTR INSTR CONCAT (|| We can also use pipe) LPAD RPAD LTRIM RTRIM REVERSE

7/27/12

REPLACE TRANSLATE

1717

DATE FUNCTIONS

SYSDATE TO_CHAR(date, format) TO_DATE(date, format_mask) FORMAT: 'DD-MON-YYYY HH:MI:SS TRUNC ADD_MONTHS NEXT_DAY (NEXT_DAY(<date>, <day of the week>)) MONTHS_BETWEEN

7/27/12

1818

JOINS

Inner Join (Simple Join)

This is the simple join we use regularly. Used in order to fetch more data than that actually matches Used to join a table to the same table
1919 Join with out a where clause results in

Outer Join (Left/Right/Full)

Self Join

Cross Join (Cartesian Product)


7/27/12

EXISTS Statement

The EXISTS condition is considered "to be met" if the subquery returns at least one row.

SELECT columns FROM tables WHERE EXISTS ( subquery );

The EXISTS condition can be used in any valid SQL statement - select, insert, update, or delete.

7/27/12

2020

VIEWS

A view is, in essence, a virtual table. It does not physically exist. Rather, it is created by a query joining one or more tables. CREATE VIEW view_name AS SELECT columns FROM table WHERE predicates;

7/27/12

2121

CASE and DECODE Statements

DECODE Statement

DECODE (value, <if this value>, <return this value>, <if this value>, <return this value>, .... <otherwise this value>)

CASE Statement

CASE WHEN (<Condition 1>) THEN <Return this value> WHEN (<Condition 2>) THEN <Return this value> . ELSE <otherwise this value>

END

CASE is the later version of DECODE. It is only available in the version after Oracle 8

7/27/12

2222

ETL

Legacy System

Flat Files Ext Table Stg Table Targe t Table

New Oracle System

7/27/12

2323

External Tables

External Tables let you query data in a flat file as though the file were an Oracle table.

External tables can be queried, but they are not usable in many ways regular oracle tables are used.

You cannot perform any DML operations on external tables other than table creation.

Oracle uses ORACLE_LOADER access driver to move data from flat file into the database.
7/27/12 2424

External Tables

FLAT FILE

External Table

Physical Directory C:\Temp

Database Directory

7/27/12

Database Server

2525

External Tables Client Side Server Side


Client Side
1. Create a flat file and send it to DBA to copy it on to the Server 2. DBA should create a physical directory in the OS and copy the file on to that location. 3. Create a directory in oracle database which points to the physical directory created in Step 2. Grants select access to client user. 4. Create an external table which points to the directory created in oracle database by the DBA. 5. Now we can directly select data from the external table as if we are selecting data from any other table.
Note: Generally in the work location the machine you will be working will have oracle client installed on it, database will be on some other machine(Server). We will not have permissions to access the Server, only DBAs has access to them. But if you are practicing on your home machine both the database and client will be on same machine, so you can perform both the client side and server side tasks by yourself.

Server Side

7/27/12

2626

PL/SQL

PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90s to enhance the capabilities of SQL. The PL/SQL Engine:

Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be stored in the client system (client-side) or in the database (server-side).

7/27/12

2727

PL/SQL Block
DECLARE Variable declaration BEGIN Program Execution EXCEPTION Exception handling END;

Every statement in the above three sections must end with a semicolon( ; ). PL/SQL blocks can be nested within other PL/SQL blocks. Comments can be used to document code.

7/27/12

2828

PLACE HOLDERS Variables and Constants

Variables and Constants

Variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value] For example: Declaring a variable: l_var varchar2(40); Declaring a constant: l_cons CONSTANT numeric(8,1) := 8363934.1; Declaring a variable with an initial value (not a constant): lvar varchar2(10) := 'Example'; 7/27/12 2929

PLACE HOLDERS Records

Records: A record is a group of related data items stored in fields, each with its own name and datatype. Suppose you have various data about an employee such as name, salary, and hire date. These items are logically related but dissimilar in type. A record containing a field for each item lets you treat the data as a logical unit. Thus, records make it easier to organize and represent information.

TYPE type_name IS RECORD (field_declaration[,field_declaration]...);

The attribute %ROWTYPE lets you declare a record that 7/27/12 3030 represents a row in a database table.

PLACE HOLDERS - Cursors

A cursor is a mechanism by which you can assign a name to a "select statement" and manipulate the information within that SQL statement.

Declare Statement

CURSOR cursor_name IS SELECT_statement;

Open Statement

OPEN cursor_name;

Fetch Statement

FETCH cursor_name INTO <list of variables>;

Close Statement

CLOSE cursor_name;

Cursor Attributes

%ISOPEN - Returns TRUE if the cursor is open, FALSE if the cursor is closed. %ISFOUND - Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.

7/27/12

3131 - Returns NULL if cursor is open, but fetch has not been executed.

PLACE HOLDERS - Cursors

%ISNOTFOUND

Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed. - Return NULL if cursor is open, but fetch has not been executed. Returns FALSE if a successful fetch has been executed. Returns TRUE if no row was returned.

%ROWCOUNT

Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed. - Returns the number of rows fetched. The ROWCOUNT attribute doesn't give the real row count until you have iterated through the entire cursor. In other words, you shouldn't rely on this attribute to tell you how many rows are in a cursor after it is opened.

7/27/12

3232

Cursor For Loop

This is a simpler version to the Cursor Using this we avoid many of the Cursor steps we discussed in the previous slides. No declarations are required. Can be directly used in the executable section.
7/27/12

Syntax
FOR record_index in cursor_name

3333

Loops and Conditional Statements

IF THEN ELSE

Syntax:

IF condition THEN {...statements...} ELSIF condition THEN {...statements...} ELSE {...statements...} END IF;

7/27/12

3434

Loops and Conditional Statements

GOTO Statement

The GOTO statement causes the code to branch to the label after the GOTO statement.

For example: GOTO label_name; Then later in the code, you would place your label and code associated with that label.

<<Label_name>> {statements}
3535

7/27/12

Loops and Conditional Statements


FOR LOOP The syntax for the FOR Loop is:

FOR loop_counter IN [REVERSE] lowest_number..highest_number LOOP {.statements.} END LOOP;


3636

7/27/12

You would use a FOR Loop when you

WHILE LOOP

Loops and Conditional Statements

The syntax for the WHILE Loop is: WHILE condition LOOP {.statements.} END LOOP; You would use a WHILE Loop when you are not sure how many times you will execute the loop body. Since the WHILE condition is evaluated before entering the loop, it is possible that the loop body may not execute even once.

7/27/12

3737

Loops and Conditional Statements

DO WHILE OR REPEAT UNTILL LOOP


Oracle doesn't have a Repeat Until loop, but you can emulate one. The syntax for emulating a REPEAT UNTIL Loop is: LOOP {.statements.} EXIT WHEN boolean_condition; END LOOP;

You would use an emulated REPEAT UNTIL Loop when you do not know how many times you want the loop body to execute. The REPEAT UNTIL Loop would terminate when a 7/27/12 3838 certain condition was met.

Exceptions

PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block known as exception Handling. Using Exception Handling we can test the code and avoid it from exiting abruptly.

PL/SQL Exception message consists of three parts. 1) Type of Exception 2) An Error Code 3) A message By Handling the exceptions we can ensure a PL/SQL block does not exit abruptly.

7/27/12

3939

Structure of Exception
DECLARE Declaration section BEGIN Execution section EXCEPTION WHEN ex_name1 THEN -Error handling statements WHEN ex_name2 THEN -Error handling statements WHEN Others THEN
7/27/12 handling statements -Error 4040

Nested PL/SQL Block


DELCARE Declaration section BEGIN DECLARE Declaration section BEGIN Execution section EXCEPTION Exception section END;
7/27/12 EXCEPTION 4141

Types Of Exceptions

There are 3 types of Exceptions.

a) Named System Exceptions


System exceptions are automatically raised by Oracle, when a program violates a rule.

b) Unnamed System Exceptions


System exception for which oracle does not provide a name is known as unnamed system exception.

c) User-defined Exceptions
rules.

We can explicitly define these exceptions based on

business

7/27/12

4242

Named System Exception

System exceptions are automatically raised by Oracle, when a program violates a rule. There are some system exceptions which are raised frequently, so they are predefined and given a name in Oracle which are known as Named System Exceptions. For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions. Named system exceptions are: 1) Not Declared explicitly, 2) Raised implicitly when a predefined Oracle error occurs, 3) Caught by referencing the standard name within an exception-handling routine.

7/27/12

4343

Named System Exception


Exception Name Reason CURSOR_ALREADY_ When you open a cursor that is already OPEN open. INVALID_CURSOR When you perform an invalid operation ORA-01001 on a cursor like closing a cursor, fetch data from a cursor that is not opened. NO_DATA_FOUND When a SELECT...INTO clause does not ORA-01403 return any row from a table. TOO_MANY_ROWS When you SELECT or fetch more than ORA-01422 one row into a record or variable. Syntax: ZERO_DIVIDE When you attempt to divide a number by ORA-01476 zero. Error Number ORA-06511

BEGIN Execution section EXCEPTION WHEN NO_DATA_FOUND THEN dbms_output.put_line ('A SELECT...INTO did not return any row.'); END; 7/27/12 4444

Unnamed System Exceptions

Those system exception for which oracle does not provide a name is known as unnamed system exception.

These exceptions do not occur frequently. These Exceptions have a code and an associated message.

There are two ways to handle unnamed system exceptions:

1. By using the WHEN OTHERS (SQL CODE AND SQL ERRM) exception handler, or 2. By associating the exception code to a name and using it as a named exception.

7/27/12

4545

Unnamed System Exceptions Contd.

We can assign a name to unnamed system exceptions using a Pragma called EXCEPTION_INIT. EXCEPTION_INIT will associate a predefined Oracle error number to a programmer defined exception name.

Steps to be followed to use unnamed system exceptions are

They are raised implicitly. If they are not handled in WHEN Others they must be handled explicitly. To handle the exception explicitly, they must be declared using Pragma EXCEPTION_INIT and handled referencing the user-defined exception name in the exception section.

7/27/12

4646

Unnamed Exception Contd.


DECLARE exception_name EXCEPTION; PRAGMA EXCEPTION_INIT (exception_name, Err_code); BEGIN Execution section EXCEPTION WHEN exception_name THEN handle the exception END;
7/27/12 4747

User Defined Exceptions

Apart from system exceptions we can explicitly define exceptions based on business rules. These are known as user-defined exceptions.

Steps to be followed to use user-defined exceptions:

They should be explicitly declared in the declaration section. They should be explicitly raised in the Execution Section. They should be handled by referencing the user-defined exception name in the exception section.

7/27/12

4848

User Defined Exceptions


DECLARE exception_name EXCEPTION; BEGIN Execution section Raise exception_name EXCEPTION WHEN exception_name THEN handle the exception END;

7/27/12

4949

RAISE_APPLICATION_ERROR ()

RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to display the user-defined error messages along with the error number whose range is in between -20000 and -20999. Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous transactions which are not committed within the PL/SQL Block are rolled back automatically (i.e. change due to INSERT, UPDATE, or DELETE statements). RAISE_APPLICATION_ERROR raises an exception but does not handle it. RAISE_APPLICATION_ERROR is used for the following reasons, a) to create a unique id for an user-defined exception. b) to 7/27/12 make the user-defined exception look like an Oracle 5050 error.

RAISE_APPLICATION_ERROR ( )

The General Syntax to use this procedure is: RAISE_APPLICATION_ERROR (error_number, error_message); The Error number must be between -20000 and -20999 The Error_message is the message you want to display when the error occurs. Steps to be folowed to use RAISE_APPLICATION_ERROR procedure: 1. Declare a user-defined exception in the declaration section. 2. Raise the user-defined exception based on a specific business rule in the execution section. 3. Finally, catch the exception and link the exception to a user-defined error number in RAISE_APPLICATION_ERROR.
7/27/12 5151

Exceptions in Nested PL/SQL Block


DELCARE Declaration section BEGIN DECLARE Declaration section BEGIN Execution section EXCEPTION Exception section END; EXCEPTION 7/27/12 5252

Sequences (Autonumber)

In Oracle, we can create an auto number field by using sequences. A sequence is an object in Oracle that is used to generate a number sequence. This can be used when you need to create a unique number to act as a primary key. CREATE SEQUENCE sequence_name MINVALUE value MAXVALUE value START WITH value INCREMENT BY value CACHE value;

7/27/12

5353

Sequence Attributes

Seq_name.nextval : This would retrieve the next value from the sequence Seq_name. Seq_name.currval : This would retrieve the current value from the sequence Seq_name.

7/27/12

5454

Stored Program Units

A stored procedure, function, or package is a PL/SQL program unit that:

Has a name. Can take parameters, and can return values. Is stored in the data dictionary. Anonymous Blocks SubPrograms Can be called by many users Unnamed PL/SQL blocks Compiled every time Not stored in the database Named PL/SQL blocks Compiled only once Stored in the database

Cannot be invoked by other They are named and therefore can be applications invoked by other applications Subprograms called functions must Do not return values return values Cannot take parameters Can take parameters

7/27/12

5555

Mode of Arguement

In PL/SQL, we can pass parameters to procedures and functions in three ways.

1) IN type parameter: These types of parameters are used to send values to stored procedures. 2) OUT type parameter: These types of parameters are used to get values from stored procedures. This is similar to a return type in functions. 3) IN OUT parameter: These types of parameters are used to send values and get values from stored procedures.

NOTE: If a parameter is not explicitly defined a parameter type, then by default it is an IN type parameter.

7/27/12

5656

Procedure
CREATE [OR REPLACE] PROCEDURE procedure_name
[(argument1 [mode1] datatype1, argument2 [mode2] datatype2, . . .)]

IS|AS procedure_body;

Procedure_name : Is the name of the procedure to be created Argument: Is the name given to the procedure parameter. Every argument is associated with a mode and datatype. You can have any number or arguments separated by a comma. Mode: Mode of argument: IN (default), OUT, IN OUT Datatype: Is the data type of the associated parameter. The datatype of

7/27/12 parameters can not have explicit size, instead use %TYPE.

5757

Procedure

Create the procedure and compile it to store in the database

Invoke the procedure

BEGIN Procedure_name(parameters); END;

Create a procedure to add an employee to the employees table. The following values should be given as input to the procedure.

First_name, Last_name, Phone_number, JobId, Salary, managerr_id, department_id

Email should be calculated by concatenating first letter of first 7/27/12 5858 name with the last name and concatenate it with seearkay.com

Functions
CREATE [OR REPLACE] FUNCTION function_name [(argument1 [mode1] datatype1, argument2 [mode2] datatype2,. . .)] RETURN datatype IS|AS function_body

Function_name: Is the name of the function to be created Argument: Is the name given to the function parameter. Every argument is associated with a mode and datatype. You can have any number of arguments separated by a comma. You will pass the argument when you invoke the function Mode: The type of the parameter; only IN parameters should be declared Datatype: Is the data type of the associated parameter RETURN datatype: Is the data type of the value returned by the 7/27/12 5959 fuction

Functions

Create a function and compile it to store in the database. Invoke the function in this way

Begin Var:= function_name(parameters) End; OR function_name(parameters)6060 from

SELECT 7/27/12

Managing SubPrograms and Other Objects

Object Information user_objects Text of the subprogram user_source Syntax Errors user_errors

User_objects: object_name, object_id, object_type, created, last_ddl_time, timestamp, status

User_source: Name, Type, Line, Text

User_Errors: Name, Type, Sequence, Line, Position, Text


7/27/12 6161

ROWID

ROWID: Just as your home address uniquely identifies where you live, an Oracle ROWID uniquely identifies where a row resides on disk. The information in a ROWID gives Oracle everythingit needs to find your row, the disk number, the cylinder, block and offset into the block.

SELECT rowid, ta.*


FROM table_name ta;

7/27/12

6262

ROWNUM
ROWNUM:

The ROWNUM is a "pseudo-column", a placeholder that you can reference in SQL. The ROWNUM can be to select a subset of data from a table.

For example, to only display the first-10 rows, you might apply a ROWNUM filter:

select * from table_name whererownum<=10;

Note: Between or greater than operator cannot be used with 7/27/12 6363

ROWID VS ROWNUM

In sum, the difference between ROWNUM and ROWID is that

ROWNUM is temporary while ROWID is permanent.

ROWID can be used to fetch a row, while ROWNUM only has meaning within the context of a single SQL statement, a way of referencing rows within a fetched result set.

7/27/12

6464

Tiggers

A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete, Update is executed on a database table. Syntax: CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) BEGIN
7/27/12 6565

--- sql statements

Types Of Triggers

Insert Triggers:

Before Insert Trigger After Insert Trigger

Update Triggers:

Before Update Trigger After Update Trigger


6666

7/27/12

Before Insert Trigger

A BEFORE INSERT Trigger means that Oracle will fire this trigger before the INSERT operation is executed.

CREATE or REPLACE TRIGGER trigger_name BEFORE INSERT ON table_name [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END; Restrictions:

You can not create a BEFORE trigger on a view. You can update the :NEW values.

You 7/27/12 can not update the :OLD values.

6767

After Insert Trigger

An AFTER INSERT Trigger means that Oracle will fire this trigger after the INSERT operation is executed.

CREATE or REPLACE TRIGGER trigger_name AFTER INSERT ON table_name [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END; Restrictions:

You can not create an AFTER trigger on a view. You can not update the :NEW values.

You 7/27/12 can not update the :OLD values.

6868

Before Update Trigger

A BEFORE UPDATE Trigger means that Oracle will fire this trigger before the UPDATE operation is executed. CREATE or REPLACE TRIGGER trigger_name BEFORE UPDATE ON table_name [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END; Restrictions:

You can not create a BEFORE trigger on a view. You can update the :NEW values. You can not update the :OLD values.

7/27/12

6969

After Update Trigger

An AFTER UPDATE Trigger means that Oracle will fire this trigger after the UPDATE operation is executed. CREATE or REPLACE TRIGGER trigger_name AFTER UPDATE ON table_name [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END; Restrictions:

You can not create an AFTER trigger on a view. You can not update the :NEW values. You can not update the :OLD values.

7/27/12

7070

Before Delete Trigger

A BEFORE DELETE Trigger means that Oracle will fire this trigger before the DELETE operation is executed.

CREATE or REPLACE TRIGGER trigger_name BEFORE DELETE ON table_name [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END; Restrictions:

You can not create a BEFORE trigger on a view. You can update the :NEW values.

You 7/27/12 can not update the :OLD values.

7171

UTL_FILES

With the UTL_FILE package, PL/SQL programs can read and write operating system text files. Create a oracle directory which points to a physical directory like we did in external tables Copy the file into this directory Use UTL_FILE to read data and write data to files
7272

7/27/12

Collect Funciton(Adv)

Oracle 10g has introduced an extremely useful new group function, COLLECT.

This function enables us to aggregate data into a collection, retaining multiple records of data within a single row.

One of the main benefits of this function is that it makes "string aggregation" (one of the web's most-requested Oracle technique) very simple.

7/27/12

7373

SQL Loader

SQL Loader is used to load data from flat files in to oracle tables.

7/27/12

7474

SQL Loader : Control File

The control file is a text file written in a language that SQL*Loader understands. The control file tells SQL*Loader where to find the data, how to parse and interpret the data, where to insert the data, and more. First Section

Global options such as rows, records to skip, and so on INFILE clauses to specify where the input data is located Mode (Append/Insert)

Second Section

One or more INTO TABLE blocks. Each of these blocks contains information about the table into which the data is to be loaded, such as the table name and the columns of the table.

Third Section

Is optional and, if present, contains input data.

7/27/12

7575

SQL Loader : Control File Syntax Considerations

The syntax is free-format (statements can extend over multiple lines).

It is case insensitive; however, strings enclosed in single or double quotation marks are taken literally, including case.

In control file syntax, comments extend from the two hyphens (--) that mark the beginning of the comment to the end of the line. The optional third section of the control file is interpreted as data rather than as control file syntax; consequently, comments in this section are not supported.

The keywords CONSTANT and ZONE have special meaning to SQL*Loader and are therefore reserved. To avoid potential conflicts, Oracle recommends that you do not use either CONSTANT or ZONE as a name for any tables or columns.

7/27/12

7676

SQL Loader Input Data and Data Files

SQL*Loader reads data from one or more files (or operating system equivalents of files) specified in the control file. From SQL*Loader's perspective, the data in the datafile is organized as records.

The record format can be specified in the control file with the INFILE parameter. If no record format is specified, the default is stream record format.

Note: If data is specified inside the control file (that is, INFILE * was specified in the control file), then the data is interpreted in the stream record format with the default record terminator.

7/27/12

7777

SQL Loader : Log File

Log File and Logging Information : When SQL*Loader begins execution, it creates a log file. If it cannot create a log file, execution terminates. The log file contains a detailed summary of the load, including a description of any errors that occurred during the load. For Example
Table Name 6 Rows successfully loaded. 0 Rows not loaded due to data errors. 0 Rows not loaded because all WHEN clauses were failed. 0 Rows not loaded because all fields were null.

Total logical records skipped: Total logical records read: Total logical records rejected: Total logical records discarded:

0 6 0 0

Run began on Fri Aug 05 18:17:19 2011

7/27/12

7878

Run ended on Fri Aug 05 18:17:19 2011

SQL Loader: Discarded and Rejected Records

Records read from the input file might not be inserted into the database. Such records are placed in either a bad file or a discard file.

The Bad File: The bad file contains records that were rejected, either by SQL*Loader or by the Oracle database. If you do not specify a bad file and there are rejected records, then SQL*Loader automatically creates one. It will have the same name as the data file, with a .bad extension.

The Discard File: As SQL*Loader executes, it may create a file called the discard file. This file is created only when it is needed, and only if you have specified that a discard file should be enabled. The discard file contains records that were filtered out of the load because they did not match any record-selection criteria specified in the control file.

7/27/12

7979

SQL Loader : Invoke a CTL File

Go to the location where control file is saved in command prompt SQLLDR CONTROL=sample.ctl, LOG=sample.log, BAD=baz.bad, DATA=etc.dat USERID=scott/tiger@orcl, ERRORS=999, LOAD=2000, DISCARD=toss.dsc, DISCARDMAX=5 Parameter File: PARFILE specifies the name of a file that contains commonly used command-line parameters. For example, the command line could read: sqlldr PARFILE=example.par The parameter file could have the following contents: USERID=scott/tiger CONTROL=example.ctl ERRORS=9999 7/27/12 8080 LOG=example.log

SQL Loader CASES

CASE 1: Loading Variable Length data CASE 2: Loading Fixed Format Fields CASE 3: Loading a Delimited Free Format File CASE 4: Loading a Combined 7/27/12 8181

PACKAGES

A package is a schema object that groups logically related PL/SQL types, variables, and subprograms. Package has two parts in it

Package Specification

All Declarations

Package Body

Actual Code

Advantages

Better Performance Modularity


8282

7/27/12 Easier Application Design

Partition By Clause

Using partition by clause we can create a table with more than one partition.

Table can be truncated by partitions.

Note: This can also be done by a delete statement, but truncate statement is very efficient when compared to a delete statement.

Truncate statement requires no undo space as it cannot be rolled back, but for delete statement it has to save all the deleted data untill the session is commited, so it takes a lot of UNDO space. 7/27/12 8383

PRAGMA Autonomous Transaction

Autonomous Transaction: Autonomous transactions refer to the ability of PL/SQL temporarily suspend the current transaction and begin another transaction. The second transaction is known as an autonomous transaction. The autonomous transaction functions independently from the parent code. An autonomous transaction has the following characteristics:

The child code runs independently of its parent. The child code can commit or rollback and parent resumes. The parent code can continue without affecting child work.

We use a compiler directive in PL/SQL (called a pragma) to tell Oracle that our transaction is autonomous. An autonomous transaction executes within an autonomous scope. The PL/SQL compiler is instructed to mark a routine as autonomous (i.e. independent) by the AUTONMOUS_TRANSACTIONS pragma from the calling code.

7/27/12

8484

Dynamic Programming Execute Immediate

The EXECUTE IMMEDIATE statement executes a dynamic SQL statement or anonymous PL/SQL block. You can use it to issue SQL statements that cannot be represented directly in PL/SQL, or to build up statements where you do not know all the table names, WHERE clauses, and so on in advance. Syntax: EXECUTE IMMEDIATE sql_stmt

sql_stmt can have any SQL Query saved as a text in it.

All the DDL statements which cannot be executed in PLSQL block can now be executed using an EXECUTE IMMEDIATE statement. 7/27/12 8585

PL/SQL Tables Bulk Collect

PL/SQL tables are PL/SQLs way of providing arrays. Arrays are like temporary tables in memory and thus are processed very quickly. They are not database tables, and DML statements cannot be issued against them. Remember that PL/SQL tables exist in memory only, and therefore dont exist in any persistent way, disappearing after the session ends. A PL/SQL TABLE DECLARATION There are two steps in the declaration of a PL/SQL table. First, you must define the table structure using the TYPE statement. Second, once a table type is created, you then declare the actual table.

declare type type_name is table of table.col_name%type l_table 7/27/12 type_name 8686

Bulk Collect

Using bulk collect it is possible to select multiple rows in one go. We use bulk collect to load an array of values into a PL/SQL Tables Syntax:

SELECT col1 BULK COLLECT INTO l_plsql_table


7/27/12 8787

Performance Tuning

7/27/12

8888

Indexes

An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes. Syntax: CREATE [UNIQUE] INDEX index_name ON table_name (column1, column2, . column_n) [ COMPUTE STATISTICS ]; UNIQUE indicates that the combination of values in the indexed columns must be unique. COMPUTE STATISTICS tells Oracle to collect statistics during the creation of the index. The statistics are then used by the optimizer to choose a "plan of execution" when SQL statements are executed.
8989

7/27/12

Indexes

Below are the cases when a index is not used even though it has been created on a column

If we use (not equal to) <> operator

Use greater than or less than instead of not equal to.

If we use a function on the column If we use union query

Use a union all query


9090

7/27/12

Explain Plan

This statement displays the execution plan chosen by the oracle optimizer. Results of the explain plan include the following:

Order in which oracle will search the join tables Types of access employed (index search, full table scan) Names of the indexes used. Names of the predicates/filters used.

Before issuing explain plan, we need to create a table to hold its output, EG: PLAN_TABLE (UTXPLAN.SQL script to create the plan table) EXPLAN PLAN [SET statement_id = 'username]
7/27/12 9191

FOR SELECT STATEMENT;

Explain Plan

PLAN_TABLE will have results like operation, cost, optimizer, CPU_COST, IO_COST.

Explain plan results alone, however cannot differentiate between well tuned statements and those that perform poorly. For example if explain plan output shows that a statement uses an index, then this does not mean the statement runs efficiently.

7/27/12

9292

SQL Trace & TKProf

We can enable the SQL trace facility for a session or for an instance. When the SQL trace facility is enabled, performance statistics for all SQL statements executed in a user session or in the instance are placed into trace files.

Tkprof: The trace files generated by SQL_TRACE are not in the readable form.Tkprof is used to convert these files to human readable form.

TKPROF reports each statement executed with the resources it has consumed, the number of times it was called, the number of rows which it has processed. This information lets us easily locate the statements that are using the greatest resource. (call,count, CPU, elapsed are show in the file). 7/27/12 9393

SQL Trace & TKPROF

ALTER SESSION SET SQL_TRACE = true;

SELECT value from v$parameter where name = 'user_dump_dest' -- Gives the directory path where all the files are saved.

tkprof trace_filename.trc trace_filename.prf (.prf file can be opened using a notepad and is in human readable form).

7/27/12

9494

Hints

Hints let you make decisions usually made by the optimizer. As an application designer, you might know information about your data that the optimizer does not know. Hints provide a mechanism to instruct the optimizer to choose a certain query execution plan based on the specific criteria.
7/27/12 9595

Hints

For example, you might know that a certain index is more selective for certain queries. Based on this information, you might be able to choose a more efficient execution plan than the optimizer. In such a case, use hints to instruct the optimizer to use the optimal execution plan. Hints are used in select statements

SELECT /*+ HINT */ col1, col2 FROM TABLE_NAME;

Hints provide a mechanism to direct the optimizer to choose a certain query execution plan based on the following criteria:

Join order Join method 9696

7/27/12 Access path

Materialized Views

A materialized view is a stored summary containing precomputed results (originating from an SQL select statement).

As the data is precomputed, materialized views allow for (seemingly) faster dataware query answers.

Syntax: CREATE MATERIALIZED VIEW <name> REFRESH <refresh option> <refresh mode> AS SELECT <select clause>;

7/27/12

9797

Materialized View Refresh Option

REFRESH OPTION: - COMPLETE totally refreshes the view Can be done at any time; can be time consuming

- FAST incrementally applies data changes A materialized view log is required on each detail table Data changes are recorded in MV logs or direct loader logs Many other requirements must be met for fast refreshes

- FORCE does a FAST refresh in favor of a COMPLETE


7/27/12is the default refresh option This 9898

Materialized View Refresh Mode

REFRESH MODE: ON COMMIT refreshes occur whenever a commit is performed on one of the views underlying detail table(s)

Available only with single table aggregate or join based views Keeps view data transactionally accurate Need to check alert log for view creation errors

ON DEMAND refreshes are initiated manually using one of the procedures in the DBMS_MVIEW package

Can be used with all types of materialized views Manual Refresh Procedures DBMS_MVIEW.REFRESH(<mv_name>, <refresh_option>) DBMS_MVIEW.REFRESH_ALL_MVIEWS()

7/27/12

9999

You might also like