P. 1
1 Rdbms SQL Pl SQL

1 Rdbms SQL Pl SQL

|Views: 59|Likes:
Published by jagdaleomkar5

More info:

Published by: jagdaleomkar5 on May 31, 2011
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PPT, PDF, TXT or read online from Scribd
See more
See less





Introduction to Oracle as a RDBMS

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

Copyright Infogain Corporation, 2007


Entity 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.


Copyright Infogain Corporation, 2007


Introduction to SQL .

and Deleting rows in a table ‡ Creating. Replacing. contains set of commands which provide an access to a relational database such as Oracle SQL statements are instructions to the database.SQL ” Structured Query Language (SQL). The strengths of SQL benefit all types of users. database administrators. 2007 . Altering. management. Updating. SQL provides statements for a variety of tasks. and Dropping objects ‡ Controlling access to the database and its objects -5- ” ” ” ” Copyright Infogain Corporation. including: Querying data ‡ Inserting. and end users. including application programmers.

«} From table [Where condition's)] [Order By asc/desc ]. ” Copyright Infogain Corporation.A Simple Select Statement Select *| { (Distinct) column | expression [alias]. 2007 -6- . Select *| { (Distinct) column | expression [alias]. «} ” From table ” [Where condition (s)] ” [Order By asc/desc ].

<>. IS NULL. not between. <=. <>. !=. !=. µ%tin%¶ ” Arithmetic operators: ± +. not in. IN. >.OR NOT. LIKE. 2007 -7- . OR ‡ Logical operators: ± Copyright Infogain Corporation. /. =. BETWEEN. ^=. >=. -. >=. in. AND. *. <. >. like. <=.Operators Used in Where Clause ” There are three types of Operators: ‡ Common operators: ± =. <. AND.

and CONNECT BY clauses There are four types of Single Row function: ‡ Arithmetic Functions ‡ Character Functions ‡ Date Functions ‡ General Functions ” ” Copyright Infogain Corporation. 2007 -8- . START WITH clauses.Single 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.

where e = 2. 2007 -9- .. n is rounded to 0 places.Arithmetic Functions (cont. EXP returns e raised to the nth power. If m is omitted. ‡ SELECT EXP(4) FROM DUAL.) ” ROUND returns n rounded to m places right of the decimal point. m can be negative to round off digits left of the decimal point..1) FROM DUAL. m must be an integer. ” Copyright Infogain Corporation. ‡ SELECT ROUND(15.71828183 .193.

‡ SELECT CHR(67) a. LOWER returns char. ‡ SELECT LOWER('MR. SCOTT MCMILLAN') FROM DUAL.10 - . ” ” Copyright Infogain Corporation. with all letters uppercase. with all letters lowercase. ‡ SELECT UPPER('Large') FROM DUAL. 2007 .CHR(65) b. UPPER returns char.CHR(84) c FROM DUAL.Character Functions ” CHR returns the character having the binary equivalent to n in either the database character set or the national character set.

‡ SELECT TO_CHAR( ADD_MONTHS( line_status_date. d is rounded to the nearest day.Date Functions ” SYSDATE returns the current date and time.'DDMM_YYYY') FROM line_item_master WHERE order_number = 'ORD000101µ ROUND returns d rounded to the unit specified by the format model fmt.'YEAR') FROM DUAL.1).11 - . Returns a date as result. ‡ SELECT ROUND (TO_DATE ('27-OCT-92'). 2007 . ” ” Copyright Infogain Corporation. ADD_MONTHS adds or subtracts months to or from a date. If you omit fmt. ‡ SELECT sysdate FROM DUAL.

. NEXT_DAY returns the date of next specified day of the week after the µdate¶. 2007 . ‡ SELECT SYSDATE. result is positive.12 - ” ” Copyright Infogain Corporation. ‡ SELECT MONTHS_BETWEEN (TO_DATE('02-02-1995'. LAST_DAY(SYSDATE) SYSDATE FROM DUAL. You might use this function to determine how many days are left in the current month. If d1 is later than d2. TO_DATE('01-01-1995'. negative.Date Functions (cont.'TUESDAY') FROM DUAL. if earlier. LAST_DAY(SYSDATE).'MM-DD-YYYY') ) FROM DUAL.) ” MONTHS_BETWEEN returns number of months between dates d1 and d2. ‡ SELECT NEXT_DAY('15-MAR-98'.'MM-DDYYYY'). LAST_DAY returns the date of the last day of the month that contains d.

If no format is specified the default format is DD-MM-YY.Date Functions (cont. ‡ SELECT TRUNC(TO_DATE('27-OCT-92'. ” ” Copyright Infogain Corporation. TO_CHAR converts the date µd¶ to character format µf¶. ‡ SELECT TO_CHAR(TO_DATE('20-MAR-98').13 - .) ” TRUNC returns d with the time portion of the day truncated to the unit specified by the format model fmt.'DD-MON-YY'). TO_DATE converts the character string representing date into a date format according to µf¶ format specified. ‡ SELECT sysdate.'RM') FROM DUAL.'DAY')FROM DUAL. 'YEAR') FROM DUAL. d is truncated to the nearest day. TO_CHAR(sysdate. 2007 . If you omit fmt.

Conversion Functions Data-Type Conversion Implicit data-type Conversion Explicit data-type Conversion Copyright Infogain Corporation. 2007 .14 - .

2007 .Implicit Data-Type Conversion From To VARCHAR2 OR CHAR VARCHAR2 or CHAR NUMBER DATE NUMBER DATE VARCHAR2 VARCHAR2 Copyright Infogain Corporation.15 - .

2007 .Type Conversion TO_NUMBER TO_DATE NUMBER CHARACTER DATE TO_CHAR TO_CHAR Copyright Infogain Corporation.Explicit Data .16 - .

Group Functions ” Type of group functions ‡ AVG ‡ COUNT ‡ MIN ‡ MAX ‡ SUM ‡ VARIANCE ‡ STDDEV Copyright Infogain Corporation. 2007 .17 - .

as opposed to single row functions.) ” Group functions are those statistical functions which gives information about a group of value taken as whole Group functions return based on many rows. These functions are valid in the select list of a query and the GROUP BY clause only.18 - . 2007 .Group Functions (cont. ” ” ” Copyright Infogain Corporation. which return one result for each row. For example COUNT group function returns no of rows returned.

Self Joins. Types of Joins: Equi Joins. Outer Joins.19 - . Non Equi Joins. Joins are used to combine columns from different tables. the information from any number of tables can be accessed. With joins. The connection between tables is established through the WHERE clause. all within a single command. 2007 . ” ” ” ” Copyright Infogain Corporation.JOINS ” 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.

cz.customer_id.20 - .. 2007 . ” ” ” Copyright Infogain Corporation. it checks for the equality of values in these columns.party_id.e. In this case in WHERE condition we use (=) operator.price_list_id. It combines rows that have equivalent values of a specified columns.customer_name. ra_customer ra where cz. Here.ra. joining the customer_id of cz_imp_customer and ra_customer. Here.Equi Joins ” When two tables are joined together using equality of values in one or more columns. the WHERE clause defines the joining condition i.customer_id = ra. ‡ ra. they make an Equi Join.customer_name from cz_imp_customer cz. Example: ‡ Select cz.

Cartesian Product ” When no join condition clause is specified in WHERE clause. 2007 .cz. ra_customer ra. ‡ ra. each row of one table matches every row of the other table.price_list_id.party_id. ” Copyright Infogain Corporation.21 - . ‡ Select cz.customer_name from cz_imp_customer cz. This results in a Cartesian Product.customer_name.ra.

” Copyright Infogain Corporation. ra_customer ra ‡ Where cz.customer_id. ‡ Select cz.cz.party_id. 2007 .customer_id(+)=ra.customer_name ‡ From cz_imp_customer cz.customer_name.ra.22 - .Outer Joins ” It extends the result of simple joins.ra. It retrieve records from another table that do not have a matching record in addition to one¶s having matching records.price_list_id.

Data type of corresponding columns must be the same.Set Operators ” SET Operators are used to combine information of similar type from one or more than one table. So Set operators combine two or more queries into one result.23 - . 2007 . The types of SET operators in ORACLE are: ‡ UNION ‡ INTERSECT ‡ MINUS ” ” ” Copyright Infogain Corporation.

. 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.Sub queries ” Sub queries allow a developer to build powerful commands out of simple ones.24 - ” ” ” ” Copyright Infogain Corporation. 2007 . A sub query is a SELECT statement that is nested within another SELECT statement and which returns intermediate results. The inner query generates values that are tested in the predict of the outer query determining when it will be true. SQL first evaluates the inner query (sub query) with in WHERE clause.

‡ 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 ” ” Copyright Infogain Corporation. ‡ Place sub queries on the right side of the comparison operator.25 - . 2007 .Types 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.

SQL * Plus prompts for the value of the variable. ” ” ” Copyright Infogain Corporation.Substitution 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. accepts it and then substitutes it in the variable. 2007 .26 - .

2007 . ‡ 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 ” ” Copyright Infogain Corporation.Defining Substitution Variables ” Predefine a variable using the DEFINE command.27 - .

Producing Readable Output with SQL*Plus .

Example ‡ sql>SET ECHO ON ‡ sql>SHOW ECHO ‡ sql>echo ON ” ” Copyright Infogain Corporation.29 - .Customizing the SQL*Plus Environment ” SET commands can be used to control current session. 2007 . ‡ SET {variable} {value} Use SHOW command to verify what value you have set for a variable.

2007 .30 - .SQL*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 Copyright Infogain Corporation.

2007 .31 - .) ” 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¶ ” Copyright Infogain Corporation.SQL*Plus Format Commands (cont.

” set feedback on ” clear break ” column customer_id clear ” column customer_name clear ” column creation_date clear ” Copyright Infogain Corporation.32 - .creation_date from ra_customers ” order by customer_id.Example 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. 2007 .customer_name.

33 - . 2007 .SQL Environment PL/SQL engine PL/SQL block PL/SQL PL/SQL block SQL Procedural Statement Executor SQL Statement Executor Oracle8 Server Copyright Infogain Corporation.

34 - . 2007 Data retrieval Data manipulation language (DML) Data definition language (DDL) Transaction control Data Control language (DCL) .SQL Statements SELECT INSERT UPDATE DELETE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT GRANT REVOKE Copyright Infogain Corporation.

DDL Statements .SQL DML.

DML ± Insert.36 - . Update. ‡ UPDATE: Update is used to change data in a table. The most common SQL statements are insert. ‡ INSERT: Insert is used to add rows of data to a table. ‡ DELETE: Delete is used to delete rows of data from a table. Delete ” DML statements are SQL commands that allow you to manipulate the data in the database. 2007 . This statements allow you to work with the contents of the database. ” ” Copyright Infogain Corporation. update and delete.

values can also be given through a query. parameter substitution can also be used with INSERT The syntax for INSERT command is: ‡ INSERT INTO < table-name > VALUES ( < list-of-values>). ” ” ” ” Copyright Infogain Corporation. Values can be inserted for all the columns or for the selected columns To the INSERT INTO command. however.37 - . 2007 .Insert ” INSERT command is used to insert rows in the table. the columns of the table being inserted must match the columns output by the sub query In place of values.

µHendry'.Examples ” To insert values for all columns following command is used: ‡ Insert into customer_data ‡ VALUES (1.COUNTRY) ‡ Values (2.'qwerty'. 2007 .'india').µRonaldo¶.USERNAME.STATE.38 - .'india'). ” Copyright Infogain Corporation.'Gujrat'.µDelhi'. To insert only the selected columns the following command is used: ‡ Insert into customer_data ‡ (ID.

««] [WHERE < condition >] ” Copyright Infogain Corporation. 2007 .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 > ” [.39 - .column-name = value.

40 - . 2007 . 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.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. ” Copyright Infogain Corporation.

41 - . ‡ Alter Adds a column. ‡ Create Creates a table. Alter. Rollback DDL is the subset of SQL commands used to create. changes storage allocation. ‡ Rollback Undo all the changes or all the work the user has done In the current transaction. and also record information in the Data dictionary. redefines a column. 2007 . ” Copyright Infogain Corporation. modify or remove Oracle database structures.DDL ± Create. ” These commands have an immediate effect on the database.

2007 .42 - ” ” ” ” ” Copyright Infogain Corporation.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) >. . «««.) .

changes their data types and can also add or delete constrains.element > | < constraints > «. ALTER TABLE command adds column to the table or change their sizes.element > « ] ‡ [ drop < options > ] ..43 - .Alter ” To change the definition of a table ALTER TABLE command is used.] ‡ [ modify < column. ” Copyright Infogain Corporation. ” The syntax for ALTER table command is: ” Alter table < table-name > ‡ [ add ( < column. 2007 .

updates. deletes) permanently and save the data permanently.Transaction processing ± Commit. Commit is used to make changes to data (inserts. 2007 .44 - . Rollback is used to discard parts or all the work the user has done in the current transaction. Commit and Rollback are Transaction Processing languages. All changes made to the database can be referred as a Transaction. ” ” ” Copyright Infogain Corporation. Rollback ” Transaction is a logical unit of work.

DDL Statements .SQL DML.

46 - .View 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 ” ” ” ” Copyright Infogain Corporation. 2007 .

: One view to provide a detailed look at rows.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. 2007 .g. others to present summaries with grouping in various ways Copyright Infogain Corporation.47 - .

and re-grant privileges Sub query ‡ A complete SELECT statement ‡ Can use aliases for the columns ‡ Can involve multiple tables ” Copyright Infogain Corporation.Creating 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. 2007 .48 - . recreate it.

ra_customer ra where cz.View Example #1 ” Create a Read Only View Create or replace view customer_view as select cz.49 - .ra.customer_id with read only.customer_id = ra.party_id.price_list_id. Copyright Infogain Corporation. 2007 . ” Use the View SQL> desc customer_view SQL> select * from customer_view.customer_name from cz_imp_customer cz. ra.

” Use the View SQL> select * from customer_check SQL> update customer_check set salary = 20000 where id = 1. 2007 .View Example #2 ” Create a View SQL> create or replace view customer_check as select * from customer_data where salary=10000 WITH CHECK OPTION. update customer_check * ERROR at line 1: ORA-01402: view WITH CHECK OPTION where-clause violation Copyright Infogain Corporation.50 - .

51 - . 2007 . 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.DML Using Views ” For DML. the table¶s constraints must be satisfied as well ” Copyright Infogain Corporation.

” ” Modifying a View ‡ Views can¶t be modified ‡ Use CREATE OR REPLACE to redefine it Copyright Infogain Corporation.Dropping and Modifying Views ” 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 DROP VIEW <viewname>.52 - . 2007 .

2007 .Index 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 .53 - ” ” Copyright Infogain Corporation.

: Index fields that frequently appear in WHERE clauses to speed retrieval ” Copyright Infogain Corporation.g.: Index foreign key fields to speed joins ‡ E.g. 2007 .When are Indexes Created? ” 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.54 - .

. SQL> CREATE INDEX customer_id_idx ON ra_customer(customer_id). 2007 . Copyright Infogain Corporation. column]. Index created.).55 - ..Creating an Index ” You must have CREATE INDEX privilege CREATE [BITMAP] INDEX index ON table (column[.

.Creating a Composite Index ” Up to 32 columns per index CREATE INDEX index ON table (column[..56 - . SQL> CREATE INDEX customer_composite_idx ON customer_data(id. 2007 . username). column].). Index created. ” What is the leading column of this index? What WHERE clauses could benefit from this index? ” Copyright Infogain Corporation.

57 - .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 ” ” ” ” Copyright Infogain Corporation. 2007 .When to Create an Index ” The column is used frequently in the WHERE clause or in a join condition ‡ E.

2007 .When 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! ” ” ” Copyright Infogain Corporation.58 - .

” ” Copyright Infogain Corporation.59 - .Removing 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. Index dropped. Oracle automatically drops all of the table¶s indexes DROP INDEX indexname. SQL> DROP INDEX customer_composite_idx. 2007 .

2007 .Sequence 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 ” ” ” Copyright Infogain Corporation.60 - .

61 - .Creating a Sequence ” The following was in the CreateIssue25 script CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}]. 2007 . Copyright Infogain Corporation. SQL> CREATE SEQUENCE customer_seq INCREMENT BY 1 START WITH 1 NOCACHE.

NEXTVAL 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

Copyright Infogain Corporation, 2007

- 62 -

Using a Sequence

Sequences are generally used in INSERT and UPDATE statements e.g.:
SQL> INSERT INTO customer_data VALUES (customer_seq.NEXTVAL, 'Scott','tiger', 'Mahatastra',¶India¶,10000);


What customer_id was used for that article?
SQL> select customer_seq.CURRVAL from dual

Copyright Infogain Corporation, 2007

- 63 -

Using a Sequence (cont.)

Gaps in sequence values can occur when: ‡ A ROLLBACK occurs
‡ The system crashes ‡ A sequence is used in another table

Copyright Infogain Corporation, 2007

- 64 -

Copyright Infogain Corporation. 2007 . Sequence altered.Modifying a Sequence ” You must be the owner or have the ALTER SEQUENCE privilege Can change the increment value. cycle option. or cache option ‡ Can¶t change the START value« the sequence must be dropped and re-created ” SQL> ALTER SEQUENCE customer_seq 2 INCREMENT BY 1 3 MAXVALUE 9999 4 NOCACHE 5 NOCYCLE. minimum value. maximum value.65 - .

” Copyright Infogain Corporation.Removing a Sequence ” Once removed. 2007 . the sequence can no longer be referenced You must be the owner of the sequence or have the DROP ANY SEQUENCE privilege DROP SEQUENCE <sequence name>.66 - .

2007 . dropping a Synonym. ” ” ” ” Copyright Infogain Corporation.Synonyms ” SYNONYMS is a database object which is used as a alias for a table nothing but a alternative name for the table. The syntax for creating Synonym is: ‡ CREATE SYNONYM synonym name FOR reference. 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.67 - .

68 - .Example ” To create new synonym: ‡ CREATE SYNONYM customer ‡ FOR cz_imp_customer. ” Copyright Infogain Corporation. To drop synonym: ‡ DROP SYNONYM customer. 2007 .

2007 . Revoke ” ORACLE provides extensive security features in order to safeguard the user¶s information from both unauthorized access and intentional damage.Security ± Creating user.69 - . ” Copyright Infogain Corporation. This security is provided by granting or revoking privileges on a userby user and privilege-by-privilege basis. Grant.

Copyright Infogain Corporation. ‡ GRANT: A user can grant access to his database object's) to other user's) ‡ REVOKE: To withdraw a privilege you have granted. Revoke (cont. of course restricted only to those privileges that the user has.Security ± Creating user.) ” A user can also grant privileges directly to other user. 2007 . 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. ‡ Creating USER: Use the CREATE USER statement to create and configure database user. the REVOKE command is used.70 - .

