Vous êtes sur la page 1sur 163

ORACLE

WHAT IS ORACLE ?

Conceptually Oracle is a Kernel package that has a number of tools that can be purchased separately and integrated with the kernel as Addons. These tools allows the user to create data base objects, forms, reports, graphs etc. Some of the tools of Oracle are SQL *Plus, Oracle Forms, Oracle Report Writer, Oracle Graphics, SQL Precompiler for C & Cobol.

TOOLS OF ORACLE

Oracle DBA : The Oracle DBA can compile and execute SQL Sentences issued by a user.
SQL *Plus : It is made up of two parts : i) Interactive SQL ii) PL / SQL It is an oracle specific program which accepts SQL commands and PL/SQL blocks and executes them. PL/SQL is Extension of SQL. It can contain any number of SQL statements integrated with the flow of control statements.

Forms : This is a graphical tool used for generating and executing forms based applications. Allows us to create a data entry screen.
Reports : It is an application development tool of oracle for developing displaying and printing reports.

Oracle Graphics : Using this tool data can be represented in the form of graphs.

STRUCTURED QUERY LANGUAGE

INTRODUCTION TO SQL
Structured Query Language is a standard command set used to communicate with the RDBMS. This is the natural language of Oracle DBA. It is developed by IBM in 1970s. ANSI has accepted SQL has become a standard language for RDBMS. Language is used by most of the database management systems to unable users to access data.

FEATURES OF SQL
SQL is English Like Language. SQL is non-procedural language. SQL commands sets can be used by administrators, developers and end users alike for their varying requirements. SQL can be used for variety of tasks.

Creating and manipulating database objects. Manipulating data stored in database. Querying data stored in the tables. Controlling access to the databases objects for security Ensure database security.

SQL
SQL is broadly divided into three categories :

DDL (Data Definition Language) Create, Drop, Alter, Truncate DML (Data Manipulation Language) Select, Insert, Update, Delete DCL (Data Control Language) Grant, Revoke, Commit, Rollback, Savepoint

INVOKING SQL *PLUS


Start windows in normal way. Click on Start button and click on Programs. It displays a list of programs. Click on Oracle and then select SQL *Plus. You are prompted for your Login id and Password. Once Login id and password is entered, and SQL> prompt appears. Now you are connected to Oracle DBA. Now you can start to write SQL Commands or SQL statements.

Guidelines for Writing SQL Commands


An SQL command is entered at the SQL *Plus prompt. Word delimiter is a space or a tab. Command entry can be in upper or lower case. SQL commands may be one line or several lines. Most recent SQL or PL/SQL command is stored in SQL buffer. Buffer command can be edited or re-executed. SQL commands can be terminated by

1) Semicolon (;)

2) Slash (/)

3) Blank Line

SELECT Statements

Simplest form of SELECT Statement contains


SELECT clause FROM clause e.g.-Select Ename, DeptNo from Emp; e.g.-Select * from emp;

Specifying column headers (Column Aliases) Concatenation operator Handling NULL values Eliminating duplicate values.

SELECT Statements
Simplest form of SELECT Statement contains The SELECT SQL verb is used to view the table data. 1.AllRows and all column:
SELECT * FROM tablename;

2.Selected Columns and All Rows:


SELECT columname,columname FROM tablename;

3.Selected Rows and All Columns:


SELECT * FROM tablename WHERE search condition;
SELECT columnname,columnname FROM tablename WHERE search condition;

3.Elimination of duplicates from the Select statement:


SELECT DISTINCT * FROM tablename; SELECT DISTINCT columnname, columname FROM tablename ;

4.Sorting data in a table:


SELECT * FROM tablename

ORDER BY columnname,columname [sort order];

SELECT Statements

Sorting query results (ORDER BY clause)


Data results are presented in a sorted order (ascending or descending) according to the value of the column specified with ORDER BY clause. More than one column can be used to query result. When data is sorted in the ascending order NULL values appears at the end in sorted column. ORDER BY clause should be the last clause in SELECT statement. ASC and DESC.

SELECT Statements

Both DISTINCT and ORDER BY clause can not be used with SELECT statement.

WHERE clause : Used with SELECT statement to retrieve selected row from a table. Condition specified with WHERE clause acts as a filter and returns only those rows that satisfy the condition. WHERE clause must follow the FROM clause, if used. Condition specified after WHERE clause contains:
A

column name, A comparison operator, literal or list of values.

END1

ORACLE DATA TYPES


Data Type
Char (size)

Description
Represents fixed length characters up to the width size. The default width is 1 and maximum width is 255 characters.

Varchar2 (size) Represents fixed length characters up to the width size. The maximum width is 2000 characters.
Number Represents the floating point number with 38 significant digits precision.

Number (Size) Represents integers of precision size.

Number (p,s)
Date

Represents numbers with precision of size p and numbers of digits after the decimal is s. Represents date and time in table in fixed length in 7 bytes. Default format is dd-mm-yyy.

ORACLE DATA TYPES


Data Type
Long Raw

Description
Represents the variable length characters up to 2 GB. Only one column is allowed per table. Used to store byte oriented data like binary data or byte strings and the maximum size is 2000 bytes.

Long Raw
CLOB

Used to store binary data of variable length, which can have a maximum size off 2 GB.
Used to store character object with single byte characters. Can not contain character sets of varying widths. Table can have multiple columns with CLOB data type.

BLOB
BFILE

Used to store large binary objects such as graphics video clips and sound files. Table can have multiple columns. Used to store file pointers to LOBs managed by file systems external to the database.

DATA DEFINITION LANGUAGE (DDL)

DDL is a set of SQL commands used to create, modify or remove various database objects such as table views, synonyms etc.

DDL commands
Create Alter Drop Truncate

CREATING TABLES
Creating Table : CREATE TABLE statement : Syntax : CREATE TABLE <tablename> (column_name data_type (size), column_name data_type(size) .);

E.g. CREATE TABLE student (sr_no number(2), roll_no number (3), name varchar2(20), address varchar2(50));

INSERTING VALUES IN THE TABLE

INSERT statement : Syntax : INSERT INTO <tablename> (column, column) VALUES (value, value ); Note :

When you supply values to all columns it is not necessary to have column list. When to supply values to specific columns, it is mandatory to have a column list. Date and character columns are required to be enclosed in a single quotes. One INSERT command add one row to a table at a time unless a subquery is used. Can be used a substitution variables to insert rows.

DELETE OPERATIONS

The verb DELETE in SQL is used to remove rows from table. To remove All the rows from a table or A select set of rows from a table. REMOVAL OF ALL ROWS : Syntax : DELETE FROM <tablename>; REMOVAL OF A SPECIFIED ROW/S Syntax : DELETE FROM <tablename> WHERE search condition;

RENAMING TABLES

To rename a table, the syntax is : Syntax : RENAME oldtablename TO newtablename

DESTROYING TABLES

To destroy the table, the Syntax is : Syntax : DROP TABLE <tablename>;

End2

EXAMINING OBJECTS CREATED BY A USER

Finding out the table/s created by a user : To determine which tables the user has access to the syntax is : SELECT * FROM TAB; The objects name and type are displayed. Finding out the column details of a table created : To find information about the columns defined in the table use the following syntax : Syntax : DESCRIBE <tablename>;

UPDATING THE CONTENTS OF A TABLE

The update command is used to change or modify data values in a table. To update All the rows from a table OR A select set of rows from a table.

UPDATING OF ALL ROWS : Syntax : UPDATE <tablename> SET (columnname = expression, columnname = expression);
UPDATING RECORDS CONDITIONALLY : Syntax : UPDATE <tablename> SET (columnname = expression, columnname = expression) WHERE columnname = expression;

