You are on page 1of 36

PL/SQL Training Presentation

A database can be a set of flat files stored on computer tape or disk or it could consist of database tables that are managed by a Database Management System (DBMS).

There are different types of DBMS products: relational, network and hierarchical. The most widely commonly used type of DBMS today is the Relational Database Management Systems (RDBMS).

Some Data Base Management Systems can be accessed directly using programming languages such as COBOL while others provide their own programming language for interacting with the database. Many DBMS applications also provide reporting and query tools to view data in the database.

Commercial Databases

Oracle IBM DB 2 Microsoft SQL Server Ingres. The first commercial RDBMS.

Free/Open Source Databases

MySQL PostgresSQL

SQL is the structured query language. T-Sql is a development environment for creating stored procedures. Every environment needs a way to create batches of SQL statements. Microsoft provides it in the form of T-Sql. Note some commands in T-Sql such as Begin, End, Looping constructs, and others
What is the difference between SQL and T-SQL? Why would a company use one over the other?

ANSI SQL is the standard Structured Query Language. Most database vendors support SQL. TSQL is Microsoft's "flavor" of SQL; it is ANSI SQL with Microsoft's extensions. A company could choose to use T-SQL over SQL if they have a database application that communicates with a MS SQL Server database only. Therefore a developer could use the "extras" for improved performance, ease of SQL coding, etc. A company could chose SQL because a front-end may have to communicate with several relational database management systems (RDBMs) therefore a programmer could rely on the fact that most database understand ANSI SQL.

Transact-SQL (T-SQL) is Microsoft's and Sybase's proprietary extension to SQL. Transact-SQL is central to using SQL Server. All applications that communicate with an instance of SQL Server do so by sending Transact-SQL statements to the server, regardless of the user interface of the application. Transact-SQL augments SQL with certain additional features: Control-of-flow language Local variables Various support functions for string processing, date processing, mathematics, etc. Changes to DELETE and UPDATE statements TSQL can be used for much more than just creating stored procedures. TSQL is Microsofts implementation of the SQL language. It has Data Definition Language, looping and decision constructs, etc. all of which are ANSI specified. In addition it supports ANSI specifications for features such as schema exposure separating the user from the base table storage so that schema queries will work in both SQL Server and other ANSI compliant databases. You will see this capability demonstrated in the INFORMATION_SCHEMA views. So what is not ANSI compliant or transportable. Perhaps items such as User Defined Functions or Table Variables. If you don t use these kinds of features in your TSQL code it will be transporable and thus ANSI compliant. TSQL and PL/SQL are supersets of the ANSI standards. To what version for ANSI Standard they comply depends on the version of the product. This is true of almost any database engine including others such as Sybase, Sybase SQL Anywhere, MySQL, Posgres SQL, RBASE, Informix .

A database product saying its RDBMS it means it uses SQL as a language and data inside it is written always in table form i.e. rows/records & columns/fields. Moreover there may or may not be relationship in-between those tables SQL is nothing but a set of commands/statements and are categorized into following five groups viz., DQL: Data Query Language, DML: Data Manipulation Language, DDL: Data Definition Language, TCL: Transaction Control Language, DCL: Data Control Language. DQL: SELECT DML: DELETE, INSERT, UPDATE DDL: CREATE, DROP, TRUNCATE, ALTER TCL: COMMIT, ROLLBACK, SAVEPOINT DCL: GRANT, REVOKE

A View in Oracle and in other database systems is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. For example, if we frequently issue the following query Benefits of using Views Commonality of code being used. Since a view is based on one common set of SQL, this means that when it is called it s less likely to require parsing. Security. Views have long been used to hide the tables that actually contain the data you are querying. Also, views can be used to restrict the columns that a given user has access to.

CREATE VIEW view_uscustomers AS SELECT customerid, customername FROM customers WHERE countryid='US';

A materialized view is a database object that contains the results of a query. They are local copies of data located remotely, or are used to create summary tables based on aggregations of a table's data. Materialized views, which store data based on remote tables are also, know as snapshots