. ‡ REVOKE: ‡ REVOKE UPDATE ON customer_master FROM PUBLIC. 2007 .71 - ” Copyright Infogain Corporation.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.Examples on User.

72 - . PL/SQL engine executes only a procedural statements and sends SQL statements to the SQL executer. 2007 . ” ” Copyright Infogain Corporation. PL/SQL engine executes PL/SQL block. PL/SQL also provides performance improvements through blocking of RDBMS calls. The PL/SQL engine resides within the Oracle Server so it is available from any application development tool that supports PL/SQL. It includes many features and designs of programming language.Introduction 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.

2007 Packaged procedure .73 - . Database trigger Copyright Infogain Corporation.Structure of PL/SQL Anonymous block Stored Procedure / function DECLARE BEGIN Application trigger EXCEPTION Application Procedure / function END.

2007 .74 - Copyright Infogain Corporation. . 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 Define the executable statements Define the action that take place if an error arises ‡ BEGIN (mandatory) ± ‡ EXCEPTION (optional) ± ” END.Anonymous Blocks ” Anonymous block is block without a name These blocks are declared at the point in an application where they are to be run.

Executable Section ‡ Contains SQL statements to manipulate data in the database. ” ” Copyright Infogain Corporation. This section is mandatory. 2007 . cursors and user-defined exceptions that will be referenced within the executable section.) ” Declaration Section ‡ Contains all variables.Anonymous Blocks (cont. Exception Handling Section ‡ Specifies the actions to perform when errors and abnormal conditions arise within the executable section. and PL/SQL statement to manipulate data in the block. This section is optional. constants.75 - . This section is also optional.

.76 - Oracle with PL/SQL Copyright Infogain Corporation. THEN SQL ELSE SQL END IF.. 2007 .Benefits of PL/SQL Improve Performance SQL Application SQL SQL SQL OTHER DBMSs Application SQL IF. SQL .

77 - ” ” ” ” Copyright Infogain Corporation.Variables and Constants ” Variables are used to store the result of a query or calculation. Constants are declared by specifying the keyword CONSTANT before the data type. The general syntax is: ‡ <VAR-NAME> <TYPE> (:= <VALUE>). 2007 . the assignment operator µ:=µ is used. 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. .

Types of Variables ” PL/SQL Variables ‡ Scalar ‡ Composite ‡ Reference ‡ LOB Syntax Of Declaring a PL/SQL Variables Identifier [CONSTANT] data type [NOT NULL] [:= | DEFAULT expr]. ‡ Customer_name VARCHAR2(15) := µ THOMAS µ. Example: ‡ Customer_id NUMBER(4) NOT NULL:= 10. 2007 . .78 - ” ” ” Copyright Infogain Corporation.

79 - .%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 ‡ x_salary ‡ x_min_salary ” ” ” ra_customers. 2007 . NUMBER(7.2).customer_name%TYPE. x_salary%TYPE Copyright Infogain Corporation.

PUT_LINE (µThe monthly salary is µ|| TO_CHAR(salary)). 2007 .Printing Output to the Screen DBMS_OUTPUT.2) := 1000.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. ” Copyright Infogain Corporation.80 - . ” END. ” BEGIN ” salary:= salary/2. ” DBMS_OUTPUT.