MODIFYING THE STRUCTURE OF TABLE

ADDING NEW COLUMNS : Syntax : ALTER TABLE <tablename> ADD (newcolumnname datatype(size),.);

MODIFYING EXISTING COLUMNS : Syntax : ALTER TABLE <tablename> MODIFY (columnname newdatatype (newsize));

RESTRICTIONS ON THE ALTER TABLE : Using the ALTER TABLE clause the following tasks cannot be performed.
Change the name of the table. Change the name of the column. Drop a column. Decrease the size of a column if table data exists.

END3

CREATING A TABLE FROM A TABLE

Syntax : CREATE TABLE <tablename> (columnname, columnname) AS SELECT columnname, columnname FROM <tablename>;
The Source table is the table identified in the SELECT section of the SQL sentence. The Target table is one identified in the CREATE section of the SQL sentence. This SQL sentence populates the Target table with data from the Source Table.

To create a Target table without the records from the source table (i.e. create the structure only), the select statement used will have a where clause. The condition specified in the where clause must not be satisfied. This means the select statement in the CREATE TABLE definition must not retrieve any rows.

INSERTING DATA INTO A TABE FROM ANOTHER TABLE

In addition to inserting data one row at a time into a table, it is quite possible to populate a table with data that already exists in another table. The syntax for this is : Syntax : INSERT INTO <tablename> SELECT columnname, columnname FROM <tablename>; Insertion of a data set into a table from another table : INSERT INTO <tablename> SELECT columnname, columnname FROM <tablename> WHERE columnname = expression ;

OPERATORS
Operator
+ (Addition) - (Subtraction) * (Multiplication) Arithmetic Operators

Description

/ (Division)
= (Equal to) > (Greater Than) >= (Greater Than or Equal To) < (Less Than) Logical Operators

<= (Less Than or Equal To)

LOGICAL OPERATORS

The AND Operator : The Oracle engine will process all rows in a table and display the result only when all of the conditions specified using the AND operator are satisfied. e.g.SELECT product_no, description, profit_percent FROM product_master WHERE profit_percent >=10 AND profit_percent <=20;

The OR Operator : The Oracle engine will process all rows in a table and display the result only when any of the conditions specified using the OR operator are satisfied.

e.g.SELECT clinet_no, name, address1, address2, city, pincode FROM client_master WHERE (pincode =400054 OR pincode = 400057;

The NOT Operator : The Oracle engine will process all rows in a table and display the result only when none of the conditions specified using the NOT operator are satisfied.
SELECT clinet_no, name, address1, address2, city, pincode FROM client_master WHERE NOT (city = Bombay or city = Delhi);

e.g.-

RANGE SEARCHING
In order to select data that is within a range of values, the BETWEEN operator is used. The BETWEEN operator allows the selection of rows that contain values within a specified lower and upper limit. The range coded after the word BETWEEN is inclusive. The lower value must be coded first. The two values in between the range must be linked with the keyword AND. A BETWEEN operator can be used with both character and numeric data types. However, one cannot mix the data types i.e. the lower value of a range of values from a character column and the other from a numeric column.

E.g: SELECT product_no,description, profit_percent,sell_price FROM product_master WHERE profit_percent BETWEEN 10 AND 20;

PATTERN MATCHING

The use of the LIKE predicate :


The comparison operator discussed so far have compared one value, exactly to one other value. Such a precision may not always be desired or necessary. For this purpose Oracle provides a predicate LIKE. The LIKE predicate allows for a comparison of one string value with another string value, which is not identical. This is achieved by using wildcard characters. Two wildcard characters that are available are :
For character : data types The percent sign (%) matches any string The Underscore ( _ ) matches any single character.

1) Retrieve all information about suppliers whose names begin with the letters ja from supplier_master. E.g.: SELECT * FROM supplier_master WHERE supplier_name LIKE ja%; 2) Retrieve all information about suppliers where the second character of names are either r or h. E.g.: SELECT * FROM supplier_master WHERE supplier_name LIKE _r% OR supplier_name LIKE _h%;

The IN and NOT IN predicates :


The arithmetic operator ( = ) compares a single value to another single value. In case a value needs to be compared to a list of values then the IN predicate is used. One can check a single value against multiple values by using the IN predicate. The NOT IN predicate is the opposite of the IN predicate. This will select all the rows where values do not match all of the values in the list.

1) Retrieve the supplier_name, address1,address2, city and pincode from the table supplier_master where the supplier_name is either Ramos or Clark or Pramada . E.g.: SELECT supplier_name,address1,address2, city, pincode FROM supplier_master WHERE supplier_name IN (Ramos, Clark, Pramada); 2) NOT IN E.g.: SELECT supplier_name,address1,address2, city, pincode FROM supplier_master WHERE supplier_name NOT IN (Ramos, Clark, Pramada);

THE ORACLE TABLE DUAL


Dual is a small Oracle worktable, which consists of only one row and one column, and contains the value x in that column. Besides arithmetic calculations, it also supports date retrieval and its formatting. Often a simple calculation needs to be done, e.g. 2*2. The only SQL verb to cause an output to be written to a VDU screen is SELECT. However, a SELECT must have a table name in its FROM clause, otherwise the SELECT fails. When an arithmetic exercise is to be performed such as 2*2 or 4/2 etc, there really is no table being referenced, only numeric literals are being used. To facilitate such calculations via a SELECT, Oracle provides a dummy table called DUAL, against which SELECT statement that are required to manipulate numeric literals can be fired and output obtained.

Example :

SQL> SELECT 2 * 2 FROM dual;


Output : 2*2 ------4 The current date can be obtained from the table DUAL in the required format as shown below : SYSDATE : Sysdate is a pseudo column that contains date and time. It requires no arguments when selected from the table DUAL and returns the current date.

Example :
SQL> SELECT sysdate FROM dual; Output : SYSDATE -------------18-FEB-82

END4

ORACLE FUCTIONS

CHARACTER FUNCTIONS
Function
LOWER (char) UPPER (char) INITCAP (char) CONCAT (char1,char2) SUBSTR (char, m, n) LPAD (char1,n,char2) RPAD (char1,n,char2) LTRIM (char, set) RTRIM (char, set)

Description
Returns char, with all letters in lower case. Returns char, with all letters in upper case. Returns string with the first letter in upper case. Joins char1 and char2 values in the output. Returns a portion of char, beginning at character m exceeding upto n characters. Returns char1 left padded to length n with the sequence of characters in char2. Returns char1 right padded to length n with the sequence of characters in char2. Removes characters from the left of char with initial characters removed upto the first character not in set. Returns char after final characters removed after the last character not in set.

Function Lower Upper Initcap Substr Lenghth

Syntax SELECT LOWER (IVAN BAYROSS) LOWER FROM Dual; SELECT UPPER (Mr. Carol) FROM Dual; SELECT INITCAP (IVAN BAYROSS) Title Case FROM Dual; SELECT SUBSTR (BAYROSS,3,4) Substring FROM Dual; SELECT LENGTH (IVAN BAYROSS) LENGTH FROM Dual;

Ltrim
Rtrim Lpad Rpad Concat

SELECT LTRIM (NISHA,N) Left trim example FROM Dual;


SELECT RTRIM (NISHA,A) Right trim example FROM Dual; SELECT LPAD (Page 1,10,*) Lpad FROM Dual; SELECT RPAD ( name,10,x) Rpad FROM client1_master Where name= TURNER; SELECT CONCAT(Rohan,Patil) Concat FROM Dual;