PL/SQL (Procedural Language/Structured Query Language) . pl/sql is the procedural implementation of sql i.e. u can pass sql statements in procedural format using pl/sql PL/SQL supports variables, conditions, loops , exceptions and arrays The basic PL/SQL code structure is : DECLARE -- optional, which declares and define variables, cursors and user-defined exceptions. BEGIN -- mandatory - SQL statements - PL/SQL statements EXCEPTION -- optional, which specifies what actions to take when error occurs. END; -- mandatory DECLARE TYPE / item / FUNCTION / PROCEDURE declarations BEGIN Statements EXCEPTION EXCEPTION handlers END label;

Step 1 Define the type of block (procedure, function, anonymous) and the way it is called (header). Step 2 Declare any variables used in that block (declaration section). Step 3 Use those local variables and other PL/SQL objects to perform the required actions (execution section). Step 4 Handle any problems that arise during the execution of the block (exception section).

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. CREATE [UNIQUE] INDEX index_name ON table_name (column1, column2, . column_n) [ COMPUTE STATISTICS ]; CREATE INDEX supplier_idx ON supplier (supplier_name, city);

Sequence Sequence are nothing but which Automatically generates unique numbers Is a sharable object Is typically used to create a primary key value Replaces application code Speeds up the efficiency of accessing sequencevalues when cached in memory

CREATE SEQUENCE <SEQUENCENAME> START WITH <INT> MIN VALUE/NOMINVALUE<INT> MAXVALUE/NOMAXVALUE<INT> INCREMENT BY CYCLE/NOCYCLE CACHE/NOCACHE; EX:CREATE SEQUENCE SEQ1 INCREMENT BY 1 START WITH 1 MINVALUE 0 NOCYCLE NOCACHE NOORDER;

What is a primary key? A primary key is a single field or combination of fields that uniquely defines a record. None of the fields that are part of the primary key can contain a null value. A table can have only one primary key.
CREATE TABLE supplier ( supplier_id supplier_name contact_name ); numeric(10) varchar2(50) varchar2(50), not null, not null,

CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name)

ALTER TABLE supplier add CONSTRAINT supplier_pk PRIMARY KEY (supplier_id, supplier_name); What is a foreign key? A foreign key means that values in one table must also appear in another table. The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table. A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement

CREATE TABLE products ( product_id supplier_id numeric(10) numeric(10) not null, not null,

CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id) );

ALTER TABLE products add CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES supplier(supplier_id);

What are Oracle Constraints?


Oracle constraints are means in the process of defining some conditions about the database that must remain true while inputting/modifying/deleting data in the database. Constraints are used to enforce table rules and prevent data dependent deletion (enforce database integrity). You may also use them to enforce business rules (with some magination). These Oracle constraints can be attribute-based (column), tuple-based (table), key based and referential integrity based. As Oracle views are always dynamically generated from their base tables, so the view can not contain constraints. If there is a violation of the constraints caused by some actions performed on the database, then the Oracle constraints aborts the action accordingly. The Oracle implementation of constraints differs from the SQL implementation of these constraints.

CREATE TABLE STUDENT ( STUDENT _ID NUMBER(3) CONSTRAINT S_ID CHECK (STUDENT _ID > 0), STUDENT _NAME CHAR(30) CONSTRAINT S_NAME NOT NULL, MARKS_COUNT NUMBER(6), CONSTRAINT STUDENT _PRIME PRIMARY KEY (STUDENT _ID))

Identifiers
An identifier is a name for a PL/SQL object, including any of the following: Constant Variable Exception Procedure Function Package Record PL/SQL table Cursor Reserved word

PL/SQL Constants
As the name implies a constant is a value used in a PL/SQL Block that remains unchanged throughout the program. A constant is a user-defined literal value.

DECLARE salary_increase CONSTANT number(3); BEGIN salary_increase := 100; dbms_output.put_line (salary_increase); END;

MOST IMPORTANT: HOW TO DISPLAY MESSAGES ON SCREEN DBMS_OUTPUT : is a package that includes a number of procedure and functions that accumulate information in a buffer so that it can be retrieved later. These functions can also be used to display messages to the user. PUT_LINE : Put a piece of information in the package buffer followed by an end-of-line marker. It can also be used to display message to the user. Put_line expects a single parameter of character data type. If used to display a message, it is the message string. EG: dbms_output.put_line(x);