2007 .Operators in PL/SQL ” Logical Arithmetic Concatenation Parentheses to control order of operations Exponential operator(**) ” ” ” ” Copyright Infogain Corporation.81 - .

NOT OPERATION Exponentiation. >. BETWEEN. negation Multiplication. <=. ISNULL. <.subtraction.concatenation Comparison Conjunction Inclusion +. 2007 . || =. -.Operators in PL/SQL (cont.) OPERATOR **. !=.82 - . LIKE. IN AND OR Copyright Infogain Corporation. >=.division Addition. *. / +. logical negation Identity.

salary%Type BEGIN SELECT salary INTO v_salary FROM customer_data WHERE id = 2 :g_salary := v_sal. END. Example: VARIABLE g_salary NUMBER DECLARE v_salary customer_data. / SQL> PRINT g_salary . 2007 .Bind Variables ” Bind Variables in PL/SQL can be used using a colon(:) as a prefix.83 - ” Copyright Infogain Corporation.

Scope of x Scope of y Copyright Infogain Corporation.... END. 2007 .Determining Variable Scope . BEGIN .. DECLARE y Number. END.84 - .... BEGIN . x Number. ..

Writing SQL Statements in PL/SQL Block

The syntax of SQL Statements in the PL/SQL environment SELECT select_list INTO { variable_name[, variable_name] « | record_name } FROM table | view WHERE condition;