END5

NUMBER FUNCTIONS
Function ABS (n) Description Returns the absolute value of n.

CEIL (n)
ROUND (n, m) MOD (m, n) TRUNC (n, m) POWER (m, n) SQRT (n) EXP (n) SIGN (n)

Returns smallest integer that is greater than or equal to n


Returns n rounded to m places right of the decimal point, if m is omitted then n is rounded to 0. Returns the remainder of m divided of m divided by n. Returns n truncated to m decimal places if m is omitted to 0 places. Returns m raised to the nth power. Returns the square root of n. Returns e raised to the nth power. If n<0, the function returns -1, if n=0 the function returns 0, if n>0 the function returns 1.

Function

Syntax

ABS
POWER ROUND SQRT CEIL MOD TRUNC EXP FLOOR

SELECT ABS(-15) Absolute FROM dual;


SELECT POWER(3,2) Raised FROM dual; SELECT ROUND(15.19,1) Round FROM dual; SELECT SQRT(25) Square Root FROM dual; SELECT CEIL(5) CEIL FROM dual; SELECT MOD(12,10) MOD FROM dual; SELECT TRUNC(12,3) MOD FROM dual; SELECT EXP(2) EXP FROM dual; SELECT FLOOR(12) FLOOR FROM dual;

SIGN

SELECT SIGN(-2) SIGN FROM dual;

DATE FUNCTIONS
Function SYSDATE MONTHS_BETWEEN (d1,d2) ADD_MONTHS (d, n) LAST_DAY (d) NEXT_DAY (d, char) Description Returns todays date. Returns number of months between d1 and d2. Returns the date d plus n months. Returns the date of the last day of the month that contains d. Returns the date of the first weekday named by char that is later than the date d. The argument char may be number representing a day or a character string.

Date Functions SYSDATE ADD_MONTHS LAST_DAY MONTHS_BETWEEN NEXT_DAY

Syntax SELECT SYSDATE FROM DUAL; SELECT ADD_MONTHS(SYSDATE,4) FROM DUAL; SELECT SYSDATE, LAST_DAY(SYSDATE) LAST FROM DUAL; SELECT MONTHS_BETWEEN(02-FEB-92,02-JAN92)MONTHS FROM DUAL; SELECT NEXT_DAY(04-FEB-98,FRIDAY) NEXT DAY FROM DUAL;

TIME FUNCTION
NEW_TIME (date, this, other) : Gives the date (and time) in this time zone. this will be replaced by a three-letter abbreviation for the current time zone. other will be replaced by a three-letter abbreviation for the other time zone for which youd like to know the time and date. Time zones are as follows : AST/ADT : Atlantic Standard / daylight Time BST/BDT : Bering Standard / daylight Time CST/CDT : Central Standard / daylight Time EST/EDT : Eastern Standard / daylight Time GST : Greenwich Mean Time HST/HDT : Alaska-Hawaii Standard / daylight Time MST/MDT : Mountain Standard / daylight Time NST : Newfoundland Standard Time PST/PDT : Pacific Standard / daylight Time YST/YDT : Yukon Standard / daylight Time

END6

CONVERSION FUNCTIONS
Function TO_CHAR (n, fmt) TO_CHAR (n, fmt) TO_DATE (char, fmt) ASCII (char) CHR (num) Description Converts the value of NUMBER datatype to a value of CHAR datatype using optional format string. Converts the value of DATE datatype to a CHAR value. Converts the character value representing date into a date value according to the fmt specified. Returns ASCII value of char. Returns ASCII character of num.

Function
TO_CHAR TO-CHAR TO_DATE ASCII CHR

Syntax
SELECT TO_CHAR(17145,$099,999) CHAR FROM DUAL; SELECT TO_CHAR(HIREDATE, MONTH DD,YYYY) New Date Format FROM EMP WHERE EMPNO=11; INSERT INTO EMP (EMPNO,HIREDATE) VALUES 07756,TO_DATE (30-SEP-85 10:55 A.M.,DD-MON-YY HH:MI A.M.); SELECT ASCII(a) ASCII FROM DUAL; SELECT CHR(97) CHAR FROM DUAL;

GROUP FUNCTIONS

Processes multiple rows of a table and group them based on a condition. Group functions return only a single row as the result of grouping the rows. Important notes :

Where clause can used to restrict the input of rows for group formation. Group functions cannot be used with where clause. Can be used multiple column name in the group by clause. All group functions except COUNT (*) ignore nulls. Columns not taking part in the group functions cannot appear in the SELECT column list. They can appear in the select column-list only if they are part of GROUP BY clause.

GROUP FUNCTIONS
Function Description

AVG (expr)
COUNT (expr)

Returns average value.


Returns number of rows in the query

MAX (expr) MIN (expr)


SUM (expr)

Returns maximum value of expr. Returns minimum value of expr.


Returns sum of values of expr.

Function AVG COUNT MIN MAX SUM

Syntax SELECT AVG(sell_price) Average FROM PRODUCT_MASTER Select count(empno) No of Employees FROM EMP; SELECT MIN(bal_due) Minimum Balance FROM CLIENT_MASTER; SELECT MAX(bal_due) Maximum Balance FROM CLIENT_MASTER SELECT SUM(bal_due) Total Balance Due FROM CLIENT_MASTER

HAVING CLAUSE Having clause is used to restrict the display of grouped rows. The result of the grouped query is passed on to the HAVING clause for output filtration. Important notes :

The WHERE clause can still be used to consider the specific set of rows. The WHERE clause restricts the input before grouping The WHERE clause can not use group functions. The HAVING clause restricts the output and can only be used when the GROUP BY clause is part of query.

e.g:SELECT PRODUCT_NO, SUM (QTY_OERDERED) TOTAL QTY ORDERED FROM SALES_ORDER_DETAILS GROUP BY PRODUCT_NO

e.g:SELECT PRODUCT_NO, SUM (QTY_OERDERED) TOTAL QTY ORDERED FROM SALES_ORDER_DETAILS GROUP BY PRODUCT_NO HAVING PRODUCT_NO = P00001 OR PRODUCT_NO =P00004;

END7

CONSTRAINTS

Rules which are enforced on data being entered, and prevents the user from entering invalid data into tables are called Constraints. Thus, constraints super control data being entered in tables for permanent storage. Oracle permits data constraints to be attached to table columns via SQL syntax that will check data for integrity. Even if single column of the record being entered into the table fails a constraint, entire record is rejected and not stored in the table. Helps to enforce business rules on data. Always conforms to the rule specified by the integrity constraints. Advantages of Integrity Constraints :

Do not have to program applications to check for the validity of data. Once define an integrity constraint for a table all program using that table can benefit from it. Are easy to specify and maintain. When business rule change constraint can be modified centrally.

Types of Integrity Constraints

Entity Integrity Constraints :

Ensure that each row in a table is unique.

Referential Integrity Constraints :


These constraints ensure that the values in a column of a table match the values in a related column of another table. Enforce the business rules across more than one table in a database.

Integrity constraints can be applied at two levels :


Table Constraints Column Constraints

Entity Integrity Constraints

DEFAULT constraint :

At the time of table creation a default value can be assigned to a column. When the user is loading a record with values and leaves this column empty, the Oracle engine will automatically load this column with the default value. Create Table <table name> (column_name data_type (size) [DEFAULT default_value]);

NOT NULL constraint :

When a column is defined as not null , then that column becomes a mandatory column. It implies that a value must be entered into the column if the record is to be accepted for storage in table. Create Table <table name> (column_name data_type (size) [DEFAULT default_value] [NOT NULL] );