Handling Variables The PL/SQL variables can be a scalar type such as DATE, NUMBER, VARCHAR(2), DATE, BOOLEAN, LONG and CHAR, or a composite type, such array type VARRAY. DECLARE TYPE v_arr IS VARRAY(25) of NUMBER(3); v1 v_arr; v_empno employee.empno%TYPE; variable_name DATE := '01-Jan-2005'; BEGIN v1(2) := 3; DBMS_OUTPUT.PUT_LINE('The Value of v1(2) = ' || v1(2)); v_empno := 4; END;

Coding Guidelines Single-line comments are prefixed with two dashes --. Multiple-line comments can be enclosed with the symbols /* and */. Variables and function identifiers can contain up to 30 characters, and should not have the same name as a database column name. Identifiers must begin with an alphanumerical character. SQL functions can be used in PL/SQL.

SQL Aggregate Functions SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions: AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum SQL Scalar functions SQL scalar functions return a single value, based on the input value. Useful scalar functions: UCASE() - Converts a field to upper case LCASE() - Converts a field to lower case MID() - Extract characters from a text field LEN() - Returns the length of a text field ROUND() - Rounds a numeric field to the number of decimals specified NOW() - Returns the current system date and time FORMAT() - Formats how a field is to be displayed

SQL Statements in PL/SQL The following code block shows how to run DML statements in PL/SQL. Basically they look similar to the SQL. Note that the SELECT statement retrieves the single-row value and store into a variable using INTO clause. DECLARE v_sal employee.sal%TYPE; BEGIN INSERT INTO employee VALUES (6, 'TOM LEE', 10000); UPDATE employee SET sal = sal + 5000 WHERE empno = 6; SELECT sal INTO v_sal FROM employee WHERE empno = 6; DBMS_OUTPUT.PUT_LINE('Salary increased to ' || v_sal); DELETE FROM employee WHERE empno = 6; COMMIT; SELECT END; INSERT UPDATE DELETE SELECT FROM WHERE AND OR GROUP BY HAVING AND OR ORDER BY INSERT INTO VALUES INSERT INTO SELECT FROM WHERE UPDATE SET WHERE DELETE FROM WHERE

Control Structures Conditions checking IF <condition> THEN [ELSIF <condition> THEN] [ELSE <condition> THEN] END IF; Basic loops. LOOP ... EXIT WHEN <condition> END LOOP; FOR loop. FOR counter IN lower_bound .. upper_bound ... END LOOP; WHILE loop. WHILE <condition> LOOP ... END LOOP;

IF x = 1 THEN sequence_of_statements_1; ELSIF x = 2 THEN sequence_of_statements_2; ELSIF x = 3 THEN sequence_of_statements_3; ELSIF x = 4 THEN sequence_of_statements_4; ELSIF x = 5 THEN sequence_of_statements_5; ELSE sequence_of_statements_N; END IF; The CASE statement simplifies some large IF-THEN-ELSE structures. CASE WHEN x = 1 THEN sequence_of_statements_1; WHEN x = 2 THEN sequence_of_statements_2; WHEN x = 3 THEN sequence_of_statements_3; WHEN x = 4 THEN sequence_of_statements_4; WHEN x = 5 THEN sequence_of_statements_5; ELSE sequence_of_statements_N; END CASE;

CASE statement can be used with predefined selector: CASE x WHEN 1 THEN sequence_of_statements_1; WHEN 2 THEN sequence_of_statements_2; WHEN 3 THEN sequence_of_statements_3; WHEN 4 THEN sequence_of_statements_4; WHEN 5 THEN sequence_of_statements_5; ELSE sequence_of_statements_N; END CASE;

FOR for_index IN low_value .. high_value LOOP executable_statements; END LOOP; FOR record_index IN my_cursor LOOP executable_statements; END LOOP;

SQL Cursor
A SQL cursor is a private Oracle SQL working area. There are two types of SQL cursor: implicit or explicit cursor. The implicit cursor is used by Oracle server to test and parse the SQL statements and the explicit cursors are declared by the programmers. Using the implicit cursor, we can test the outcome of SQL statements in PL/SQL. For example, SQL%ROWCOUNT, return the number of rows affected; SQL%FOUND, a BOOLEAN attribute indicating whether the recent SQL statement matches to any row; SQL%NOTFOUND, a BOOLEAN attribute indicating whether the recent SQL statement does not match to any row; SQL%ISOPEN, a BOOLEAN attribute and always evaluated as FALSE immediately after the SQL statement is executed. To write the explicit cursor, please refer to the following example. Note that a cursor definition can array a number of arguments. For example, DECLARE CURSOR csr_ac (p_name VARCHAR2) IS SELECT empno, name, sal FROM employee WHERE name LIKE '%p_name%'; BEGIN FOR rec_ac IN csr_ac ('LE') LOOP

