P. 1


|Views: 48|Likes:
Published by mousumiinder

More info:

Published by: mousumiinder on Jun 04, 2012
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






  • END1
  • END3
  • END4
  • END5
  • END6
  • END7
  • END8
  • END9
  • END10
  • END11
  • END12
  • END13
  • END14
  • END15
  • END16



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.


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.

  Oracle Graphics : Using this tool data can be represented in the form of graphs. Allows us to create a data entry screen. . Forms : This is a graphical tool used for generating and executing forms based applications. Reports : It is an application development tool of oracle for developing displaying and printing reports.


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

 SQL commands sets can be used by administrators.  Controlling access to the databases objects for security  Ensure database security.  Creating and manipulating database objects.  SQL can be used for variety of tasks.FEATURES OF SQL SQL is English Like Language.  Querying data stored in the tables.  .  SQL is non-procedural language.  Manipulating data stored in database. developers and end users alike for their varying requirements.

Alter.SQL SQL is broadly divided into three categories :  DDL (Data Definition Language) Create. Insert. Truncate DML (Data Manipulation Language) Select. Drop. Update. Delete DCL (Data Control Language) Grant. Savepoint   . Revoke. Commit. Rollback.

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

Guidelines for Writing SQL Commands An SQL command is entered at the SQL *Plus prompt.) 2) Slash (/) 3) Blank Line .  Most recent SQL or PL/SQL command is stored in SQL buffer.  Word delimiter is a space or a tab.  Buffer command can be edited or re-executed.  SQL commands can be terminated by  1) Semicolon (.  Command entry can be in upper or lower case.  SQL commands may be one line or several lines.

-Select Ename.  . e.SELECT Statements  Simplest form of SELECT Statement contains SELECT clause  FROM clause e. DeptNo from Emp.  Specifying column headers (Column Aliases)  Concatenation operator  Handling NULL values  Eliminating duplicate values.-Select * from emp.g.g.

Selected Columns and All Rows: SELECT columname. 3. SELECT columnname.SELECT Statements Simplest form of SELECT Statement contains  The „SELECT‟ SQL verb is used to view the table data. 1.columname FROM tablename. . 2.Selected Rows and All Columns: SELECT * FROM tablename WHERE search condition.AllRows and all column:  SELECT * FROM tablename.columnname FROM tablename WHERE search condition.

Elimination of duplicates from the Select statement: SELECT DISTINCT * FROM tablename. columname FROM tablename . 4. SELECT DISTINCT columnname.3. .columname [sort order].Sorting data in a table: SELECT * FROM tablename ORDER BY columnname.

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.  ASC and DESC.  ORDER BY clause should be the last clause in SELECT statement.  .

 WHERE clause must follow the FROM clause.  Condition specified after WHERE clause contains: A column name.SELECT Statements  Both DISTINCT and ORDER BY clause can not be used with SELECT statement. if used.  Condition specified with WHERE clause acts as a filter and returns only those rows that satisfy the condition. literal or list of values. A comparison operator. .  WHERE clause :  Used with SELECT statement to retrieve selected row from a table.

END1 .

Varchar2 (size) Represents fixed length characters up to the width size. . Default format is „dd-mm-yyy‟. Number Represents the floating point number with 38 significant digits precision. Represents date and time in table in fixed length in 7 bytes. The maximum width is 2000 characters. Number (p. The default width is 1 and maximum width is 255 characters. Number (Size) Represents integers of precision size.ORACLE DATA TYPES Data Type Char (size) Description Represents fixed length characters up to the width size.s) Date Represents numbers with precision of size „p‟ and numbers of digits after the decimal is „s‟.

Can not contain character sets of varying widths. BLOB BFILE Used to store large binary objects such as graphics video clips and sound files. Used to store character object with single byte characters. Only one column is allowed per table. .ORACLE DATA TYPES Data Type Long Raw Description Represents the variable length characters up to 2 GB. Long Raw CLOB Used to store binary data of variable length. which can have a maximum size off 2 GB. Table can have multiple columns. Used to store file pointers to LOBs managed by file systems external to the database. Table can have multiple columns with CLOB data type. Used to store byte oriented data like binary data or byte strings and the maximum size is 2000 bytes.

modify or remove various database objects such as table views.DATA DEFINITION LANGUAGE (DDL)  DDL is a set of SQL commands used to create.  DDL commands Create  Alter  Drop  Truncate  . synonyms etc.

g.   E. address varchar2(50)). name varchar2(20). . roll_no number (3).). CREATE TABLE student (sr_no number(2). column_name data_type(size) ….CREATING TABLES Creating Table :  CREATE TABLE statement : Syntax : CREATE TABLE <tablename> (column_name data_type (size).

Note :      When you supply values to all columns it is not necessary to have column list. it is mandatory to have a column list.INSERTING VALUES IN THE TABLE   INSERT statement : Syntax : INSERT INTO <tablename> (column. . When to supply values to specific columns. value …). column…) VALUES (value. Can be used a substitution variables to insert rows. 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.

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.

the Syntax is : Syntax : DROP TABLE <tablename>. the syntax is : Syntax : RENAME oldtablename TO newtablename DESTROYING TABLES  To destroy the table. .RENAMING TABLES  To rename a table.

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. 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>. The objects name and type are displayed.  .

columnname = expression) WHERE columnname = expression. columnname = expression).  . 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. UPDATING RECORDS CONDITIONALLY : Syntax : UPDATE <tablename> SET (columnname = expression.UPDATING THE CONTENTS OF A TABLE  The update command is used to change or modify data values in a table.

.  MODIFYING EXISTING COLUMNS : Syntax : ALTER TABLE <tablename> MODIFY (columnname newdatatype (newsize)).…….MODIFYING THE STRUCTURE OF TABLE  ADDING NEW COLUMNS : Syntax : ALTER TABLE <tablename> ADD (newcolumnname datatype(size).).

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

END3 .

the select statement used will have a „where clause‟. The Target table is one identified in the „CREATE‟ section of the SQL sentence. columnname) AS SELECT columnname. The Source table is the table identified in the „SELECT‟ section of the SQL sentence. The condition specified in the where clause must not be satisfied. .CREATING A TABLE FROM A TABLE  Syntax : CREATE TABLE <tablename> (columnname.e. This SQL sentence populates the Target table with data from the Source Table. This means the select statement in the CREATE TABLE definition must not retrieve any rows.   To create a Target table without the records from the source table (i. create the structure only). 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 . 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>.INSERTING DATA INTO A TABE FROM ANOTHER TABLE  In addition to inserting data one row at a time into a table.

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

SELECT product_no.g.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. . description. profit_percent FROM product_master WHERE profit_percent >=10 AND profit_percent <=20.

city. e. .SELECT clinet_no. address1.g. name. address2. 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. pincode FROM client_master WHERE (pincode =400054 OR pincode = 400057.

pincode FROM client_master WHERE NOT (city = „Bombay‟ or city = „Delhi‟). SELECT clinet_no.- . 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. e. address2. address1.g. name. city.

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

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

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.PATTERN MATCHING  The use of the LIKE predicate : The comparison operator discussed so far have compared one value. Two wildcard characters that are available are : For character : data types The percent sign (%) matches any string The Underscore ( _ ) matches any single character.

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

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

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

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

Output : SYSDATE -------------18-FEB-82 . 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.Example : SQL> SELECT 2 * 2 FROM dual. Example : SQL> SELECT sysdate FROM dual. It requires no arguments when selected from the table DUAL and returns the current date.

END4 .


char2) LTRIM (char. Returns char. set) RTRIM (char.char2) SUBSTR (char. with all letters in upper case. n) LPAD (char1.n. Returns char1 left padded to length n with the sequence of characters in char2. Returns a portion of char. set) Description Returns char. Returns char after final characters removed after the last character not in set. m. beginning at character „m‟ exceeding upto „n‟ characters. with all letters in lower case.char2) RPAD (char1.CHARACTER FUNCTIONS Function LOWER (char) UPPER (char) INITCAP (char) CONCAT (char1. .n. Removes characters from the left of char with initial characters removed upto the first character not in set. Returns char1 right padded to length n with the sequence of characters in char2. Returns string with the first letter in upper case. Joins char1 and char2 values in the output.

SELECT RTRIM („NISHA‟.10.4) “Substring” FROM Dual. Ltrim Rtrim Lpad Rpad Concat SELECT LTRIM („NISHA‟. .3. SELECT RPAD ( name. SELECT LENGTH („IVAN BAYROSS‟) “LENGTH” FROM Dual.‟N‟) “Left trim example” FROM Dual.‟Patil‟) “Concat” FROM Dual. SELECT SUBSTR („BAYROSS‟. SELECT LPAD („Page 1‟.‟A‟) “Right trim example” FROM Dual.‟*‟) “Lpad” FROM Dual.‟10‟. SELECT UPPER („Mr.Function Lower Upper Initcap Substr Lenghth Syntax SELECT LOWER („IVAN BAYROSS‟) “LOWER” FROM Dual. SELECT CONCAT(„Rohan‟.‟x‟) “Rpad” FROM client1_master Where name= „TURNER‟. SELECT INITCAP („IVAN BAYROSS‟) “Title Case” FROM Dual. Carol‟) FROM Dual.

END5 .

NUMBER FUNCTIONS Function ABS (n) Description Returns the absolute value of n. m) MOD (m. if n>0 the function returns 1. Returns the remainder of m divided of m divided by n. 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. the function returns -1. Returns the square root of n. if n=0 the function returns 0. n) TRUNC (n. if m is omitted then n is rounded to 0. . CEIL (n) ROUND (n. Returns m raised to the nth power. Returns e raised to the nth power. Returns n truncated to m decimal places if m is omitted to 0 places. If n<0. m) POWER (m.

SELECT SQRT(25) “Square Root” FROM dual.1) “Round” FROM dual.10) “MOD” FROM dual.2) “Raised” FROM dual.19.Function Syntax ABS POWER ROUND SQRT CEIL MOD TRUNC EXP FLOOR SELECT ABS(-15) “Absolute” FROM dual.3) “MOD” FROM dual. SELECT FLOOR(12) “FLOOR” FROM dual. SELECT POWER(3. SELECT EXP(2) “EXP” FROM dual. SELECT ROUND(15. SELECT MOD(12. SELECT CEIL(5) “CEIL” FROM dual. . SIGN SELECT SIGN(-2) “SIGN” FROM dual. SELECT TRUNC(12.

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


this will be replaced by a three-letter abbreviation for the current time zone. „this‟. 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  .TIME FUNCTION NEW_TIME (date. „other‟) : Gives the date (and time) in this time zone. other will be replaced by a three-letter abbreviation for the other time zone for which you‟d like to know the time and date.

END6 .

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.



  

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 sum of values of expr. Returns number of rows in the query MAX (expr) MIN (expr) SUM (expr) Returns maximum value of expr. Returns minimum value of expr.

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

 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.  The result of the grouped query is passed on to the HAVING clause for output filtration.HAVING CLAUSE Having clause is used to restrict the display of grouped rows.  .  Important notes :  The WHERE clause can still be used to consider the specific set of rows.


END7 .

Once define an integrity constraint for a table all program using that table can benefit from it. Even if single column of the record being entered into the table fails a constraint. . Helps to enforce business rules on data. When business rule change constraint can be modified centrally.CONSTRAINTS        Rules which are enforced on data being entered. Are easy to specify and maintain. entire record is rejected and not stored in the table. and prevents the user from entering invalid data into tables are called „Constraints‟. Always conforms to the rule specified by the integrity constraints. Thus. constraints super control data being entered in tables for permanent storage. Advantages of Integrity Constraints :     Do not have to program applications to check for the validity of data. Oracle permits data constraints to be attached to table columns via SQL syntax that will check data for integrity.

 Enforce the business rules across more than one table in a database.Types of Integrity Constraints  Entity Integrity Constraints :  Ensure that each row in a table is unique.   Integrity constraints can be applied at two levels : Table Constraints  Column Constraints  .  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.

Entity Integrity Constraints  DEFAULT constraint :   At the time of table creation a „default value‟ can be assigned to a column. It implies that a value must be entered into the column if the record is to be accepted for storage in table.  NOT NULL constraint :   When a column is defined as not null . Create Table <table name> (column_name data_type (size) [DEFAULT default_value]………). Create Table <table name> (column_name data_type (size) [DEFAULT default_value] [NOT NULL] ………). . 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. then that column becomes a mandatory column.

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

 . name varchar2(20).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 (column_name.  Create Table <table name> (column_name data_type (size) UNIQUE). column_name……)).2)). address1 varchar2(30). e. remarks varchar2(60).g:CREATE TABLE clinet_master (client_no varchar2(6) UNIQUE. city varchar2(15).bal_due number(10. state varchar2(15). address2 varchar2(30). pincode number(6).

city varchar2(15) CHECK (city IN („Delhi‟. name varchar2(20) CHECK(name=upper(name)).‟Madras‟)). bal_due number(10.‟Bombay‟. address1 varchar2(30). address2 varchar2(30). .g: CREATE TABLE client_master (clinet_no varchar2(6) CHECK(client_no like „C%‟).  Create Table <table name> (column_name data_type (size) CHECK (condition)……). pincode number(6).2)). CHECK Constraint : Business rule validations can be applied to a table by using CHECK constraint. state varchar2(15).  Create Table <table name> (column_name data_type (size) …… CHECK (condition). e.‟Calcutta‟. remarks varchar2(60).

Create Table <table name> (column_name data_type (size) …… PRIMARY KEY (column_name.e.…………). the column cannot be left blank. The NOT NULL attribute is active. A multicolumn primary key is called a composite primary key.  A single column primary key is called Simple key.……). column_name.   . The data held across the column must be UNIQUE. A Primary Key column in a table has special attributes :   It defines the column as mandatory column i.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. Create Table <table name> (column_name data_type (size) PRIMARY KEY.

column. .……). 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.Referential Integrity Constraints  FOREIGN KEY constraint :      Foreign key represents relationship between tables. Oracle references the primary key.…… FOREIGN KEY (column. by default. Create Table <table name> (column_name data_type (size) REFERENCES table_name (column. Create Table <table name> (column_name data_type (size). If the name of column is not specified. column. The master table can be referenced in the foreign key definition by using the REFERENCES adverb.………) . 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.…) REFERENCES table_name (column.

END8 .

Defining Integrity Constraints in the Alter table command    You can also define integrity constraints. . Syntax : ADD : ALTER TABLE <tablename> ADD <constraint_definition> e.g:ALTER TABLE supplier_master ADD Primary Key (supplier_no). in the ALTER TABLE command. using the constraint clause.

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

g:ALTER TABLE supplier_master Drop Primary Key. DROP : ALTER TABLE <tablename> DROP <constraint_definition> e. e. .g:ALTER TABLE sales_order_details Drop Constraint fk_prno.

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

address1 varchar2(15).  .2)). address2 varchar2(15). bal_due number(10.g:CREATE TABLE client_master (client_no varchar2(6) CONSTRAINT p_clientkey PRIMARY KEY.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. city varchar2(10). pincode number(8). name varchar2(25).

Primary Key. Foreign Key references or order_no of sales_order table. Column Name detlorder_no proederoduct_no varchar2 6 qty_ordered qty_disp number number 8 8 product_rate number 8. .2 Not null.Assignment  Create a sales_order_details table where : Date Type varchar2 Size 6 Attributes Primary Key. Cannot be greater than qty_ordered. Foreign Key references product_no of product_master table.

END9 .

To create views. IN etc. UPDATE and DELETE statements.  It can be used by the following commands :      To insert records in a target table. .Subqueries  A subquery is form of an SQL statement that appears inside another SQL statement. To update records in a target table. HAVING. The statement containing a subquery is called a parent query. To provide values for conditions in WHERE. The parent query statement uses the rows returned by the subquery. To create tables and insert records in the table created. used with SELECT. It is also termed as nested query.

Subqueries  A format of subquery can be as under :  SELECT column1.  e. column2 from <tablename> WHERE column = (SELECT column FROM <tablename> WHERE condition) . .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 .

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

 E.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.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).

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

Solution : SELECT job.Subqueries in Having Clause   Write a query to find out jobs having the salary less than the average salary of ANALYST. . avg (sal) FROM emp GROUP BY job HAVING avg (sal) < (SELECT avg (sal) FROM emp WHERE job = „ANALYST‟).

Subqueries are executed from the innermost to the outermost subqueries except in the case of correlated subqueries. 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  A Subquery is a SELECT statement that has a result which is utilized by another SQL statement.

job. Sol : select ename.Correlated Subqueries   In correlated subqueries the inner query is evaluated repeatedly for each row in the result set of the parent query. Execute the inner query using the rows value.   E. Continue step 1 to 3 until no row from the outer query remains.g. Write a query to find out employees who earn salary less than the average salary for their jobs. Behaviour of a correlated subqueryis evaluated as follows:     Get a row from outer query. .job). Use the value resulting from the inner query to qualify or disqualify the row fetched from the outer query. sal from emp e where sal < (select avg (sal) from emp where job = e.

. dept_no from emp where dept_no IN (Select dept_no from emp where ename = „Amol‟) AND ename IN (Select ename from inv_sys). Sol : Select ename1.

END10 .


Multi-Table Queries   Use to retrieve data from more than one table using single query. and retrieve the rows according to the result of data comparisons. Join   To retrieve data multi-table queries create a join between two or more tables. A join compares data in the specified. Equi – Join Non – Equi – Join Outer Join Self Join  Types of Joins :     .

D. Select E.Salgrade From Emp E.Deptno = D.g. E. D. S. .Equi – Join  Equi-join :    Joins based on an equality condition specified with the WHERE clause in the SELECT statement. Select E. E.Sal And S. E. Must prefix the column names with the table names followed by a period (.Ename. < >) other than = .Sal Between S.Deptno From Emp E.Deptno. <=. Dept D Where E.g.Dname. E. E.Sal. Salgrade S Where E. >=.) to reference columns.  Non Equi-join :   A non equi-join specifies the relationship between columns belonging to different tables by making use of the relational operator (>. <.Hisal .Mgr.Name.Deptno.

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

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 :  .Set Operators  UNION Operator :  UNION operator combines the result of two queries and returns distinct rows selected by either query.

END11 .


. They isolate applications from changes in definition of base tables . Advantages of using VIEW :     Restricts access to a table or tables. Show the same data to different users in different ways. Update. Allow users to make simple queries to retrieve the results from complicated queries i.VIEW    A view is a query that retrieves limited data derived from one or more tables in a database. they hide data complexity. Unlike table view does not physically exists in a database and does not occupy storage.e. Insert.   Create or Replace View <view_name> AS Select Statement . Delete and Drop operations can be performed on views as like Table.

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

. view or sequence. Syntax : CREATE SYNONYM <synonym_name> FOR <table_name>. which is used as an alias (alternative name) for a table. They are used to :   Simplify SQL statements.Synonym   A Synonym is a database object.   Users can do DML operations on synonym but cannot perform DDL operations except dropping the synonym. Hide the name and owner of the object.

. A sequence can be in an either ascending or descending order. Syntax : CREATE SEQUENCE <sequence_name> INCREMENT BY integervalue START WITH integervalue.CURRVAL. sequential integer values. Seq.   Create Sequence order_seq Increment By 1 Start with 1 Maxvalue 10 Minvalue 1 Cycle Cache 4. which can generate unique.Sequences     A sequence is a database object. MAXVALUE integervalue / NO MAXVALUE MINVALUE integervalue / NOMINVALUE CYCLE/NOCYCLE. Seq. It can be used to automatically generate primary key values. NEXTVAL. CACHE / NOCACHE.

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


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.

 



 


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.



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.




In exclusive mode option.  NOORDER :  This does not guarantee sequence numbers are generated in order of request. .  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. NOCACHE :  Specifies that values of a sequence are not pre-allocated. If the ORDER / NOORDER clause is omitted. a sequence always generates numbers in order. This is only necessary if you are using Parallel server in Parallel mode option. a sequence takes the NOORDR clause by default.

 SYSTEM is for use by a DBA user.Introduction to DBA (Database Administrator)   DBA refers to the person who is the database administrator and has the DBA role. or needed by. DBA Role :  DBA Role has all system privileges – including unlimited space quotas – and the ability to grant all privileges to other users. . while DBA refers just to those privileges encompassed by the DBA role. normal users. Some of the rights that are reserved for the dba are never given to.

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

Granting & Revoking Permissions  Depending on a user‟s status and responsibility.   . This is called Revoking of Privileges. appropriate rights on Oracle‟s resources can be assigned to the user. This is called Granting of Privileges. The rights that allow the use of some or all of Oracle‟s resources on the server are called Privileges. 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. Objects that are created by a user are owned and controlled by that user. Privileges once given can be taken back by the owner of the object.

g. 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. GRANT SELECT. Syntax : GRANT {ALL | object privileges} ON object_name TO user_name [WITH GRNAT OPTION]. . E. views and sequences. GRANT ALL ON bonus TO passion. GRANT Statement :     The Grant statement provides various types of access to database objects such as tables.

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

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

END12 .

PL / SQL .

The PL/SQL block is terminated by the end keyword. A block of PL/SQL code contains three sections :  Declarations :   Defines and initializes the variables and cursors used in block. PL/SQL code is grouped into structures called blocks. Exception Handling : Provides customized handling of error handling. The exception keyword signals start of the block. The Executable commands section is followed by Exception Handling Section. Executable Commands : Uses flow-control commands (such as if commands and loops) to execute the commands and assign values to the declared variables.Introduction    PL/SQL if Oracle‟s Procedural Language (PL) superset of Structure Query Language (SQL).    The Declarations section starts with the keyword declare and ends when the Executable commands section starts (as indicated by the keyword begin). .

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

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

„ @ % .* / < > = ! . “ # $ ^ & _ \ { } ? [ ]  Words used in a PL/SQL block are called Lexical Units. || << >> The Compound Symbols used in PL/SQL blocks are :  .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 : ( ) + .%„“ < > != ~= ^= <= >= := ** .. The spaces have no effect on the PL/SQL block. : . Blank spaces can be freely insert between lexical units in a PL/SQL block. The Ordinary Symbols used in PL/SQL blocks are :    ()+-*/<>=.

then the integer part must be separated from the float part by a period.89.1. „A‟ These are predetermined constants.. If a float is being represented.   LITERALS : A literal is a numeric value or a character string used to represent itself.‟ These are string literals consisting of single characters. +67. 8g3. 56e-04. You can represent the single quote character itself. . This will not be the same as a double quote.  String Literal :    Character Literal :    Logical (Boolean) Literal :  . Example : „Passion Infotech‟. FALSE.e5. NULL. 1. in a string literal by writing it twice.-90 These are represented by one or more legal characters and must be enclosed within single quotes. „B‟. 1. The values it can take are :TRUE. Example : 56. Example : „&‟. „Passion‟‟s POP makes the difference. Numeric Literal :   These can be either integers or floats. 7.

PL/SQL can use %TYPE attribute to declare variables based on definitions of column in a table. reduces maintenance costs.PL/SQL Data Types     The default data types that can be declared in PL/SQL are Number (for storing numeric value). Date data types can have NULL values. if a column‟s attribute change. and allows programs to adapt to changes made to the table. This provides for data independence. . %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. the variable‟s attribute will change as well. NOT NULL causes creation of a variable or a constant that cannot have a null value. Date (for storing date and time data). Boolean (for storing TRUE. Number. Char (for storing character data). FALSE. NULL). Hence. Char.

 Constants :   Logical Comparison :  .e. 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. Variable must be separated from each other by at least one space or by a punctuation mark. colon followed by an equal to sign)  Selecting or fetching table data values into variables. Assigning values to Variables : The assignment of a value to a variable can be done in two ways :  Using the assignment operator := (i. Reserved words cannot be used as variable names unless enclosed within double quotes. PL/SQL supports the comparison between variables and constants in SQL and PL/SQL statements. Thereafter. Variables :    Variables in PL/SQL blocks are named variables. while the constant is within the scope of the PL/SQL block. no further assignments to the constants are possible. A variable name must begin with a character and can be followed by a maximum of 29 characters.

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. These functions can be used to display message to the user. SERVEROUTPUT is a SQL *PLUS environment parameter that displays the information passed as a parameter to the PUT_LINE function. Displaying user Message on Screen :  Syntax : dbms_output.put_line(„Message‟). Syntax :   SET SERVEROUTPUT ON. 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. .

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

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

Syntax : IF <condition> THEN < Action > ELSEIF <condition> THEN < Action > ELSE < Action > END IF.  .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.

else dbms_output.E.2):=500. . min_bal constant number(5.put_line(“Insufficient Balance”).debit_amt Where acc_id=acc_no. Begin /* Accept an account_no from the user */ acc_no:=&acc_no.debit_amt. Select acc_bal into acc_balance from accounts where acc_id = acc_no. acc_no varchar2(6).g:- Declare /*Declaration of memory variables & constants to be used in the Execution section */ acc_balance number(8). End. debit_amt number(5):=2000. If acc_balance >= min_bal then update accounts set acc_bal = acc_bal . acc_balance:=acc_balance . end if.

A loop marks a sequence of statements that has to be repeated.   .Iterative Control  Iterative control indicates the ability to repeat or skip sections of a code block. 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.

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

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

end LOOP < Action > END LOOP.. The FOR Loop : FOR variable IN [REVERSE] start .  The variable in the FOR Loop need to be declared. . The For Loop variable is always be increment by 1. Also the increment value cannot be specified.

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

Example: Declare TOTBASIC SALARY. (totbasic will now be of the same type as basic column from the table.) .Variable Attribute .BASIC%TYPE.%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. salary.

) . %Rowtype: It is declare a variable which is actually a record which is the same structure as a row from a table. salary. Example: SALREC SALARY%ROWTYPE. (salrec is a record variable equivalent to the row from the table.

END13 .

 Closing Transactions :  A transaction can be closed by using either a commit or rollback statement. A COMMIT ends the current transaction and makes permanent any changes made during the transaction. a transaction is a group of events that occurs between any of the following events :   Connecting to Oracle. or a series of operations performed on Oracle table data is termed as a Transaction. table data can be changed or all changes made to the table data undone. Rollback. By using these statements.  Using COMMIT :  . Committing changes to the database. Specifically.Oracle Transactions    A series of one or more SQL statements that are logically related.   Disconnecting from Oracle. rollback or connection made to the Oracle engine. A transaction begins with the first executable SQL statement after a 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 data that is stored in the cursor is called the Active Data Set. The actual size however. Hence the cursor‟s size will be limited by the size of this pre-defined area.  The Oracle Engine uses a work area for its internal processing in order to execute an SQL statement. If the Oracle engine for its internal processing has opened a cursor they are known as „Implicit Cursors‟. Conceptually. TYPES OF CURSORS : Cursors are classified depending on the circumstances under which they are opened. within cursors are opened. Oracle has a pre-defined area in main memory set aside. Such user-defined cursors are known as „Explicit Cursors. is determined by the Oracle‟s engine‟s built in memory management capabilities and the amount of RAM available. This work area is private to SQL‟s operations and is called Cursor. the size of the cursor in memory is the size required to hold the number of rows in the Active Data Set. CURSORS   . A user can also open a cursor for processing data as required.

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. These cursor variables can be accessed and used in a PL/SQL code block. Both Implicit and Explicit cursors have four attributes. FALSE otherwise. the Oracle engine creates a set of four system variables which keeps track of the „Current‟ status of the cursor. Returns TRUE if record was not fetched successfully. FALSE otherwise. FALSE otherwise. Whenever any cursor is opened and used. They are described below : Attribute Name Description Returns TRUE if cursor is open. Returns number of records processed from the cursor. Returns TRUE if record was fetched successfully. %ISOPEN %FOUND %NOTFOUND %ROWCOUNT .

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

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

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

 Example for SQL%NOTFound: Begin update emp set sal = sal +(sal *0. Does not exist'). If SQL%NOTfound then dbms_output. end if.put_line('Employee no.15) Where empno=&empno.put_line('Employee Record Modified Successfully'). end. else dbms_output. .

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

Initialization of a cursor takes place via the open statement. creates Active Data Set. Fetch and Close commands :  Defines a private SQL area named after the cursor name. This is done by naming the cursor and mapping it to a query. Sets the cursor row pointer in the Active Data Set to the first record. Explicit Cursors :   Cursor declared by the user is called Explicit Cursor. this     Cursor Declaration :   The functionality of Open. It is declared in the Declare section of the PL/SQL block and used with Executable section. Executes a query associated with the cursor which retrieves table data and populates the named private SQL area in memory i. . A cursor is defined in the declarative part of PL/SQL block.e.  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


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.




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;

empno%type. .05) Where empno = str_emp_code. num_salary*0. End if. Commit. num_salary. End loop. If c_emp %found then update emp set sal = num_salary + (num_salary * . insert into emp_raise values(str_emp_code. Begin Open c_emp. else exit. End. loop fetch c_emp into str_emp_code. num_salary emp. EXAMPLE FOR CURSORNAME%FOUND: Declare cursor c_emp is select empno. sal from emp where deptno =20.05). str_emp_code emp.sal%type. Close c_emp. sysdate.

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

END15 .

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

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

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

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

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

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

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

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

END16 .

data manipulation. Each and every data is logically accessible through a combination of table name. Inapplicable or missing information can be represented through null values. authorization and transactional control. it must be able to manage the database through its relational capabilities. 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 :  .CODD’s Rules  Rule 0 :  For any system to be called an RDBMS. view definition. integrity constraint. The description of database is held in the same way as ordinary data and is accessible to authorized users. column name and primary key value. There must be one language which is comprehensive in supporting data definition.   Rule 1 : The Information Rule :  All information is explicitly and logically represented in tables as values.

table emp is split into emp1 & emp2 & view is created as emp based on emp1. All integrity constraints should be stored in the system catalog or in a database as a table. All the data manipulation commands must be operational on sets of rows having a relation rather than a single row. Application program is not affected by this change). Application programs remain logically unimpaired whenever any changes are made in the storage representation. emp2. If index is dropped).g. (e.CODD’s Rules   Rule 6 : The View Updating Rule :  All views that are theoretically updatable are updated by the system. Application program and terminal activity remain logically unimpaired when changes of any kind that are made to the base tables (e.g. 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 :  .

CODD’s 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. .

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)//-->