e.g:CREATE TABLE cilent_master (client_no varchar2(6) NOT NULL, name varchar2(20) NOT NULL, address1 varchar2(30) NOT NULL, address2 varchar2(30) NOT NULL, city varchar2(15), state varchar2(15), pincode number(6), remarks varchar2(60), bal_due number(10,2));

Entity Integrity Constraints

UNIQUE constraint :
The purpose of a unique key is to be ensure that information in the column(s) is unique. Create Table <table name> (column_name data_type (size) UNIQUE); Create Table <table name> (column_name data_type (size) UNIQUE (column_name, column_name)); e.g:CREATE TABLE clinet_master (client_no varchar2(6) UNIQUE, name varchar2(20), address1 varchar2(30), address2 varchar2(30), city varchar2(15), state varchar2(15), pincode number(6), remarks varchar2(60),bal_due number(10,2));

CHECK Constraint :
Business rule validations can be applied to a table by using CHECK constraint. Create Table <table name> (column_name data_type (size) CHECK (condition)); Create Table <table name> (column_name data_type (size) CHECK (condition); e.g:

CREATE TABLE client_master (clinet_no varchar2(6) CHECK(client_no like C%), name varchar2(20) CHECK(name=upper(name)), address1 varchar2(30), address2 varchar2(30), city varchar2(15) CHECK (city IN (Delhi,Bombay,Calcutta,Madras)); state varchar2(15), pincode number(6), remarks varchar2(60), bal_due number(10,2));

Referential Integrity Constraints

PRIMARY KEY constraint :

Primary Key is one or more column(s) in a table used to uniquely identify each row in the table. A Primary Key column in a table has special attributes :

It defines the column as mandatory column i.e. the column cannot be left blank. The NOT NULL attribute is active. The data held across the column must be UNIQUE.

A single column primary key is called Simple key. A multicolumn primary key is called a composite primary key.
Create Table <table name> (column_name data_type (size) PRIMARY KEY,); Create Table <table name> (column_name data_type (size) PRIMARY KEY (column_name, column_name,);

Referential Integrity Constraints

FOREIGN KEY constraint :

Foreign key represents relationship between tables. A foreign key is a column (or a group of columns) whose values are derived from the primary key or unique key of some other table. The table in which the foreign key is defined is called a Foreign Table or Detail Table. The table that defines the primary or unique key and is referenced by the foreign key is called the Primary Table or Master Table. The master table can be referenced in the foreign key definition by using the REFERENCES adverb. If the name of column is not specified, by default, Oracle references the primary key. Create Table <table name> (column_name data_type (size) REFERENCES table_name (column, column,) ; Create Table <table name> (column_name data_type (size), FOREIGN KEY (column,) REFERENCES table_name (column, column,);

END8

Defining Integrity Constraints in the Alter table command


You can also define integrity constraints, using the constraint clause, in the ALTER TABLE command. Syntax : ADD : ALTER TABLE <tablename> ADD <constraint_definition> e.g:ALTER TABLE supplier_master ADD Primary Key (supplier_no);

MODIFY :
ALTER TABLE <tablename> MODIFY <constraint_definition>
e.g:ALTER TABLE sales_order_details ADD constraint order_fkey Foreign Key (detlorder_no) References sales_order Modify (qty_ordered number(8) Not Null);

DROP :

ALTER TABLE <tablename> DROP <constraint_definition>


e.g:ALTER TABLE supplier_master Drop Primary Key;

e.g:ALTER TABLE sales_order_details Drop Constraint fk_prno;

Assigning User Defined Name to Constraints

When constraints are defined, Oracle assigns a unique name to each constraint. The convention used by Oracle is : SYS_Cn where n is a numeric value that makes the constraint name unique. Constraint can be given user defined name along with the constraint definition. A constraint can be dropped by referring to the constraint by its name. Under this circumsta-nces a user defined constraint name becomes very convenient. If Oracle generated names are to be used, it becomes difficult to search for and identify the required constraint to be dropped. Hence user named constraints simplifies the task of dropping constraints.

Assigning User Defined Name to Constraints


A constraint can be given a user-defined name by preceding the constraint definition with the reserve word CONSTRAINT and a user-defined name. The syntax is : CONSTRAINT<constraintname> <constraintdefinition> e.g:CREATE TABLE client_master (client_no varchar2(6) CONSTRAINT p_clientkey PRIMARY KEY, name varchar2(25), address1 varchar2(15), address2 varchar2(15), city varchar2(10), pincode number(8), bal_due number(10,2));

Assignment

Create a sales_order_details table where :


Date Type varchar2 Size 6 Attributes Primary Key, Foreign Key references or order_no of sales_order table. Primary Key, Foreign Key references product_no of product_master table. Cannot be greater than qty_ordered.

Column Name detlorder_no

proederoduct_no varchar2

qty_ordered qty_disp

number number

8 8

product_rate

number

8,2

Not null.

END9

Subqueries

A subquery is form of an SQL statement that appears inside another SQL statement. It is also termed as nested query. The statement containing a subquery is called a parent query. The parent query statement uses the rows returned by the subquery.

It can be used by the following commands :


To insert records in a target table. To create tables and insert records in the table created. To update records in a target table. To create views. To provide values for conditions in WHERE, HAVING, IN etc. used with SELECT, UPDATE and DELETE statements.

Subqueries

A format of subquery can be as under :

SELECT column1, column2 from <tablename> WHERE column = (SELECT column FROM <tablename> WHERE condition) ;

e.g:Select * from sales_order Where client_no = (select client_no from client_master Where name=Rahul Desai);

Types

of Subqueries :

Single Row Subqueries Multiple Value Subqueries Multiple Column Subqueries Co-related Subqueries

Single Row Subqueries Single row subqueries returns a single value from a table. The subquery result is then compared to the value of the column (s) in the parent statement. E.g. Write a query to find out names of employees who earn less than the average salary. Solution : SELECT ename FROM emp WHERE sal < (SELECT avg (sal) FROM emp);

Multiple Value Subqueries Multiple value subqueries returns more than one value to the parent query statements from a table. The subquery result is then compared to the value the columns in the parent statements. E.g. Write a query to find out names of employees who earn maximum salary in each job. Solution : SELECT ename FROM emp WHERE sal IN (SELECT max (sal) FROM emp GROUP BY job);

Multiple Column Subqueries


Multiple column subqueries return values from more than one column. The subquery result is then compared to the value of the column (s) in the parent statement. E.g. Write a query to find out names of employees who earn maximum salary in each job. Solution : SELECT ename, job, sal FROM emp WHERE (sal, job) IN (SELECT max (sal), job FROM emp GROUP BY job);

Subqueries in Having Clause


Write a query to find out jobs having the salary less than the average salary of ANALYST. Solution : SELECT job, avg (sal) FROM emp GROUP BY job HAVING avg (sal) < (SELECT avg (sal) FROM emp WHERE job = ANALYST);

Subqueries

A Subquery is a SELECT statement that has a result which is utilized by another SQL statement. Points to remember :

The limit to level of nesting is 255 subqueries. The inner query must be enclosed in parentheses and must be on right hand side of the condition that uses its result. The ORDER BY clause can be used once with the outermost query and it should be the last clause of that SELECT statement. Subqueries are executed from the innermost to the outermost subqueries except in the case of correlated subqueries.

Correlated Subqueries

In correlated subqueries the inner query is evaluated repeatedly for each row in the result set of the parent query. Behaviour of a correlated subqueryis evaluated as follows:

Get a row from outer query. Execute the inner query using the rows value. Use the value resulting from the inner query to qualify or disqualify the row fetched from the outer query. Continue step 1 to 3 until no row from the outer query remains.

E.g. Write a query to find out employees who earn salary less than the average salary for their jobs. Sol : select ename, job, sal from emp e where sal < (select avg (sal) from emp where job = e.job);

Sol : Select ename1, dept_no from emp where dept_no IN (Select dept_no from emp where ename = Amol) AND ename IN (Select ename from inv_sys);

END10

QUERYING MULTIPLE TABLES

Multi-Table Queries

Use to retrieve data from more than one table using single query. Join

To retrieve data multi-table queries create a join between two or more tables. A join compares data in the specified, and retrieve the rows according to the result of data comparisons. Equi Join Non Equi Join Outer Join Self Join

Types of Joins :

Equi Join

Equi-join :

Joins based on an equality condition specified with the WHERE clause in the SELECT statement. Must prefix the column names with the table names followed by a period (.) to reference columns. E.g. Select E.Ename, D.Dname, E.Deptno, D.Deptno From Emp E, Dept D Where E.Deptno = D.Deptno;

Non Equi-join :

A non equi-join specifies the relationship between columns belonging to different tables by making use of the relational operator (>, <, <=, >=, < >) other than = . E.g. Select E.Name, E.Mgr, E.Sal, S.Salgrade From Emp E, Salgrade S Where E.Sal Between S.Sal And S.Hisal ;

Outer Join :

Outer join returns matching rows from both the tables and all the rows from one of the tables specified in the join. Use an outer join operator (+) with the column of the table from which you want to retrieve only the matching rows. E.g. Write a query to retrieve employee names and their respective department names and department name for which no person is employed. Select Ename, Dname, From Emp E, Dept D Where E.Deptno (+) = D.Deptno ;
Join that compares values in a single column of one table are called self join. E.g. Write a query to retrieve the names of all employees and their managers. Select E.Ename Employee, M.Ename Manager, From Emp E, Emp M, Where E.Mgr = M.Empno;

Self Join:

Set Operators

UNION Operator :

UNION operator combines the result of two queries and returns distinct rows selected by either query. UNION ALL operator displays all rows retrieve by both the queries. Duplicate values also appear in the query result. INTERSECT operator is used to retrieve rows that are common in the result set of two or more queries. MINUS operator retrieve all rows selected by the first query that are not in the second query.

UNION ALL Operator :

INTERSECT Operator :

MINUS Operator :

END11

DATABASE OBJECTS

VIEW

A view is a query that retrieves limited data derived from one or more tables in a database. Unlike table view does not physically exists in a database and does not occupy storage. Advantages of using VIEW :

Restricts access to a table or tables. Allow users to make simple queries to retrieve the results from complicated queries i.e. they hide data complexity. Show the same data to different users in different ways. They isolate applications from changes in definition of base tables .

Create or Replace View <view_name> AS Select Statement ; Insert, Update, Delete and Drop operations can be performed on views as like Table.

Create: Create View vv_sales AS select * from salesman_master; Renaming: The columns of the view can take on different names from the table columns, if required. Create View vv_clientadmin AS Select name,address1 add1,address2 add2, city, pincode, state from client_master; Select a data set from view: Once a view has been created, it can be queried exactly like a base table. Select columname, columnname from viewname; E.g:-Select name,address1,address2,city,state from vv_clientadmin Where city IN (BOMBAY,DELHI); Drop View: Drop View viewname;

Synonym

A Synonym is a database object, which is used as an alias (alternative name) for a table, view or sequence. They are used to :

Simplify SQL statements. Hide the name and owner of the object.

Users can do DML operations on synonym but cannot perform DDL operations except dropping the synonym. Syntax : CREATE SYNONYM <synonym_name> FOR <table_name>;

Sequences

A sequence is a database object, which can generate unique, sequential integer values. It can be used to automatically generate primary key values. A sequence can be in an either ascending or descending order. Syntax :

CREATE SEQUENCE <sequence_name> INCREMENT BY integervalue START WITH integervalue, MAXVALUE integervalue / NO MAXVALUE MINVALUE integervalue / NOMINVALUE CYCLE/NOCYCLE, CACHE / NOCACHE;

Create Sequence order_seq Increment By 1 Start with 1 Maxvalue 10 Minvalue 1 Cycle Cache 4; Seq. NEXTVAL, Seq.CURRVAL.

Select sequence_name.nextval from dual; E.g-Insert into sales_order (order_no,order_date,client_no) values (order_seq.nextval,sysdate,C00001); Select sequence_name.currval from dual; Alter :Alter sequence order_seq Increment by 2 Cache 30; Drop : Drop sequence sequnce_name; Drop sequence order_seq;

Keywords & Parameters

INCREMENT BY :

Specifies the interval between sequence numbers. It can be any positive or negative value but not zero. If this clause is omitted, the default value is 1. Specifies the sequence minimum value. Specifies a minimum value 1 for an ascending sequence or -(10)^26 for a descending sequence.

MINVALUE :

NOMINVALUE :

MAXVALUE :

Specifies a maximum value that a sequence can generate.


Specifies a maximum of 10^27 for an ascending sequence or -1 for a descending sequence. This is the default clause.

NOMAXVALUE :

START WITH

Specifies the first sequence number to be generated. The default for an ascending sequence is the sequence minimum value (1) and for a descending sequence, it is the maximum values (-1). Specifies that the sequence continues to generate repeat values after reaching either its maximum value. Specifies that a sequence cannot generate more values after reaching the maximum value.
Specifies how many values of a sequence ORACLE pre-allocates and keeps in memory for faster access. The minimum value for this parameter is two.

CYCLE :

NOCYCLE :

CACHE :

NOCACHE :

Specifies that values of a sequence are not pre-allocated.

ORDER :

This guarantees that sequence numbers are generated in the order of request. This is only necessary if you are using Parallel server in Parallel mode option. In exclusive mode option, a sequence always generates numbers in order.

NOORDER :

This does not guarantee sequence numbers are generated in order of request. This is only necessary if you are using Parallel Server in Parallel mode option. If the ORDER / NOORDER clause is omitted, a sequence takes the NOORDR clause by default.

Introduction to DBA (Database Administrator)

DBA refers to the person who is the database administrator and has the DBA role, while DBA refers just to those privileges encompassed by the DBA role. DBA Role :

DBA Role has all system privileges including unlimited space quotas and the ability to grant all privileges to other users.

SYSTEM is for use by a DBA user. Some of the rights that are reserved for the dba are never given to, or needed by, normal users.

Creating User

The oracle system comes with many users already created, including SYSTEM and SYS. The SYS user owns the core internal tables Oracle uses to manage the database; SYSTEM owns additional tables and views. You can log on to the SYSTEM user and MANAGER as password to create other users, since SYSTEM has that privilege. Format for creating user : CREATE USER user_name IDENTIFIED BY password; E.g. CREATE USER Disha IDENTIFIED BY Computer;

Granting & Revoking Permissions

Depending on a users status and responsibility, appropriate rights on Oracles resources can be assigned to the user. The rights that allow the use of some or all of Oracles resources on the server are called Privileges. Objects that are created by a user are owned and controlled by that user. If a user wishes to access any of the objects belonging to another user, the owner of the object will have to give permission for such access. This is called Granting of Privileges. Privileges once given can be taken back by the owner of the object. This is called Revoking of Privileges.

GRANT Statement :

The Grant statement provides various types of access to database objects such as tables, views and sequences. Syntax : GRANT {ALL | object privileges} ON object_name TO user_name [WITH GRNAT OPTION]; E.g. GRANT ALL ON bonus TO passion; GRANT SELECT, UPDATE ON bonus TO passion;

Object Privileges :

Each object privilege that is granted authorizes the grantee to perform some operation on the object. The user can grant all the privileges or grant only specific object privileges.

Object Privileges

ALTER

allows the grantee to change the table definition with the ALTER TABLE command. DELETE : allows the grantee to remove from the table with the DELETE command. INDEX : allows the grantee to create an index on the table with the CREATE INDEX command. INSERT : allows the grantee to add records to the table with the INSERT command. SELECT : allows the grantee to query the table with the SELECT statement. UPDATE : allows the grantee to modify the records in the tables with the UPDATE command. WITH : The WITH GRANT OPTION allows the GRANT OPTION grantee to in-turn grant object privileges to other users.

REVOKE Statement :

Privileges once given can be denied using the REVOKE command. The object owner can revoke privileges granted to another user. A user of an object who is not the owner, but has been granted the GRANT privilege, has the power to REVOKE the privileges from grantee. Syntax : REVOKE { ALL | object privileges } ON object_name FROM user_ name; E.g

REVOKE ALL ON bonus FROM passion;

REVOKE UPDATE ON bonus FROM passion;

END12

PL / SQL

Introduction

PL/SQL if Oracles Procedural Language (PL) superset of Structure Query Language (SQL). PL/SQL code is grouped into structures called blocks. A block of PL/SQL code contains three sections :

Declarations :

Defines and initializes the variables and cursors used in block. Executable Commands : Uses flow-control commands (such as if commands and loops) to execute the commands and assign values to the declared variables. Exception Handling : Provides customized handling of error handling.

The Declarations section starts with the keyword declare and ends when the Executable commands section starts (as indicated by the keyword begin). The Executable commands section is followed by Exception Handling Section. The exception keyword signals start of the block. The PL/SQL block is terminated by the end keyword.

The structure of a typical PL/SQL block is as follows : declare <declarations section> begin <executable commands> exception <exception handling> end;

Advantages of PL/SQL

Pl/SQL is development tool that not only supports SQL data manipulation but also provides facilities of conditional checking, branching and looping. PL/SQL sends an entire block of statements to the Oracle engine at one time. The communication between the program block and the Oracle engine reduces considerably. This in turn reduces network traffic. PL/SQL also permits dealing with errors as required, and facilities displaying user-friendly messages, when errors are encountered. PL/SQL allows declaration and use of variables in blocks of code. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without the use of the Oracle Engine. This considerable improves transaction performance. Applications written in PL/SQL are portable to any computer hardware and operating system, where Oracle is operational. Hence PL/SQL code blocks written for a DOS version of Oracle will run on its UNIX version without any modifications at all.

PL/SQL Character Set


THE CHARACTER SET : The Basic character set includes the following :

Uppercase alphabets { A Z} Lowercase alphabets { a z} Numerals ( 0 9) Symbols : ( ) + - * / < > = ! ; : . @ % , # $ ^ & _ \ { } ? [ ]

Words used in a PL/SQL block are called Lexical Units. Blank spaces can be freely insert between lexical units in a PL/SQL block. The spaces have no effect on the PL/SQL block. The Ordinary Symbols used in PL/SQL blocks are :

()+-*/<>=;%
< > != ~= ^= <= >= := ** .. || << >>

The Compound Symbols used in PL/SQL blocks are :

LITERALS : A literal is a numeric value or a character string used to represent itself. Numeric Literal :

These can be either integers or floats. If a float is being represented, then the integer part must be separated from the float part by a period. Example : 56, 7.89, 8g3, 56e-04, .1, 1., 1.e5, +67,-90 These are represented by one or more legal characters and must be enclosed within single quotes. You can represent the single quote character itself, in a string literal by writing it twice. This will not be the same as a double quote. Example : Passion Infotech, Passions POP makes the difference. These are string literals consisting of single characters. Example : &, B, A These are predetermined constants. The values it can take are :TRUE, FALSE, NULL.

String Literal :

Character Literal :

Logical (Boolean) Literal :

PL/SQL Data Types

The default data types that can be declared in PL/SQL are Number (for storing numeric value), Char (for storing character data), Date (for storing date and time data), Boolean (for storing TRUE, FALSE, NULL). Number, Char, Date data types can have NULL values. PL/SQL can use %TYPE attribute to declare variables based on definitions of column in a table. Hence, if a columns attribute change, the variables attribute will change as well. This provides for data independence, reduces maintenance costs, and allows programs to adapt to changes made to the table. %TYPE declares a variable or constant to have the same datatype as that of a previously defined variable or of a column in a table or in a view. NOT NULL causes creation of a variable or a constant that cannot have a null value.

Variables :

Variables in PL/SQL blocks are named variables. A variable name must begin with a character and can be followed by a maximum of 29 characters. Reserved words cannot be used as variable names unless enclosed within double quotes. Variable must be separated from each other by at least one space or by a punctuation mark. Assigning values to Variables : The assignment of a value to a variable can be done in two ways : Using the assignment operator := (i.e. colon followed by an equal to sign) Selecting or fetching table data values into variables.
Declaring a constant is similar to declaring a variable except that you have to add the keyword constant and immediately assign a value to it. Thereafter, no further assignments to the constants are possible, while the constant is within the scope of the PL/SQL block. PL/SQL supports the comparison between variables and constants in SQL and PL/SQL statements.

Constants :

Logical Comparison :

Displaying user Message on Screen :

Syntax : dbms_output.put_line(Message); DBMS_OUTPUT : It is a package that includes a number of procedures and functions that accumulate information in a buffer so that it can be retrieve later. These functions can be used to display message to the user. PUT_LINE : Put a piece of information in the package buffer followed by an endof-file marker. Put_line expects a single parameter of character data type.

To display message to the user the SERVEROUTPUT should be set ON. SERVEROUTPUT is a SQL *PLUS environment parameter that displays the information passed as a parameter to the PUT_LINE function.
Syntax :

SET SERVEROUTPUT ON;

Comments :
A comment can have two forms : The comment line begins with a double hyphen (--). The entire line will be treated as a comment. The comment line begins with a slash followed by an asterisk (/*) till the occurrence of an asterisk followed by a slash (*/). All lines within are treated as comments. This form of specifying comments can be used to span across multiple lines. This technique can also be used to enclose a section of a PL/SQL block that temporarily needs to be isolated and ignored.

A sample program of PL/SQL : declare a number (3); begin a := 10; dbms_output.put_line(A = ||a); end; How to run a program ? SQL> set serveroutput on; SQL> / Program will show the output like : A = 10 PL/SQL procedure successfully completed.

Conditional Control in PL/SQL

PL/SQL allows the use of IF statement to control the execution of a block of code. In PL/SQL, the IF-THEN ELSE-ELSE-END IF construct in code blocks allow specifying certain conditions under which a specific block of code should be executed. Syntax : IF <condition> THEN < Action > ELSEIF <condition> THEN < Action > ELSE < Action > END IF;

E.g:-

Declare /*Declaration of memory variables & constants to be used in the Execution section */ acc_balance number(8); acc_no varchar2(6); debit_amt number(5):=2000; min_bal constant number(5,2):=500; Begin /* Accept an account_no from the user */ acc_no:=&acc_no;

Select acc_bal into acc_balance from accounts where acc_id = acc_no; acc_balance:=acc_balance - debit_amt; If acc_balance >= min_bal then update accounts set acc_bal = acc_bal - debit_amt Where acc_id=acc_no; else dbms_output.put_line(Insufficient Balance); end if;
End;

Iterative Control

Iterative control indicates the ability to repeat or skip sections of a code block. A loop marks a sequence of statements that has to be repeated. The keyword loop has to be placed before the first statement in the sequence of statements to be repeated, while the keyword end loop is placed immediately after the last statement. PL/SQL supports following structures for iterative control : The WHILE Loop : WHILE <condition> LOOP < Action > END LOOP;

Set serveroutput on Declare pi constant number(4,2):=3.14; radius number(5); area number(14,2); begin radius:=3; While radius <=7 Loop area:=pi * power(radius,2); insert into square values(radius,area); radius:=radius+1; End loop; End;

Set serveroutput on Declare a square.num%type; sq number(2); begin a:=&a; While a <=7 Loop sq:=a * a; insert into square values(a,sq); a:=a+1; End loop; End;

The FOR Loop :


FOR variable IN [REVERSE] start .. end LOOP < Action > END LOOP;

The variable in the FOR Loop need to be declared. Also the increment value cannot be specified. The For Loop variable is always be increment by 1.

declare a number(3); b number(3); Begin a:=1; b:=&b; for a in Reverse 1..5 loop b:= b+1; dbms_output.put_line(' b='||b); End loop; End;

Variable Attribute - %Type and %Rowtype

%Type : It is used in PL/SQL to declarare a variable to be of the same type as a previously declared variable or to be of the same type as a column in table. Example: Declare
TOTBASIC SALARY.BASIC%TYPE;

(totbasic will now be of the same type as basic column from the table, salary.)

%Rowtype: It is declare a variable which is actually a record which is the same structure as a row from a table. Example:
SALREC SALARY%ROWTYPE;

(salrec is a record variable equivalent to the row from the table, salary.)

END13

Oracle Transactions

A series of one or more SQL statements that are logically related, or a series of operations performed on Oracle table data is termed as a Transaction. A transaction begins with the first executable SQL statement after a commit, rollback or connection made to the Oracle engine. Specifically, a transaction is a group of events that occurs between any of the following events :

Connecting to Oracle. Committing changes to the database.

Disconnecting from Oracle. Rollback.

Closing Transactions :

A transaction can be closed by using either a commit or rollback statement. By using these statements, table data can be changed or all changes made to the table data undone. A COMMIT ends the current transaction and makes permanent any changes made during the transaction.

Using COMMIT :

Syntax : COMMIT; Using ROLLBACK :

A ROLLBACK does exactly opposite of COMMIT. It ends the transaction but undoes any changes made during the transaction. All transaction locks acquired on tables are released. Syntax : ROLLBACK [WORK] [TO [SAVEPOINT] savepoint ]; Where : WORK : is optional and is provided for ANSI compatibility. SAVEPOINT : is optional and is used to rollback a partial transaction, as far as the specified savepoint. savepoint : is a savepoint created during the current transaction.

Creating SAVEPOINT :

SAVEPOINT marks and saves the current point in the processing of a transaction. When a SAVEPOINT is used with a ROLLBACK statement, parts of a transaction can be undone. An active savepoint is on that is specified since the last COMMIT or ROLLBACK.

Syntax : SAVEPOINT savepointname; ROLLBACK can be fired from the SQL prompt with or without the SAVEPOINT clause. A ROLLBACK operation performed without the SAVEPOINT :

Ends the transaction. Undoes all the changes in the current transaction. Erases all savepoints in that transaction. Releases the transaction locks.

A ROLLBACK operation performed with the SAVEPOINT :


A predetermined portion of the transaction is rolled back. Retains the save point rolled back to, but loses those created after the named savepoint. Releases all transactional locks that were acquired since the savepoint was taken.

Declare totsal number(9); Begin insert into worker values('E007','Mock',1000); savepoint no_update; update worker set sal= sal+2000 where name = 'Blake'; update worker set sal = sal + 1500 where name = 'Clark'; select sum(sal) into totsal from worker; if totsal>50000 then rollback to savepoint no_update; end if; commit; end;

END14

The Oracle Engine uses a work area for its internal processing in order to execute an SQL statement. This work area is private to SQLs operations and is called Cursor. The data that is stored in the cursor is called the Active Data Set. Conceptually, the size of the cursor in memory is the size required to hold the number of rows in the Active Data Set. The actual size however, is determined by the Oracles engines built in memory management capabilities and the amount of RAM available. Oracle has a pre-defined area in main memory set aside, within cursors are opened. Hence the cursors size will be limited by the size of this pre-defined area.
TYPES OF CURSORS : Cursors are classified depending on the circumstances under which they are opened. If the Oracle engine for its internal processing has opened a cursor they are known as Implicit Cursors. A user can also open a cursor for processing data as required. Such user-defined cursors are known as Explicit Cursors.

CURSORS

General Cursor Attributes

When the Oracle Engine creates an implicit or explicit cursor control variables are also created to control the execution of the cursor. Whenever any cursor is opened and used, the Oracle engine creates a set of four system variables which keeps track of the Current status of the cursor. These cursor variables can be accessed and used in a PL/SQL code block. Both Implicit and Explicit cursors have four attributes. They are described below :
Attribute Name Description Returns TRUE if cursor is open, FALSE otherwise. Returns TRUE if record was fetched successfully, FALSE otherwise. Returns TRUE if record was not fetched successfully, FALSE otherwise. Returns number of records processed from the cursor.

%ISOPEN %FOUND %NOTFOUND %ROWCOUNT

Implicit Cursor :

The Oracle Engine implicitly opens a cursor on the Server to process each SQL statement. Since the cursor is opened and managed by the Oracle internally, the function of reserving an area in memory, populating this area with appropriate data, processing the data in the memory area, releasing the memory area when the processing is complete is taken care of by the Oracle Engine.
Implicit cursor attributes can be used to access information about the status of last insert, update, delete or single-row select statements. This can be done by preceding the cursor attribute with cursor name (i.e. SQL)

Implicit Cursor Attributes :


Description The Oracle engine automatically opens and closes the SQL cursor after executing its associated select, insert, update or delete SQL statement has been processed in case of implicit cursors. Thus the SQL%ISOPEN attribute of an implicit cursor cannot be referenced outside of its SQL statement. As a result, SQL%ISOPEN always evaluated to FALSE. Evaluates to TRUE, if an insert, update or delete affected one or more rows, or a single-row select returned one or more rows. Otherwise, it evaluates to FALSE. Syntax is SQL%FOUND. Is the logical opposite to %FOUND. It evaluates to TRUE, if an insert, update or delete affected no rows, or a single-row select returns no rows. Otherwise it evaluates to FALSE. The syntax for accessing this attribute is SQL%NOTFOUND. Returns number of rows affected by an insert, update or delete or select into statement. The syntax for accessing this attribute is SQL%ROWCOUNT.

Attribute Name %ISOPEN

%FOUND

%NOTFOUND

%ROWCOUNT

Example for SQL%Found: Begin update emp set sal = sal *0.15 Where empno=&empno; If SQL%found then dbms_output.put_line('Employee Record Modified Successfully'); else dbms_output.put_line('Employee no. Does not exist'); end if; end;

Example for SQL%NOTFound:

Begin update emp set sal = sal +(sal *0.15) Where empno=&empno; If SQL%NOTfound then dbms_output.put_line('Employee no. Does not exist'); else dbms_output.put_line('Employee Record Modified Successfully'); end if; end;

Example for SQL%ROWCOUNT:

Declare rows_affected char(4); Begin update emp set sal = sal * 500 Where ename = &ename; rows_affected:= to_char(sql%rowcount); if sql%rowcount > 0 then dbms_output.put_line(rows_affected || 'Employee Record Modified Successfully'); else dbms_output.put_line('There are no Employees name as scott'); End if; End;

Explicit Cursors :

Cursor declared by the user is called Explicit Cursor. It is declared in the Declare section of the PL/SQL block and used with Executable section.
A cursor is defined in the declarative part of PL/SQL block. This is done by naming the cursor and mapping it to a query. Initialization of a cursor takes place via the open statement, this

Cursor Declaration :

The functionality of Open, Fetch and Close commands :

Defines a private SQL area named after the cursor name. Executes a query associated with the cursor which retrieves table data and populates the named private SQL area in memory i.e. creates Active Data Set. Sets the cursor row pointer in the Active Data Set to the first record.

A fetch statement then moves the data held in the Active Data set into memory variables.

The fetch statement is placed inside the Loop End Loop construct, which causes the data to be fetched into the memory variables and processed until all the rows in the Active Data Set are processed. After the fetch loop exits, the cursor must be closed with the close statement. This will release the memory occupied by the cursor and its Active Data Set. CURSOR cursor_name IS SQL Select statement ; OPEN cursor_name ;

Syntax for Declaration of a Cursor :

Syntax for Opening a Cursor :

Syntax for Fetching a record from the cursor :

FETCH cursor_name INTO variable1, variable2 ;


CLOSE cursor_name ;

Syntax for Closing a Cursor :

Explicit Cursor Attributes :


Description Evaluates to TRUE, if an explicit cursor is open; or to FALSE if it is closed. The Syntax for accessing this attribute is cursor_name %ISOPEN.

Attribute Name %ISOPEN

%FOUND

Evaluates to TRUE, if last fetch succeeded because a row was available; or to FALSE if the last fetch failed because no more rows were available. The Syntax for accessing this attribute is cursor_name%FOUND.
Is the logical opposite to %FOUND. It evaluates to TRUE, if the last fetch has failed because no more rows were available, or to FALSE, if the last fetch returned a row. The syntax for accessing this attribute is cursor_name%NOTFOUND. Returns number of rows fetched from the active data set. It is set to zero when the cursor is opened. The syntax for accessing this attribute is cursor_name%ROWCOUNT.

%NOTFOUND

%ROWCOUNT

EXAMPLE FOR CURSORNAME%ISOPEN:

Declare cursor c_emp is select empno, sal from emp where deptno =&deptno; str_emp_code emp.empno%type; num_salary emp.sal%type; Begin Open c_emp; If c_emp%isopen then loop fetch c_emp into str_emp_code, num_salary; exit when c_emp%notfound; update emp set sal = num_salary + (num_salary * .05) Where empno = str_emp_code; insert into emp_raise values(str_emp_code, sysdate, num_salary * 0.05); end loop; Commit; Close c_emp; Else dbms_output.put_line('Unable to open cursor'); end if; end;

EXAMPLE FOR CURSORNAME%FOUND:

Declare cursor c_emp is select empno, sal from emp where deptno =20; str_emp_code emp.empno%type; num_salary emp.sal%type; Begin Open c_emp; loop fetch c_emp into str_emp_code, num_salary; If c_emp %found then update emp set sal = num_salary + (num_salary * .05) Where empno = str_emp_code; insert into emp_raise values(str_emp_code, sysdate, num_salary*0.05); else exit; End if; End loop; Commit; Close c_emp; End;

EXAMPLE FOR CURSORNAME%ROWCOUNT:

Declare cursor c_emp Is select ename,deptno,sal from emp where deptno=&deptno; str_ename emp.ename%type; num_deptno emp.deptno%type; num_salary emp.sal%type; Begin Open c_emp; dbms_output.put_line('Name Department Salary'); dbms_output.put_line('----------------------'); loop fetch c_emp into str_ename, num_deptno, num_salary; exit when c_emp%rowcount = 10 or c_emp%notfound; dbms_output.put_line(str_ename||' '||num_deptno||' end loop; close c_emp; end;

'||num_salary);

END15

TRIGGERS

A Trigger consists of PL/SQL code, which defines some action that the database should take when some database related event occurs. Triggers are executed when a data manipulation command (Insert, Delete, Update) is performed on a table for which the trigger has been written. Triggers are executed automatically and are transparent to the user. In order to create a trigger, the user must have the Create trigger privilege. This privilege is part of the resource role.


1.

USE:
TO enforce rules that cannot be coded through refertial integrity. To enforce certain business rules (validation) in an application. Derive column values.
Trigger Event :DELETE , UPDATE, OR INSERT issued against the table.

2.

3.

Syntax:
Create [or replace] trigger <trigger name> [before | after] [delete | insert | update] [of column] On [user]. Tablename [Referencing {OLD AS old, NEW AS new }] [FOR EACH ROW [WHEN condition] ] Declare variable declarations; constant declarations; Begin PL/SQL subprogram body; END;

Example: CREATE TRIGGER dudu after update or delete on client_master FOR each row Declare oper varchar2(8); client_no varchar2(6); name varchar2(20); city varchar2(10); Begin If updating then oper:='update'; end if; If deleting then oper:='delete'; end if; client_no:=:old.client_no; name:=:old.name; city:=:old.city; Insert into auditclient values(client_no,name,city,oper,user,sysdate); end;

Deleting a Trigger: Syntax: DROP TRIGGER triggername; E.g:DROP TRIGGER dudu;

Functions:
Functions are also a collection of SQL and PL/SQL code which can return a value to the caller.

E.g:Create or replace function sqno(no number) return number Is Begin return no*no; end; set serveroutput on Begin dbms_output.put_line('10 square is '||sqno(10)); end; /

E.g:Create or replace function netsal(ID IN emp.empno%type) Return number IS netsal emp.sal%type; Begin Select sum(sal) into netsal from emp where empno=id; Return(netsal); End;

END16

CODDs Rules

Rule 0 :

For any system to be called an RDBMS, it must be able to manage the database through its relational capabilities.

Rule 1 : The Information Rule :

All information is explicitly and logically represented in tables as values.


Each and every data is logically accessible through a combination of table name, column name and primary key value. Inapplicable or missing information can be represented through null values. The description of database is held in the same way as ordinary data and is accessible to authorized users. There must be one language which is comprehensive in supporting data definition, data manipulation, view definition, integrity constraint, authorization and transactional control.

Rule 2 : The rule of Guaranteed Access :

Rule 3 : The Systematic Treatment of Null values :

Rule 4 : The Database Description Rule (Data Dictionary) :

Rule 5 : Comprehensive Data Sub Language :

CODDs Rules

Rule 6 : The View Updating Rule :

All views that are theoretically updatable are updated by the system. All the data manipulation commands must be operational on sets of rows having a relation rather than a single row. Application programs remain logically unimpaired whenever any changes are made in the storage representation. (e.g. If index is dropped). Application program and terminal activity remain logically unimpaired when changes of any kind that are made to the base tables (e.g. table emp is split into emp1 & emp2 & view is created as emp based on emp1, emp2. Application program is not affected by this change). All integrity constraints should be stored in the system catalog or in a database as a table.

Rule 7 : The Insert & Update Rule :

Rule 8 : The Physical Independence Rule :

Rule 9 : The Logical Data Independence Rule :

Rule 10 : The Integrity Independence Rule :

CODDs Rules

Rule 11 : The Distribution Rule :

The system must be able to access or manipulate the data that is distributed in other systems.

Rule 12 : The Non-Subversion Rule :

If an RDBMS supports a lower level language then it should not bypass any integrity constraints defined in the higher level.

Vous aimerez peut-être aussi