DBMS_OUTPUT.PUT_LINE(rec_ac.empno || ' ' ||rec_ac.name || ' '||v_sal); END LOOP ; CLOSE csr_ac; END; Writing PL/SQL Procedures/Functions PL/SQL functions returns a scalar value and PL/SQL procedures return nothing. Both can take zero or more number of parameters as input or output. The special feature about PL/SQL is that a procedure/function argument can be of input (indicating the argument is read-only), output (indicating the argument is write-only) or both (both readable and writable). For example, the following is a PL/SQL procedure and a function. PROCEDURE hire_employee (emp_id INTEGER, name VARCHAR2) IS BEGIN INSERT INTO employee VALUES (emp_id, name, 1000); END hire_employee; FUNCTION sal_ok (salary REAL, title REAL) RETURN BOOLEAN IS min_sal REAL; max_sal REAL; BEGIN SELECT losal, hisal INTO min_sal, max_sal FROM sals WHERE job = title;

RETURN (salary >= min_sal) AND (salary <= max_sal); END sal_ok; A function is called as part of an expression. For example, the function sal_ok might be called as follows: IF sal_ok(new_sal, new_title) THEN ...

Writing and Compiling PL/SQL Packages. A package is a database object that groups logically related PL/SQL types, objects, and subprograms. Packages usually have two parts, a specification and a body, although sometimes the body is unnecessary. The specification is the interface to your applications; it declares the types, variables, constants, exceptions, cursors, and subprograms available for use. The body fully defines cursors and subprograms, and so implements the specification. Unlike subprograms, packages cannot be called, parameterized, or nested. Still, the format of a package is similar to that of a subprogram: CREATE PACKAGE name AS -- specification (visible part) -- public type and object declarations -- subprogram specifications END [name];

CREATE PACKAGE BODY name AS -- body (hidden part) -- private type and object declarations -- subprogram bodies [BEGIN -- initialization statements] END [name];

Parametric cursor PL/SQL also allows you to pass parameters into cursors. It eases your work because: - A parameter makes the cursor more reusable. - A parameter avoids scoping problems. However, you should pass parameters when you are going to use it at more then one place and when there are going to be different values for the same WHERE statement.
CURSOR cursor2(cust_no) IS SELECT b.trans_id, b,b.trans_item FROM trans b WHERE b.id = cust_no. What is an Index? Index in oracle helps to trace the information faster just like an index in a book. Index entries keep What is composite index? A composite index contains more than one key column

Bitmapped indexes and B-tree index In a Bitmap index, a 2 dimensional array is created. The array represents the index value

multiplied by number of rows. One column is allotted for every row in the table being indexed. When a row is retrieved, the bitmap is decompressed into the RAM data buffer to rapidly scan for matching values. Each matching value is returned as a ROW ID which can be used to access the desired information.
B-tree indexes are usually created on columns containing the most unique values. It is

an ordered set of entries in which each entry a search key value and and a pointer to a specifc row with that value. When a server finds a search key value matching a constraint, the pointer is used to fetch the row.
bitmap indexes are most appropriate for columns having low distinct values such as GENDER, MARITAL_STATUS, and RELATION

To illustrate this point, I created two tables, TEST_NORMAL and TEST_RANDOM. I inserted one million rows into the TEST_NORMAL table using a PL/SQL block, and then inserted these rows into the TEST_RANDOM table in random order: SQL> select count(*) "Total Rows" from test_normal; Total Rows ---------- 1000000 Elapsed: 00:00:01.09

SQL> select count(distinct empno) "Distinct Values" from test_normal; Distinct Values --------------- 1000000 Elapsed: 00:00:06.09

SQL> select count(*) "Total Rows" from test_random; Total Rows ---------- 1000000 Elapsed: 00:00:03.05