Copyright Infogain Corporation, 2007

- 85 -

Retrieving Data in PL/SQL
Example: DECLARE v_salary number; BEGIN select salary INTO v_salary FROM customer_data WHERE id = 1; END; /

Copyright Infogain Corporation, 2007

- 86 -

Insert/Update Data
Example: INSERT BEGIN INSERT INTO customer_data (ID, USERNAME, SALARY) VALUES (3,¶THOMAS¶,12000); END; Example: UPDATE Declare v_sal_incr customer_data.salary%TYPE:= 13000; Begin update customer_data set salary= salary + v_sal_incr where state = µMAHARASTRA¶; End;

Copyright Infogain Corporation, 2007

- 87 -

2007 . Copyright Infogain Corporation. Begin Delete from customer_data where id=v_id.88 - .Deleting Data Declare v_id customer_data%TYPE:= 3. End.

COMMIT or ROLLBACK can be used to make the transaction permanent or revoke them. ” Copyright Infogain Corporation.89 - . 2007 . A Transaction gets saved when COMMIT is issued and terminated when ROLLBACK is used.Commit and Rollback ” When a transaction starts with a DML command.

2007 . Copyright Infogain Corporation.Commit and Rollback (cont. ROLLBACK [transaction] TO [SAVEPOINT] savepoint .90 - .) Syntax COMMIT [transaction]. SAVEPOINT savepoint_name . ROLLBACK [transaction] .