SQL> select count(distinct empno) "Distinct Values" from test_random; Distinct Values --------------1000000 Elapsed: 00:00:12.07 The TEST_NORMAL table is organized and that the TEST_RANDOM table is randomly created and hence has disorganized data The column EMPNO has 100-percent distinct values and is a good candidate to become a primary key. If you define this column as a primary key, you will create a B-tree index and not a bitmap index because Oracle does not support bitmap primary key indexes.

SQL> create bitmap index normal_empno_bmx on test_normal(empno); Index created. Elapsed: 00:00:29.06 SQL> analyze table test_normal compute statistics for table for all indexes for all indexed columns; B-tree index

SQL> create index normal_empno_idx on test_normal(empno); ndex created. SQL> analyze table test_normal compute statistics for table for all indexes for all indexed columns;

Oracle's explain plan


Whenever you read or write data in Oracle, you do so by issuing an SQL statement. One of Oracle's task when it receives such a statement is to build a query execution plan. Oracle's Query Execution Plan

Whenever an SQL statement is executed, Oracle designs an execution plan for it. This execution plan is basically a step by step instruction for how the statement must be executed. That is, the order in which tables are read, if indexes are used, which join methods are used to join tables and so on. The execution plan for an SQL statement can be viewed with the explain plan statement. The query execution plan is elaborated during an SQL statement's parse phase.

An SQL statement must always be parsed. Then, it can be executed any number of times. If it is a select statement, the result-data needs be fetched for each execution.

Parse
One of the goals of the parse phase is to generate a query execution plan (QEP).

Syntax
This step checks if the syntax of the statement is correct. For example, a statement like

select foo frm bar is syntactically not correct (frm instead of from).

Semantic
A statement might be invalid even if the syntax is correct. For example select foo from bar is invalid if there is no table or view named bar,

or if there is such a table, but without a column named foo.


Also, the table might exist, but the user trying to execute the query does not have the necessary object privileges. If the statement is syntactically and semantically correct, it is placed into the library cache (which is part of the Shared Pool). View merging

If the query contains views, the query might be rewritten to join the view's base tables instead of the views.

Statement Transformation Transforms complex statements into simpler ones through subquery unnesting or in/or transformations The EXPLAIN PLAN statement runs very quickly, even if the statement being explained is a query that might run for hours. This is because the statement is simply parsed and its execution plan saved into the plan table.

Running queries through EXPLAIN PLAN will let you determine in advance if the queries are feasible or if they will be resource intensive and will take unacceptably long to run.

explain plan for select departments.department_id,department_name,avg(salary) as s,count(employee_id) as cnt from departments,employees where employees.department_id=DEPARTMENTS.DEPARTMENT_ID group by departments.department_id,department_name,salary,employee_id ;

Some of General SQL Exercises


Select statement exercises Enter select statements to: 1.Display the first name and age for everyone that's in the table. 2.Display the first name, last name, and city for everyone that's not from Payson. 3.Display all columns for everyone that is over 40 years old. 4.Display the first and last names for everyone whose last name ends in an "ay". 5.Display all columns for everyone whose first name equals "Mary". 6.Display all columns for everyone whose first name contains "Mary". Selecting Data Answers: Display everyone's first name and their age for everyone that's in table. select first, age from empinfo; Display the first name, last name, and city for everyone that's not from Payson. select first, last, city from empinfowhere city <> 'Payson'; Display all columns for everyone that is over 40 years old. select * from empinfo where age > 40; Display the first and last names for everyone whose last name ends in an "ay". select first, last from empinfo where last LIKE '%ay'; Display all columns for everyone whose first name equals "Mary". select * from empinfo where first = 'Mary'; Display all columns for everyone whose first name contains "Mary". select * from empinfo where first LIKE '%Mary%';

Creating Tables The create table statement is used to create a new table. Here is the format of a simple create table statement: create table "tablename"("column1" "data type", "column2" "data type", "column3" "data type"); Format of create table if you were to use optional constraints: create table "tablename"("column1" "data type" [constraint], "column2" "data type" [constraint], "column3" "data type" [constraint]); [ ] = optional Note: You may have as many columns as you'd like, and the constraints are optional. Example: create table employee(first varchar(15), last varchar(20), age number(3), address varchar(30), city varchar(20), state varchar(20));