PL/SQL provides a facility for executing statements repeatedly.Control Statements ± Loops.91 - . ” Copyright Infogain Corporation. 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. via loops. Loops are divided into three categories: ‡ Simple loops ‡ WHILE loops ‡ FOR loops. 2007 .

) ” The IF clause can be used for the conditional processing of statements.Control Statements ± Loops. the statements following the THEN clause are executed until one of the following is encountered: ELSIF. ” Copyright Infogain Corporation.92 - . ELSE or END IF. If (cont. 2007 . If the condition specified after the IF clause evaluates to true.

93 - . ” ” Copyright Infogain Corporation. The syntax is: ‡ LOOP ‡ < statements > ‡ END LOOP. Sequence of statements will be executed infinitely. since this loop has no stopping condition. 2007 .Simple Loops ” The most basic kind of loops is Simple loops.

The syntax is: ‡ WHILE < condition > LOOP ‡ < statements > ‡ END LOOP. 2007 . If it evaluates to TRUE. ” ” ” Copyright Infogain Corporation.94 - .While Loops ” The condition is evaluated before each iteration of the loop. If condition evaluates to FALSE or NULL the loop is finished and control resumes after the END LOOP statement. sequence of statements is executed.

Numeric FOR loops. 2007 . The syntax is: FOR ctr IN 1««20 LOOP INSERT INTO temp values (ctr). It depends on the loop condition.Numeric for Loops ” The number of interactions for simple loops and WHILE loops is not known in advance.. «««. END LOOP. have a defined number of interactions. .95 - ” ” ” Copyright Infogain Corporation. on the other hand. «««..

Cursors .

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 ” ” ” Copyright Infogain Corporation.SQL Cursor ” A Cursor is a memory area in which the SQL statement is parsed and executed. 2007 .97 - .

98 - .Implicit Cursor Attributes ” The outcome of the SQL statement can be determined by the implicit cursor attributes. 2007 . SQL%ROWCOUNT 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 SQL%FOUND SQL%NOTFOUND SQL%ISOPEN Copyright Infogain Corporation.

µ). Print rows_deleted Copyright Infogain Corporation. Begin Delete from customer_data where id=v_id.Implicit Cursor Attribute Example Variable rows_deleted varchar2(30) Declare v_id customer_data%TYPE:= 3. :rows_deleted:= (SQL%ROWCOUNT || µ rows deleted. End. 2007 .99 - .

Explicit Cursor ” Explicit Cursors are declared explicitly by the user. 2007 . ‡ Close the cursor. and manipulated through specific statements within the block¶s executable actions. The four PL/SQL steps necessary for explicit cursor processing are as follows: ‡ Declare the cursor for a query. and allow multiple rows to be processed from the query. ‡ Open the cursor . ” ” Copyright Infogain Corporation. along with other identifiers to be used in a block. ‡ Fetch a row from the cursor [continue till all rows are fetched]. Explicit cursors are for queries only.100 - .

Declaring 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.


Copyright Infogain Corporation, 2007

- 101 -

Opening, 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 %TYPE CURSOR cust_cursor is select * from customer_data; BEGIN Open 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;
Copyright Infogain Corporation, 2007 - 102 -

Explicit Cursor Attributes
Attribute %ISOPEN Type

Description 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

Copyright Infogain Corporation, 2007

- 103 -

. 2007 .. Copyright Infogain Corporation.The %ISOPEN attribute example . LOOP FETCH cust_cursor... IF NOT cust_cursor %ISOPEN THEN OPEN cust_cursor ..104 - . END IF..

Example: ‡ Declare ‡ customer_record ” ” ” ra_customers%ROWTYPE.105 - . 2007 .« Copyright Infogain Corporation. 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.The %ROWTYPE Attribute ” Used to declare a variable according to a collection of columns in a database table or view.

106 - . The attribute is useful when retrieving a row with the SELECT statement. ” ” Copyright Infogain Corporation.Advantages 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. 2007 .

Implicit open and fetch occur statement1.Cursor FOR loop ” SYNTAX « Begin FOR record_name IN cursor_name LOOP -. END LOOP. fetch and close occurs The record is implicitly declared .. Implicit open. .107 - ” ” Copyright Infogain Corporation. statement2. 2007 ..

Body: A procedure body begins with µIs¶ and ends with µEnd¶.Procedures ” 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. 2007 .108 - . ” ” ” Copyright Infogain Corporation.

Copyright Infogain Corporation.Procedural Parameters Procedure Calling environment IN parameter OUT parameter IN OUT parameter (DECLARE) BEGINE EXCEPTION END. 2007 .109 - .

END raise_cost.110 - . 2007 .Example CREATE OR REPLACE PROCEDURE raise cost (m_stockitemno IN stock_item_master. Copyright Infogain Corporation.stock_item_number%type) IS BEGIN update stock_item_master set cost = cost + (cost * 0. To execute the procedure form the SQL prompt give following command ± EXECUTE get_cost(µSTOCK_ITEM_NO¶). commit.5) where stock_item_number = m_stockitemno.

Functions ” A function is a named PL/SQL block that returns a value.111 - . A function can be called as a part of expression. or DELETE commands are not allowed. 2007 . A function can be stored in the database. as a database object. ” ” ” Copyright Infogain Corporation. for repeated execution. UPDATE. In function INSERT.

112 - .Example CREATE OR REPLACE FUNCTION get_cost (m_stockitemno IN stock_item_master.cost%type. BEGIN select cost into m_cost from stock_item_master where stock_item_number = m_stockitemno. END get_cost.stock_item_number%type) RETURN number IS m_cost stock_item_master. Copyright Infogain Corporation. 2007 . RETURN (m_cost). To run the function form the SQL prompt give following command ± Select get_cost(µSTOCK_ITEM_NO¶) from dual.

There is considerable performance improvement because of this encapsulation. 2007 . variables. Packages are groups of procedures. and SQL statements grouped together into a single unit. ” ” Copyright Infogain Corporation. functions.Packages ” A Package is a database object that groups logically related PL/SQL objects.113 - .

Packages usually have two parts.) ” The entire package is located into the memory when a procedure. 2007 . cursor.114 - . within the package is called for the first time. ” ” ” Copyright Infogain Corporation. a specification and a body. In Package specification we can declare type.Packages (cont. procedure. This reduces the unnecessary disk I/O and network traffic.

Copyright Infogain Corporation.115 - .cost%type.stock_item_number%type) RETURN number IS m_cost stock_item_master. 2007 . RETURN (m_cost). END comm_package.FUNCTION get_cost (m_stockitemno IN stock_item_master. BEGIN select cost into m_cost from stock_item_master where stock_item_number = m_stockitemno. END get_cost.

116 - . Copyright Infogain Corporation. DECLARE BEGIN EXCEPTION END .Exception Handling Trap the exception Propagate the exception DECLARE BEGIN EXCEPTION END . 2007 .

2007 .117 - .Exception Types ” Implicitly raised ‡ Predefined Oracle Server ‡ Non-predefined Oracle Server Explicitly raised ‡ User-defined ” Copyright Infogain Corporation.

statement2.] THEN statement1.118 - . . [WHEN exception C [OR exception D .. . statement2.] ” Copyright Infogain Corporation. 2007 . . .. ... [ WHEN OTHERS THEN statement1.. statement2.Trapping Exceptions Syntax EXCEPTIONS WHEN exception A [OR exception B .. . .] THEN statement1.

2007 .119 - .Predefined Oracle Server Errors ” Sample predefined exceptions ± ± ± ± ± NO_DATA_FOUND TOO_MANY_ROWS INVALID_CURSOR ZERO_DIVIDE DUP_VAL_ON_INDEX Copyright Infogain Corporation.

” ” Copyright Infogain Corporation.Trapping Non-Predefined Errors ” Declare a user defined exception Associate it with the Oracle defined error using PRAGMA EXCEPTION INIT Handle the raised exception.120 - . 2007 .

121 - . 2007 .Functions for Trapping Exceptions ” SQLCODE Returns the numeric value for the error code SQLERRM Returns the messages associated with the error number ” Copyright Infogain Corporation.

2007 .Trapping User Defined Exception ” Declare the exception Explicitly raise the exception by using the RAISE statement Handle the raised exception ” ” Copyright Infogain Corporation.122 - .

(TRUE | FALSE]). 2007 . ” ” Copyright Infogain Corporation.The 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[.123 - .

124 - . 2007 . Type Of Triggers ‡ Row-Level Triggers ‡ Statement Level Triggers ‡ BEFORE and AFTER Triggers ‡ INSTEAD OF Triggers ‡ System or User Event Triggers ” Copyright Infogain Corporation.PL/SQL TRIGGERS ” A Trigger is defined as an action the database should take when some database related event occurs.

} on { [ schema .] schema | database } } [ when ( condition ) ] { pl/sql_block | call_procedure_statement } Copyright Infogain Corporation. .125 - . . .] trigger { before | after | instead of } { dml event cause | { ddl_event [or ddl_event] . 2007 .Trigger Syntax create [ or replace ] trigger [schema . .

a row trigger is not executed.126 - . 2007 . ” ” Copyright Infogain Corporation.Row 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.

Statement Level Trigger ” A statement trigger is fired once on behalf of the triggering statement. even if no rows are affected. ” Copyright Infogain Corporation. 2007 . regardless of the number of rows in the table that the triggering statement affects.127 - . if a DELETE statement deletes several rows from a table. For example. a statement-level DELETE trigger is fired only once.

not on particular tables. triggers on the base tables of a view are fired if an INSERT. BEFORE and AFTER triggers fired by DML statements can be defined only on tables. 2007 . ” ” Copyright Infogain Corporation. However. you can specify the trigger timing--whether the trigger action is to be executed before or after the triggering statement.128 - . or DELETE statement is issued against the view.Before and After Trigger ” When defining a trigger. not on views. UPDATE. BEFORE and AFTER triggers fired by DDL statements can be defined only on the database or a schema.

2007 .Before and After Trigger Combinations ” BEFORE statement trigger BEFORE row trigger AFTER row trigger AFTER statement trigger ” ” ” Copyright Infogain Corporation.129 - .

2007 . UPDATE. UPDATE. and DELETE) You can write normal INSERT. unlike other types of triggers. Oracle fires the trigger instead of executing the triggering statement. 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 .130 - ” ” ” Copyright Infogain Corporation. INSTEAD OF triggers provide a transparent way of modifying views that cannot be modified directly through DML statements (INSERT.INSTEAD OF Triggers ” These triggers are called INSTEAD OF triggers because.

2007 . and DROP) ‡ DML statements (INSERT.131 - .System Or User Event Trigger ” System events ‡ Database startup and shutdown ‡ Server error message events User events ‡ User logon and logoff ‡ DDL statements (CREATE. and UPDATE) ” Copyright Infogain Corporation. ALTER. DELETE.

'SUN')) or (to_char(sysdate..').'DY') IN ('SAT'.'HH24') NOT BETWEEN '09' and '18') then raise_application_error(-20500. END.Example CREATE OR REPLACE TRIGGER secure_stock BEFORE INSERT ON stock_item_master BEGIN IF (to_char(sysdate. 2007 .'You may only insert during normal hours. Copyright Infogain Corporation. END IF..132 - .

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->