Sie sind auf Seite 1von 97

COLLEGE OF ENGINEERING

THIRUVANANTHAPURAM

DEPARTMENT OF COMPUTER APPLICATIONS

DATABASE MANAGEMENT SYSTEMS


LABORATORY REFERENCE MANUAL
YEAR 2006-2009

INDEX
TOPIC PAGE NUMBER

INTRODUCTION TO DBMS--------------------------------------------------------------------------------06 TERMINOLOGIES--------------------------------------------------------------------------------------------07

SQL
BASIC SQL OPERATIONS----------------------------------------------------------------------------------08 DDL----------------------------------------------------------------------------------------------------08 CREATE TABLE-------------------------------------------------------------------------08 ALTER TABLE---------------------------------------------------------------------------09 DROP TABLE-----------------------------------------------------------------------------09 TRUNCATE TABLE---------------------------------------------------------------------09 DESC COMMAND-----------------------------------------------------------------------10 DML---------------------------------------------------------------------------------------------------10 SELECT------------------------------------------------------------------------------------10 UPDATE-----------------------------------------------------------------------------------12 INSERT------------------------------------------------------------------------------------12 DELETE-----------------------------------------------------------------------------------13 TCL---------------------------------------------------------------------------------------------------13 COMMIT----------------------------------------------------------------------------------13 SAVEPOINT------------------------------------------------------------------------------13 ROLLBACK------------------------------------------------------------------------------14 DCL---------------------------------------------------------------------------------------------------14 GRANT------------------------------------------------------------------------------------14 REVOKE----------------------------------------------------------------------------------14 OPERATORS IN SQL----------------------------------------------------------------------------------------15 ARITHMETIC---------------------------------------------------------------------------------------15 COMPARISON-------------------------------------------------------------------------------------15 LOGICAL--------------------------------------------------------------------------------------------15 FUNCTIONS IN SQL-----------------------------------------------------------------------------------------16 SINGLE ROW FUNCTIONS---------------------------------------------------------------------16 DATE FUNCTIONS---------------------------------------------------------------------16 CHARACTER FUNCTIONS-----------------------------------------------------------17 NUMERIC FUNCTIONS---------------------------------------------------------------17 CONVERSION FUNCTIONS---------------------------------------------------------18 MISCELLANEOUS FUNCTIONS---------------------------------------------------18 GROUP FUNCTIONS-----------------------------------------------------------------------------18 SET OPERATORS--------------------------------------------------------------------------------------------19 JOIN-------------------------------------------------------------------------------------------------------------20 SIMPLE JOIN---------------------------------------------------------------------------------------20

Page 2

EQUI-JOIN-------------------------------------------------------------------------------20 NON EQUI-JOIN------------------------------------------------------------------------20 SELF JOIN------------------------------------------------------------------------------------------20 OUTER JOIN---------------------------------------------------------------------------------------21 SUBQUERIES-------------------------------------------------------------------------------------------------22 INTEGRITY CONSTRAINTS------------------------------------------------------------------------------23 DOMAIN INTEGRITY CONSTRAINT--------------------------------------------------------23 NOT NULL-------------------------------------------------------------------------------23 CHECK------------------------------------------------------------------------------------23 ENTITY INTEGRITY CONSTRAINT---------------------------------------------------------24 UNIQUE KEY---------------------------------------------------------------------------24 PRIMARY KEY-------------------------------------------------------------------------24 REFERENTIAL INTEGRITY CONSTRAINT------------------------------------------------24 FOREIGN KEY--------------------------------------------------------------------------24 VIEWS----------------------------------------------------------------------------------------------------------25 ASSERTIONS-------------------------------------------------------------------------------------------------26

PL/SQL
FUNDAMENTALS & BLOCK STRUCTURE-----------------------------------------------------------27 DATA TYPES--------------------------------------------------------------------------------------------------28 SCALAR---------------------------------------------------------------------------------------------28 COMPOSITE----------------------------------------------------------------------------------------29 USER DEFINED DATA TYPES----------------------------------------------------------------------------31 %TYPE-----------------------------------------------------------------------------------------------31 %ROWTYPE----------------------------------------------------------------------------------------32 LOGICAL COMPARISON----------------------------------------------------------------------------------32 CONTROL STRUCTURES----------------------------------------------------------------------------------32 CONDITIONAL CONTROL----------------------------------------------------------------------32 IF THEN-----------------------------------------------------------------------------------32 IF THEN ELSE---------------------------------------------------------------------------32 IF THEN ELSIF -------------------------------------------------------------------------32 ITERATIVE CONTROL---------------------------------------------------------------------------33 SIMPLE LOOP---------------------------------------------------------------------------33 WHILE LOOP----------------------------------------------------------------------------33 FOR LOOP--------------------------------------------------------------------------------34 SEQUENTIAL CONTROL------------------------------------------------------------------------34 GO TO--------------------------------------------------------------------------------------34 ERROR HANDLING(EXCEPTION HANDLING)-------------------------------------------------------35 PREDEFINED EXCEPTION----------------------------------------------------------------------35 USER DEFINED EXCEPTION-------------------------------------------------------------------35 SQL IN PL/SQL------------------------------------------------------------------------------------------------36 CURSOR MANAGEMENT----------------------------------------------------------------------------------37
Page 3

STATIC CURSOR----------------------------------------------------------------------------------37 EXPLICIT CURSOR---------------------------------------------------------------------38 IMPLICIT CURSOR---------------------------------------------------------------------39 CURSOR FOR LOOP-------------------------------------------------------------------------------39 REF CURSOR---------------------------------------------------------------------------------------39 STRONG CURSOR----------------------------------------------------------------------40 WEAK CURSOR-------------------------------------------------------------------------40 SUBPROGRAMS----------------------------------------------------------------------------------------------41 PROCEDURES--------------------------------------------------------------------------------------41 PARAMETER MODES-----------------------------------------------------------------43 FUNCTIONS-----------------------------------------------------------------------------------------44 PACKAGES-----------------------------------------------------------------------------------------------------45 TRIGGERS------------------------------------------------------------------------------------------------------47 BUILT-IN PACKAGES---------------------------------------------------------------------------------------49

PRO*C
OVERVIEW----------------------------------------------------------------------------------------------------51 PRO*C SYNTAX----------------------------------------------------------------------------------------------51 SQL---------------------------------------------------------------------------------------------------51 PREPROCESSOR DIRECTIVES----------------------------------------------------------------51 STATEMENT LABELS---------------------------------------------------------------------------51 HOST VARIABLES-------------------------------------------------------------------------------------------52 BASICS ----------------------------------------------------------------------------------------------52 POINTERS-------------------------------------------------------------------------------------------52 STRUCTURES--------------------------------------------------------------------------------------52 ARRAYS---------------------------------------------------------------------------------------------52 INDICATOR VARIABLES-----------------------------------------------------------------------53 ERROR HANDLING------------------------------------------------------------------------------------------53 WHENEVER STATEMENT----------------------------------------------------------------------53

APPENDIX A ALGORITHMS & SOLVED QUESTIONS SQL SECTION---------------------------------------------------------------------------------------------55


RELATIONS USED IN SQL QUERIES--------------------------------------------------------------------55 RELATIONS & CONSTRAINTS ON ATTRIBUTES---------------------------------------------------57 QUERIES--------------------------------------------------------------------------------------------------------58

PL/SQL SECTION
EXPERIMENT-1-(VERIFY WHETHER THE TRIANGLE IS FORMED OR NOT)---------------66 EXPERIMENT-2(SWAP TWO VARIABLES)---------------------------------------------------------67 EXPERIMENT-3(SUM OF DIGITS OF A GIVEN NUMBER)-------------------------------------68

Page 4

EXPERIMENT-4(SUM OF ODD NUMBERS BELOW A GIVEN NUMBER)------------------69 EXPERIMENT-5(LARGEST AND SMALLEST AMONG TWO NUMBERS)------------------70 EXPERIMENT-6(COMPUTE THE GROSS SALARY GIVEN EMPLOYEE ID)---------------72 EXPERIMENT-7(FIBONACCI SERIES BELOW A GIVEN NUMBER)-------------------------73 EXPERIMENT-8(FACTORIAL OF A NUMBER)----------------------------------------------------74 EXPERIMENT-9(PREPARE ELECTRICITY BILL)-------------------------------------------------75 EXPERIMENT-10(CHECK FOR LIBRARY MEMBERSHIP EXPIRY)--------------------------78 EXPERIMENT-11(COMMISSION FOR SALESMAN)----------------------------------------------80 EXPERIMENT-12(EMPLOYEE DETAILS USING CURSOR)-------------------------------------83 EXPERIMENT-13(EVALUATE STUDENT GRADE USING PROCEDURE)-------------------84 EXPERIMENT-14(SALARY INCREMENT USING PROCEDURE)------------------------------85 EXPERIMENT-15(EVALUATE STUDENT GRADE USING FUNCTION)---------------------86 EXPERIMENT-16(TRIGGER ON EMPLOYEE TABLE)-------------------------------------------88 EXPERIMENT-17(REPORT GENERATION)---------------------------------------------------------89

APPENDIX B EXERCISES------------------------------------------------------------------------------------------------92 EXAMINATION QUESTIONS--------------------------------------------------------------------94 APPENDIX C SYLABUS ---------------------------------------------------------------------------------------------------96

Page 5

INTRODUCTION
DATA BASE MANAGEMENT SYSTEM A database management system (DBMS) is a collection of interrelated data and a set of programs to access those data .The primary goal of DBMS is to provide a way to store and retrieve database information that is both convenient and efficient. The DBMS is hence a general purpose software system that facilitates the process of i) defining , ii) constructing and iii) manipulating database for various application . Defining a database involve specifying the data type, structures and the constraints for the data to be stored in the database. Constructing the database is the process of storing the data itself on some storage medium that is controlled by DBMS. Manipulating a database include such function as querying the database to retrieve specific data , updating the database to reflect changes in the mini world and generalizing report from the data. Need for Database Systems DBMS has been developed to overcome the disadvantages with the conventional systems like file-processing system, viz. i) Data redundancy and inconsistency ii) Difficulty in accessing data iii) Data isolation iv) Integrity problems v) Atomicity problems vi) Concurrent-access anomalies vii) Security problems

Page 6

TERMINOLOGIES Context area is an area of memory allocated for the processing of SQL statements. It contains the various information to complete the processing. Active set is the set of rows returned by a query. The cursor will point to the current row in the active set. Table aliases are used to make multiple table queries shorter and more readable. We give an alias to the table in the from clause. The alias can be used instead of table name throughout the query. Persistent objects are objects stored in the database. They can be used with SQL and PL/SQL. They are available to the user until they are explicitly deleted. Eg: tables, columns etc. Transient objects are objects which exist only within the scope of the PL/SQL block. They get deallocated when go out of the PL/SQL block. Eg:- PL/SQL variables Records a set of data about a person, place or event, or some other item. Table data is atored in records (rows) in the database. Each record is composed of a set of related fields, each field defining one attribute of informationfor the record. Taken together, a record defines one specific unit of retrievable information in a database. Tables the basic unit of data storage in a relational database. A table stores data in records (rows) and fields (columns) and is usually about a particular category of things, such as employees or parts. Also called a base table. A table-type Recordset is a logical representation of a base table in a database. Database engine that part of the database system that retrieves data from and stores data in user and system databases. Date data type a data type used to store dates and times as real number. Date variables are stored as 64-bit (8 byte numbers). The value to the left of the decimal represents a date, and the value to the right of the decimal represents a time. Dynaset a type of recordset object that returns a dynamic set of pointers to live database data. Like a table- or a snapshot- type Recordset, a dynaset returns data in records (rows) and fields (columns). Unlike a table-type Recordset, a dynasettype Recordset can be the result of a query that joins two or more tables.

Page 7

SQL (STRUCTURED QUERY LANGUAGE)


SQL SQL is the standard relational database language. It includes features for defining the structure of the data, modifying data in the database and for specifying security constraints. SQL language has the following parts: * Data definition language (DDL) * Data manipulation language (DML) * Transaction control language (TCL) * Data control language (DCL) BASIC SQL OPERATION SQL statements can be grouped into four general categories: Data definition language (DDL), Data manipulation language (DML), Transaction control language (TCL), Data control language (DCL). 1. DATA DEFINITION LANGUAGE (DDL) The overall design of a database is called the database schema. A database schema is specified by a set of definitions that are expressed using a data definition language. It is used for structuring the database. We use the data definition language statements CREATE, ALTER, DROP, TRUNCATE to create new objects, alter the structure of existing objects, completely remove objects from system, or delete all rows permanently from the table leaving the structure of the table. CREATE TABLE COMMAND Create table command creates a table, the basic structure to hold user data, specifying this information such as column definitions, integrity constraints, the table's tablespace, storage characteristics, an optional cluster, data from an arbitrary query. Syntax: create table <table name> (column definition1, column definition2, , ); Example: create table vendor_master( vencode varchar2(5), venname varchar2(20), venaddr varchar2(20)); Note In a table, we should specify i) a unique column name ii) proper data type along with its width

Page 8

While naming a table, i) First letter should be an alphabet ii) Reserved words cannot be used to name a table iii) Maximum length for a table name is 30 character iv) Table name should also be unique v) Underscore, numerals and letters are allowed but not blank space and single quotes Output of the command- Table created ALTER TABLE COMMAND This command is used to change the structure of a table. This may be either to modify an existing attribute characteristic or to add a new attribute. Syntax: alter table <table name> modify (column definition..); alter table <table name> add (column definition..); This command is useful when a user wants to add a new column change the width of a data type or the data type itself include or drop integrity constraints Example: alter table vendor_master modify (venname varchar2 (25)); alter table vendor_master add (tel_no number (6)); Output of the command is Table altered DROP TABLE COMMAND This command is used to drop a table. Syntax: drop table <table name> Example: drop table vendor_master; TRUNCATE TABLE COMMAND This command is to delete the records in the table, while retaining the structure of the table. Syntax: truncate table <table name> Example: truncate table vendor_master;

Page 9

Output of the command is Table truncated

DESC COMMAND This command is used to view the structure of the table. Syntax: desc <table name>; Example: desc vendor_master; Output of the command is- a list of the columns of the table along with their data types. NAME --------VENCODE VENNAME VENADDR TEL_NO TYPE --------VARCHAR2 (5) VARCHAR2 (25) VARCHAR2 (20) NUMBER (6)

2. DATA MANIPULATION LANGUAGE (DML) These commands are the most frequently used SQL commands. They are used to query and manipulate existing objects like tables. DML commands are: SELECT, UPDATE, INSERT, DELETE SELECT STATEMENT Select command is used t retrieve information stored in the table. Syntax: select <column name> from <table name>; Example: Select * from vendor_master; Note i) ii)

// Selects all the columns of the table

we can either display all the columns in a table or only specific columns The order of the column names in the select command gives the order in which they should be displayed

VARIATIONS OF SELECT STATEMENT 1) Selecting distinct rows To exclude duplicate rows Example: select distinct vencode from vendor_master; 2) Select command with where clause

Page 10

To select specific rows or records which satisfy some specific conditions, we can use where clause in the select command. It can be followed by the condition and the optional order by clause, to display the rows in a pre defined order.

Syntax: select <columns> from <table name> where <conditions> [order by]; Example: Select * from vendor_master where vencode=v004 order by date; Note order by should be the last clause in a select statement Different statements: Select command can be used along with some DDL and DML statements to perform some more operations. Some of them are:Select command to create a table We can include a select clause in a create table command to create table and copy the records into it. Syntax: create table <table name> as select <column names> from <existing table name>; Example: create table vendor_details as select * from vendor_master; Note: where clause can be included to create table with those records which satisfy the where condition Example: create table list as select * from student_details where age>25; Select command to insert records This command either create a table or consider an existing table prior to insertion, with the same structure as the other table and then performs the insertion command. Syntax: insert in to <table name> (select column_name from <existing table name>); Example: insert in to order copy(select * from order master); Select command for column aliases It can be used to change the column name temporarily, when the query result is displayed. Syntax: select column_name <alias name> from table_name; Example:
Page 11

select vencode id from vendor;

Output will be

id ----v001 v002

UPDATE STATEMENT Update command is used to update rows in the table. One or more columns can be updated. Syntax: update <table name> set field = value, where condition; Note i) update command contains set clause ii) it also contains optional where clause to update specific rows based on a specific condition mentioned Example: update vendor_master set tel_no=89776 where vencode=v003; Output of the command 1 Row updated INSERT STATEMENT This command is used to add one or more rows to a table. Note i)

ii) iii) Syntax: insert in to <table name> values ( a list of data values); Example: insert in to vendor_master values(v001, Madhu, Pala, 23456); Multiple records can be entered using a single insert command. Example: insert in to vendor_master values (&vencode, &venname, &venaddr, &tel_no); This will prompt the user to enter values for all the columns in the table. Enter the value for vencode: v001 Enter the value for venname: Jose Enter the value for venaddr: Tdpa Enter the value for tel_no: 54232

While using this command, values are separated by commas and data types varchar2, char raw, long and dates are enclosed in single quotes. The values must be entered in the same order as they are defined in the table Values can also be entered in to only specific columns and not all columns.

Some of the columns can be omitted. Here the necessary columns should have to be explicitly specified in the insert statement. Syntax:
Page 12

insert in to <table name> (column names) values (list of values); Example: insert in to vendor_master (vencode, venname, tel_no) values(v002, Arun, 98765); This can be done in another way by specifying null. Example: insert in to vendor_master values(v002, Arun, null, 56743); Output of the command- 1 row updated Important Inserting date is similar to inserting character values. i.e. by enclosing it within quotes. The standard format for the date data type is DD-MON-YY. Example: 25-jun-05 DELETE STATEMENT This command is used to delete records or rows from the table. Syntax: delete from <table name> where conditions; Note i) ii) iii) iv)

it contains a from clause it also contains an optional where clause One or morea rows can be deleted( even all rows can be deleted) To delete specific rows from the table, we can use the where clause with appropriate conditions. Example: delete from vendor_master where vencode=v002; Output of the command- 1 row deleted

3. TRANSACTION CONTROL LANGUAGE (TCL) The changes made to the database are known as transaction. Transactions can be made permanent to a database by commit. The various commands in TCL are COMMIT SAVEPOINT ROLLBACK COMMIT COMMAND Transaction changes can be made permanent to the database by commit command. Syntax: commit work; or commit; SAVEPOINT COMMAND

Page 13

These are markers to divide a very lengthy transaction into smaller ones. They are used to identify a point in a transaction to which we can later roll back. This is used along with roll back. Syntax: savepoint savepoint_id; ROLLBACK It is used to undo the work done in th ecurrent transaction. We can either rollback the entire transaction or to a savepoint so that statements after the savepoint are rolled back. Syntax to rollback the entire transaction: rollback work; or rollback; Syntax to rollback to a particular stage in a transaction: rollback to savepoint save_pt; where save_pt is the savepoint. 4. DATA CONTROL LANGUAGE (DCL) DCL statements are used for securing the database. DCL statements such as GRANT, REVOKE control access to database and affirm or revoke database transactions. It provides the user with privilege commands. The owner of the database can grant privileges or withdraw (revoke) privilege to other database users so that they can perform the operations accordingly on the tables. GRANT PRIVILEGE COMMAND The Database Administrator (DBA) has all the privileges. A DBA can create users, assign them privileges, and even drop users. An object privilege specifies what a user can do with a database object such as a table, a sequence, or a view. The privileges are granted using GRANT statement. Syntax: grant privileges on <object_name> to <username>; Example: grant select, update on vendor_master to warehouse; grant update(qty_hand, re_level) on itemfile to warehouse; Note i) We can use all to grant all privileges ii) With grant option can be added with grant command so that they are getting the privilege to grant privileges. Output of the command grant succeeded REVOKE PRIVILEGE COMMAND The privileges, once granted, can be taken away. REVOKE statement takes privileges not only from the grantee but also from users who are granted privileges by the grantee. Syntax:
Page 14

revoke privileges on <object_name> from <username>; Example: revoke select, update on vendor_master from warehouse; Output of the command revoke succeeded OPERATORS IN SQL The operators supported by SQL are Arithmetic operators Comparison operators Logical operators Arithmetic Operators These operators are used to perform calculations based on number values. An arithmetic expression consists of column names with number data types and an arithmetic operator connecting them. The various arithmetic operators are:

+, -, *, /
Example: select itemdesc, itemrate*(max_level-qty_hand)+ itemrate*re_level from itemfile where p_category=spares; If there is more than one operator in the expression, then their precedence should be considered. Comparison Operators These are used for comparison of expressions. The various comparison operators are:

=, !=, <, >, <=, >=,


between ( to check between any two values) in (to match with any of the values in the list) like (to match a character pattern) isNull (to check whether it is Null) Example: select name from student_details where marks < 210; Logical Operators These are used to combine the results of two conditions to produce a single result. The logical operators are: AND, NOT, OR Example: Select * from student_details where marks>500 and dob>01-jan-80;
Page 15

FUNCTIONS IN SQL These are built-in functions for performing operations using the Data Manipulation commands. SQL Functions

Single Row Functions returns only one value for every row queried in the table can appear in select command & also in where clause

Group Functions Returns a result based on a group of rows Some of them are purely mathematical functions

Date functions Numeric functions Character functions Conversion functions Miscellaneous functions Some of them are discussed below. SINGLE ROW FUNCTIONS DATE FUNCTIONS Some of the important date functions are:

Avg function Min function Max function Sum function Count function

1) add_months returns a date after adding a date with a given number of months. Format: add_months(d,n) where d - date n - number of months Example: select del_date, add_months(del_date,2) from order_master;
Page 16

Output -

DEL_DATE ADD_MONTHS ---------------- -------------------15-FEB-05 15-APR-05

2) last_day returns the date corresponding to the last day of the month. Format: last_day(d) where d - date Example: select last_day (del_date) from order_master; 3) months_between returns the number of months between two dates. Format: months_between(d1, d2) where d1, d2 - dates Example: select months_between (del_date, odate) from order_master; CHARACTER FUNCTIONS These are functions operated on characters. Input will be character and output will be either character or number values. FUNCTION Initcap(char) Lower(char) Upper(char) Ltrim(char,set) Rtrim(char,set) Translate(char, from ,to) Replace(char, searchstring,[rep string]) Substr(char,m,n) NUMERIC FUNCTIONS FUNCTION Abs Ceil(n) Cos(n) cosh(n) Exp(n) floor(n) Power(m,n) INPUT Select abs(-15) from dual; Select ceil(44.778) from dual; Select cos(180) from dual; Select cosh(0) from dual; Select exp(4) from dual; Select floor(100.2) from dual; Select power(4,2) from dual;
Page 17

INPUT Select initcap(hello) from dual; Select lower(FUN) from dual; Select upper(sun) from dual; Select ltrim(xyzadams,xyz) from dual; Select rtrim(xyzadams,ams) from dual; Select translate(jack,j,b) from dual; Select replace(jack and jue,j,bl) from dual; Select substr(abcdefg,3,2) from dual;

OUTPUT Hello fun SUN adams xyzad back Black and blue cd

OUTPUT 15 45 -.5984601 1 54.59815 100 16

Mod(m,n) Round(m,n) Trunc(m,n) Sqrt(n)

Select mod(10,3) from dual; Select round(100.256,2) from dual; Select trunc(100.256,2) from dual; Select sqrt(4) from dual;

1 100.26 100.25 2

CONVERSION FUNCTIONS Used for conversion of values from one data type to another. They are: To_char() To_date() To_number() To_char() Converts date to a value of varchar2 type in a given format. Format: to_char(d, [fmt]); To_date() Converts char or varchar2 type to date data type. Format: to_date(char, [fmt]); To_number() Converts string containing numbers in to the number data type. Format: to_number(char); MISCELLANEOUS FUNCTIONS Some of the functions supported are: Uid returns the integer value corresponding to the user logged in. User returns the logins user name. GROUP FUNCTIONS Avg function returns the average of the values of the column specified. Min function returns the least of all the values of the column. Max function returns the maximum of all the values of the column. Sum function returns the sum of a range of values. Count function count the number of rows. Count(*) counts all rows Count(col_name) count all rows except null valued rows Count(distinct col_name) count all rows except null valued rows but eliminates duplicates while counting. Group by clause - Used to avoid the simultaneous usage of column name and group function. - To group the rows according to some column and perform group functions.
Page 18

Having clause - Used to specify some conditions on the rows retrieved by the group by clause.

Example: 1) select name, subject,max(marks) from student_details group by subject; Output NAME --------XXX YYY SUBJECT ------------CSE ECE MAX(MARKS) ------------------897 789

2) select name, subject,max(marks) from student_details group by subject having subject not in (ECE); Output NAME --------XXX SUBJECT ------------CSE MAX(MARKS) ------------------897

SET OPERATORS Set operators combine the results of two queries in to a single one. Union returns all distinct rows selected by both queries Union all returns all rows selected by either query including duplicates

SET OPERATORS

Intersect returns all rows common to both the queries

Minus returns all distinct rows selected only by the first query and not by the second

Example: Select orderno from order_master union select orderno from order_detail;

Page 19

JOIN The purpose of the join is to combine the data spread across tables. A join is actually performed by the where clause which combines the specified rows of tables. For combining data where a common column will provide the join condition, the references to the table names must be made. If a join involves over two tables, then the first two are joined based on the condition and then the result is compared with the next table and so on. Syntax: select columns from table1, table2 where logical expression; The classification for the join are given below Join Simple Join Equi-join Non equi-join Self Join Outer Join Simple Join Retrieves rows from two tables having a common column. Equi-join It is a join which is based on equalities. It combines rows that have equivalent values for the specified columns. i.e. it makes use of the equality operator ( = ). Example select odate, del_date, itemcode, qty_ord, qty_deld from order_master, order_detail where order_master.orderno = order_detail.orderno; Non equi-join It specifies the relationship between columns belonging to different tables by making use of the relational operator ( >, <, <=, >=, <> ) other than ( = ). Example select itemdesc, max_level, qty_ord, qty_deld from itemfile, order_detail where(( itemfile.max_level < order_detail.qty_ord) and( itemfile.itemcode= order_detail.itemcode)); Self Join Joining a table to itself is known as a self join. i.e. it joins one row in a table to another. The join is performed by mirroring the table using the where clause. It can compare each row of table to itself and also with other rows of the same table. Example select a.itemcode, a.itemdesc, a.qty_hand, b.max_level from itemfile a, itemfile b where a.qty_hand< b.max_level and a.p_category=spares and a.itemcode= b.itemcode;

Page 20

Outer Join It extends the result of a simple join. An outer join returns all the rows returned by simple join as well as those rows from one table that do not match any row from the other table. This cannot be done with a simple join alone. The symbol, ( + ) represents outer join. Example select a.orderno, vencode, qty_ord, qty_deld from order_master a, order_detail where a.orderno= order_detail.orderno (+); This will retrieve rows from order_master table which have any matching records in the order_detail table, in addition to those records which have a simple join match.

Page 21

SUBQUERIES Nesting of queries, one within another, is termed as a subquery. A statement containing a subquery is called a parent statement. Subqueries are used to retrieve data from tables that depend on the values in the table itself. Example select * from order_detail where orderno= (select orderno from order_master where del_date= 25-May-05 and vencode= v001); Note i) ii)

Always enclose subquery within parenthesis Subquery will be evaluated first followed by the main query

Subqueries that return several values Subqueries can also return more than one value. In such cases we should include operators like any, all, in or not in between the comparison operator and the subquery. Example select * from order_detail where qty_deld < any( select qty_hand from itemfile where itemrate between 50 and 120); Note =any is equivalent to in and !=all is equivalent to not in. Multiple Subqueries There is no specific limit on the number of subqueries included in a where clause. Nesting of a query within a subquery is possible.

Page 22

INTEGRITY CONSTRAINTS An integrity constraint is a mechanism used to prevent invalid data entry to the table. In other words, constraints are used for enforcing rules that the columns in a table have to conform with. The following are the various types of integrity constraints are given below. TYPES OF INTEGRITY CONSTRAINTS Domain Integrity Constraint Not Null Constraint Check Constraint Entity Integrity Constraint Unique Constraint Primary key Constraint Referential Integrity Constraint Domain Integrity Constraint These constraints set a range and any violations that take place will prevent the user from performing the manipulation that caused the breach. Two types of domain integrity constraint are: Not Null Constraint The enforcement of this constraint in a table ensures that the table contains values. When a Not Null constraint is enforced through either on a column or a set of columns in a table, it will not allow Null values. The user has to provide a value for the column. Note: i) Not Null integrity constraint can be defined using alter table command even when the table contains rows ii) Zero and Null are not equivalent iii) One null is not equivalent to another Example create table vendor_master( vencode varchar2(5), venname varchar2(25) constraint nn1 not null, venadd1 varchar2(20) constraint nn2 not null, venadd2 varchar2(25) not null); Constraint name is not a must, but it is a good practice. Check Constraint This can be defined to allow only a particular range of values. When the demarcation specified in this range is violated, the record is rejected. Check constraints specify conditions that each row must satisfy. These are rules governed by logical expressions or Boolean expression. Check conditions cannot contain suqueries.

Page 23

Example create table itemfile(itemcode varchar2(5), itemdesc varchar2(20), p_category varchar2(20), qty_hand number(5), re_level number(5), max_level number(5) constraint max check(max_level<500), itemrate number(9,2)); Entity Integrity Constraint Entity constraint can be used to identify each row in a table uniquely. Unique Constraint This is to prevent the duplication of values within the rows of a specified column or a set of columns in a table. But Null values are allowed in such columns. Note: i) if a unique key constraint is defined in more than one column, i.e. combination of columns, it is said to be composite unique key ii) combination of columns cannot be duplicated iii) composite unique key contains a maximum of 16 columns iv) the entity integrity and referential integrity can have composite keys v) this can be applied at table level, instead of column level Example create table itemfile(itemcode varchar2(5), itemdesc varchar2(20), p_category varchar2(20), qty_hand number(5), re_level number(5), max_level number(5) constraint max check(max_level<500), itemrate number(9,2), constraint un_item unique(itemdesc)); Primary key Constraint It avoids duplication of rows and does not allow Null values, when defined in a column or a set of columns. Note: i) it can be used to identify a row ii) a table can have only one primary key iii) primary key constraint assigned to a combination of columns is called a composite primary key iv) it can contain a maximum of 16 columns v) it cannot be defined in alter table command when the table contains rows having Null values Example create table order_master(orderno varchar2(5), odate date, vencode varchar2(5), o_status char(1), del_date date, constraint ord_prim primary key(orderno)); Referential Integrity Constraint It enforces relationship between tables. It designates a column or a set of columns as a foreign key. The foreign key establishes a relationship with a specified primary or unique key in another table, called the referenced key. The table containing foreign key is the child table and the one that containing the referenced key is the parent table.
Page 24

Example create table order_detail(orderno varchar2(5) constraint fk_ord references order_master(orderno), itemcode varchar2(5) constraint fk_item references itemfile(itemcode), qty_ord number(5) not null, qty_deld number(5) not null);

VIEWS A view is an oracle object that gives the user a logical view from an underlying table. When a view is created from more than one table, the user can view data from the view without using join conditions and complex conditions. Same data can be viewed differently from one or more tables. A view is stored as select statement in the data dictionary. There are two types of views: Simple view: it is based on one table and does not contain functions and grouped data. Moreover, data manipulation is possible from a simple view. Complex view: it is based on one or more tables. It may contain functions and grouped data. However, data manipulation is not always possible from a complex view. The general syntax of creating a view is: Create [or replace] [force / noforce] view viewName [Column aliases] as select sub-query [With check option [constraint constraintName]] [With read only]; A view is created with a select sub-query. The sub-query cannot use an ORDER BY clause, but a view can. The WITH CHECK OPTION applies to the where clause condition in the sub-query. It allows insertion and update of rows based on the condition that satisfies the view. The READ ONLY OPTION is to make sure that the data in the underlying table is not changed. The view can be removed using the following syntax: DROP VIEW viewName; The removal of the view does not affect the data in the underlying table. The other rules related to the data manipulation on a view are: no data manipulation on derived columns. no data manipulation on the ROWNUM pseudo column. no insertion if the base table contains columns with the NOT NULL constraint , which is not selected by the view. No insertion if derived columns exist in the view. Example create view ven_view as select * from vendor_master;

Page 25

ASSERTIONS Assertion may be defined as a predicate expressing a condition that the database should satisfy. Domain constraints and referential integrity constraints are special forms of assertions. These forms of assertions are easily tested and applied to a wide range of database applications. The general syntax of assertion is: Create assertions <assertion_name> check <predicate>

Page 26

PL/SQL (PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE)


PL/SQL FUNDAMENTALS AND BLOCK STRUCTURE PL/SQL (Procedural Language/Structured Query Language) is a block-structured language. A program can be divided into logical blocks. The block structure gives modularity to a PL/SQL program. Blocks are of two types: Anonymous block: block with a code without a name and can be used anywhere in a program. Named block: block with a code with a name. Procedures and Functions are examples. A PL/SQL program consists of statements. Uppercase and lowercase letters are treated in the same way. The PL/SQL block consists of reserved words (keywords), userdefined words, punctuation marks and literal values. A PL/SQL block consists of three sections: 1. Declarative section: optional section to define variables, constants, cursors and exceptions. 2. Execution section: mandatory section that contains PL/SQL and SQL statements for execution. 3. Exception section: optional section to perform when an error condition exists. The general format of an anonymous block is: DECLARE Declaration of variables, constants, cursors and exceptions. BEGIN PL/SQL and SQL statements. EXCEPTON Actions for error conditions. END;

Page 27

DATA TYPES Data types

Scalar Includes all SQL data types & ANSI standard data types

Composite is one that has components within it

Boolean

Binary Integer Natural (0-231-1) Positive(1-231-1)

Number Dec/decimal Int/integer Real

SCALAR DATA TYPES 1) Variables Syntax: variable_name data type (width); Example: name varchar2 (20); age number(5); xyz Boolean; 2) Constants The keyword constant must be used to declare constants. Syntax: constant_name constant data type; Example: max_limit constant int := 500.00 The keyword default can be used for this assignment. Example: done Boolean default true; 3) Character Character variables are used for storing strings or character data. The various sub types are: Character Varchar2 variable length character strings Char
Page 28

Fixed length variables Long Variable length string 4) Raw It is used to store binary data. 5) Rowid Database rowed pseudoname type. Holds rowed which is unique for each row in the database. Usually its a fixed length binary quantity. COMPOSITE DATATYPES The three composite types available in PL/SQL are records, tables and varrays. A composite type is one that has components within it. A variable of a composite type contains one or more scalar variables. They are discussed later. Composite Types Records Tables Varrays 1) Records It is a composite data type in which we can specify the data type of the column and define our own columns in the record. This allows us to access information about the attributes of a database table, which cannot be achieved using %rowtype attribute alone. It can contain any number of columns belonging to different data types. Declaring Records It is done in two steps. Syntax: Type <Type_name> is Record (Column definitions.); <PL/SQL record_type> <Type_name>; Example Type price_rectype is Record (prodid number(4) Not Null := 10, minimum price.maxprice%type); price_rec price_rectype Note

Columns declared as not null must be initialized in the declaration part A record can be initialized in its declaration part unlike PL/SQL tables, which doesnt allow initialization in the declaration part

Referencing Records The syntax for referencing individual fields or columns in a record <record_name>.<column_name> Example
Page 29

order_rec.shipdate :- 12-jan-05; 2) Tables They are temporary array-like objects used in a PL/SQL block. They can contain only one column and a primary key. The column data type can be scalar but the primary key can be only binary_integer. The number of rows can increase dynamically. The column as well as the primary key cannot be named. Declaring PL/SQL tables They are declared in the declarative part of any block. Consists of two steps, first we declare a table type, then we declare a table of that type. Syntax Type <name_of_type> is table of <col_def> index by binary_integer; <PL/SQL_Tablename> <Typename>; Example Type custtype is table of char(10) index by binary_integer; Custom custtype; Referring PL/SQL table Syntax PL/SQL_Tablename (Primary_key_value) Example Custom (4) Note: We cannot initialize PL/SQL table in its declaration. The value of a PL/SQL expression can be assigned to a specific row using the following syntax: PL/SQL_Tablename (primary_key_value) := PL/SQL expression; Example: Custom (2) := qty + primary; Example: declare Type ventype is table of vendor_master.venname%type index by binary_integer; vendor ventype; vname varchar2(15); i binary_integer := 0;

begin
Page 30

vname :=&a; vendor(i) := vname; if vendor(i) = nutech then update vendor_master set venname = vsnl where vencode = v004; dbms_output.put_line(updation performed); end if; end; 3) Varrays A varray is a data type similar to an array in C or Pascal. Declaring a Varray Syntax Type type_name is varray (maximum size) of element_type (not null); Example Type itemcode as varray(5) of varchar2(5); LOB types They are used to store large objects. A large object can be either a binary or a character value up to 4GB in size. LOB types are manipulated using the DBMS_LOB package. Different types of LOBs are: 1) BLOB (Binary LOB) Stores unstructured binary data up to 4 GB in length. Contains video or picture information. CLOB (Character LOB) Stores single byte character up to 4 GB in length. Used to store documents. BFILE (Binary File) Stores read only binary data as an external file outside the database.

2)

3)

A locator is stored in the large object column of a table. It is a pointer that specifies the actual location of LOB stored outside the database. USER DEFINED DATA TYPES Attributes Used to refer to data types and objects from the database. Two types: 1) %type 2) %rowtype %type Used to refer to columns in the table.

Example:
Page 31

vcode vendor_master.vencode%type; Advantages 1) Knowledge of the exact data type is not required. 2) If the data type of the vencode changes then that of vcode also changes at runtime. %rowtype Used to refer top record type that represents a row in a table. Example: vendor_inf vendor_master%rowtype; LOGICAL COMPARISON Comparison of variables and constants is done by logical operators. They are AND, OR and NOT. These comparisons are called Boolean Expressions. Boolean Expressions Numeric Character Date CONTROL STRUCTURES In a PL/SQL programming language, there are three control structures: 1) Conditional control 2) Iterative control 3) Sequential control CONDITIONAL CONTROL A sequence of statements can be executed based on some condition. These conditions can be specified by the if statement. If statement has three forms. If If then If then else If then elsif Syntax: If condition then Sequence of statements; End if; Example: declare orderstatus order_master.ostatus%type; begin select ostatus into orderstatus from order_master where orderno=o001;

Page 32

if orderstatus=p then update order_master set odate= 01-jan-99 where orderno=o001; else update order_master set odate = 26-jan-99 where orderno = o001; end if; end; ITERATIVE CONTROL Iterative controls (loop constructs) can be used to execute a sequence of statements more than once. The different loop constructs are: Iterative control Simple Loop While Loop For Loop Simple loop Syntax: Loop Sequence of statements; End loop; Example: declare a number :=100; begin loop a:= a+25; exit when a=250; end loop; dbms_output.put_line(to_char(a)); end; Note: Exit when statement can be used to break a loop. While loop While loop contains a condition associated with a sequence of statements. Syntax: While <condition> Loop Sequence of statements; End loop;

Page 33

Example: Declare i number :=0; j number :=0; Begin While i<=100 loop j:=j+I; j:=i+2; End loop; Dbms_output.put_line(The value of j is || j); End; Output the value of j is 2550 For loop Unlike while loop, the number of iterations will be known well in advance here. Syntax: For counter in [Reverse] lower bound .. upper bound Loop Sequence of statements; End loop; [Reverse] is optional for iteration from upper bound to lower bound. Example: Begin For i in 1 .. 2 Loop Update student_status st=o where age>35; End loop; End; SEQUENTIAL CONTROL The goto statement can be used to jump unconditionally to a particular label which is represented in double angle brackets. Synatx: Go to label; Example: Declare --statements; begin --statements; goto part2; -<part2> --statements; end;

Page 34

ERROR HANDLING (EXCEPTION HANDLING) An exception is an error condition in PL/SQL. It is of two types. Exception

Predefined Raised automatically by the system during run time

User defined Must be raised explicitly using RAISE statements Must be declared in the declarative part of the PL/SQL block

An exception is raised when an error occurs. Then normal execution stops and the control is immediately transferred to the exception handling part of the PL/SQL block. PREDEFINED EXCEPTION Syntax: Begin Sequence of statements; Exception When <exception_name> then Sequence of statements; When others then /* the last exception in the exception handler*/ Sequence of statements; End; Example: Declare Mark1 student_details.mark%type; Begin Select mark into mark1 from student_details where mark>95; Exception When no_data_found then dbms_output.put_line(No such student); End; USER DEFINED EXCEPTION Syntax: <exception_name> exception; Syntax for raise statement is Raise <exception_name>;

Example:
Page 35

declare lo_bal exception; balance customer.bal%type; begin select bal in to balance from customer where cust_id = c101; if balance < 250 then raise lo_bal; end if; exception when lo_bal then dbms_output.put_line(Low Balance); end; Raise_application_error It is used to create user defined error messages. Syntax: raise_application_error( error number, error message); where error number between 20,000 and 20,999. Error message text associated with this error. Example: --exception lo_bal then raise_application_error(-20001, low balance); -end; SQL IN PL/SQL PL/SQL supports Data Manipulation Language (DML) statements: INSERT DELETE UPDATE It also supports the Data Transaction Control Language statements: ROLLBACK COMMIT SAVE POINT The data can be retrieved using the Data Retrieval statement: SELECT

Page 36

CURSOR MANAGEMENT A cursor is handle or pointer to the context area. The PL/SQL program can control the context area by using the cursor. Declaration of the cursor is done at the declarative part of the block. Cursor Dynamic Cursor Made possible in PL/SQL by DBMS_SQL built in package

Static Cursor Select statements are known at run time

REF Cursor Reference type

Explicit Cursor name is explicitly assigned to select statement. Processing involves four steps

Implicit Used for all other SQL statements. Processing taken care by PL/SQL

Strong Return type specified

Weak Return type not specified

TYPES OF CURSORS The cursor is of three types: 1. Static cursor: The contents of a static cursor are known at the time of compilation. The cursor object is based on one SQL statement. The pointer in the cursor points to the first (and the only) row in the cursor. The static cursor is of two types: a. Implicit cursor: PL/SQL declares, manages, and closes it for every DML statement. b. Explicit cursor: Declared explicitly for every SQL statement in PL/SQL block that returns more than one row from an underlying table. 2. Dynamic cursor: In a dynamic cursor, a cursor variable is used that can change its value. The variable can refer to different SQL statements. The rows retrieved into an explicit cursor make up the active set. The cursor points to one row in the active set. 3. REF cursors: Unlike static cursors, REF cursors can name different storage locations as the program runs. ACTIONS ON EXPLICIT CURSORS An explicit cursor is declared as a select statement in the PL/SQL block. Four actions that are performed on cursors are:

Page 37

Declare it Open it Fetch rows from it Close it

Declaring an explicit cursor Syntax: Cursor CursorName is Select statement ; Declares the cursor. Opening a cursor Syntax: Open CursorName; It executes the query, identifies the active set and positions the cursor before the first row. Fetching data from a cursor Syntax: Fetch CursorName into VariableList / RecordName; It retrieves the current row and advances the cursor to the next row to fetch the remaining rows. Closing a cursor Syntax: Close CursorName; Used to disable the cursor after processing the last row in the active set. EXPLICIT CURSOR ATTRIBUTES %ISOPEN %FOUND %NOTFOUND %ROWCOUNT : : : : returns true if the cursor is open else a false returns true if the last fetch returned a row else a false returns true if the last fetch did not return a row else a false returns the total number of rows returned

Example: declare icode order_detail.itemcode%type; cursor a is select itemcode from order_detail where itemcode = i201; begin open a; loop fetch a into icode; update itemfile set itemrate = 22.05 where icode = itemcode; exit when a%NOTFOUND; end loop; dbms_output.put_line(table updated); close a; end;

Page 38

IMPLICIT CURSOR PL/SQL implicitly declares cursor for all SQL data manipulation statements, including queries that return one row. For queries that return multiple rows, explicit cursors should be used to access the rows individually. Implicit cursor attributes can be used to access information about the most recently executed SQL statement. The most recently executed SQL statement is referred as SQLCURSOR. IMPLICIT CURSOR ATTRIBUTES %ISOPEN %FOUND %NOTFOUND %ROWCOUNT : : : : always false as it is closed immediately after executing its associated SQL statement returns true if the last DML statement returned a row else a false returns true if the last DML statement did not return any row else a false returns the total number of rows returned.

CURSOR FOR LOOP A cursor for loop is an alternative for explicit cursors. A cursor for loop implicitly opens a cursor, repeatedly fetches rows from the active set, closes the cursor after processing all the rows. Syntax: for <record_name> in <cursor_name> loop --sequence of statements; end loop; Example: declare cursor for_cur is select orderno from order_master where vencode = v002; cust_rec for_cur%rowtype; begin for cust_rec in for_cur loop delete from order_detail where orderno = cust_rec.orderno; end loop; dbms_output.put_line(details has been deleted); end; REF CURSORS The reference type is similar to a pointer and the cursor variable is a reference type. Reference types are declared as REF type where type is a previously defined type.

The syntax for defining a cursor variable type is

Page 39

Type type_name is ref cursor retun return_type; Where type_name name of the new reference type return_type represents the type of the records returned by the cursor variable. Two types of REF cursors are as given below. REF Cursor Strong Cursor (Constrained Cursor) Cursor variable has return type Eg:- Type addref is ref cursor return vendor_master%rowtype Weak Cursor (Unconstrained Cursor) Cursor variable does not have return type Eg:- Type addref is ref cursor

Example Type t_add_ref is ref cursor return vendor_master%rowtype; - Strong cursor Type t_adds_ref is ref cursor; - Weak cursor Example declare type r1_cur is ref cursor; var1 r1_cur; nam varchar2(5); no number(2); begin no:= &enter_no; if no = 10 then open var1 for select orderno from order_master where vencode = v001; fetch var1 into nam; dbms_output.put_line(order no is||NAM); close var1; else open var1 for select qty_ord from order_detail where orderno = o001; loop fetch var1 into no; exit when var1%NOTFOUND; dbms_output.put_line(quantity ordered is|| no); end loop; close var1; end if; end;

Page 40

OPENING A CURSOR VARIABLE FOR A QUERY Syntax: Open cursor_variable for select statement; Where cursor_variable previously declared cursor variable select_statement desired query cursor variable is fetched using the fetch statement. CLOSING CURSOR VARIABLE Syntax: close cursor_name; SUBPROGRAMS Subprograms are named PL/SQL blocks that can accept parameters and can be invoked whenever required. Subprograms have - a declarative part - an executable part - an exception handling part Some of the features of subprograms are - modularity - reusability - maintainability PL/SQL supports two types of subprograms. They are Subprograms

Procedures Used to perform any specific task It cannot return a value

Functions Used to compute a value It can return a value

PROCEDURES A procedure is a named PL/SQL block that can perform one or more tasks. A procedure is the building block of modular programming. The general block structure of a procedure is: Create [or replace] procedure <procedure_name> [parameter list]) is [Constant /variable declarations] Begin (Executable statements) [Exception] Exception handling statements End;

Page 41

Procedures have - specification : starts with keyword procedure and ends with procedure name or parameter list. - body : starts with keyword is and ends with the keyword end. Declarative, executable and exception handling parts are in the body of the procedure. Example: Procedure width (name char(40)) is Begin (set of statements); end; Calling a Procedure A call to the procedure is made through an executable PL/SQL statement. The procedure has the following syntax: Procedure_Name [(parameters)]; The procedure can be executed from SQL environment with the execute command as follows: SQL > EXECUTE Procedure_Name [ (parameters) ]; Example: create or replace procedure items (orders varchar2) is qtyhand number; relevel number; maxlevel number; begin select qty_hand, re_level, max_level into qtyhand, relevel, maxlevel from itemfile where itemcode = orders; if qtyhand<relevel then update itemfile set qty_hand = relevel+qtyhand where itemcode = orders; else dbms_output.put_line(itemlevel ok); end if; exception when no_data_found then dbms_output.put_line(no data returned); end;

Page 42

PARAMETER MODES There are mainly three different parameter modes. They are: In Parameter Used to pass values to the subprogram when invoked It acts like a constant and cannot be assigned a value Out Parameter Used to return values to the caller of a subprogram It can be assigned some values

Parameter Modes

InOut Parameter Used to pass initial values to the subprogram when invoked and it also returns updated values to the caller Can be assigned to other variables or to itself Example: create or replace procedure or_detail (orno in varchar2, b in out varchar2) is qtyord number; qtydeld number; code varchar2(5); begin select qty_ord, qty_deld, itemcode into qtyord, qtydeld, code from order_detail where orderno = no; if qtydeld<qtyord then b := code; end if; end; To execute the above procedure, a block as shown below is written and executed. declare a varchar2(5); b varchar2(5); begin or_detail(o202,b); dbms_output.put_line(the item code is|| b); end;
Page 43

FUNCTIONS A function, like a procedure, is a named PL/SQL block. Like a procedure, it is also a stored code. The main difference between a function and a procedure is that a function always returns a value back to the calling block. A function is characterized as follows: A function can be with one, more or no parameters. A function must have an explicit RETURN statement in the executable section to return a value. The data type of the return value must be declared in the functions header. A function cannot be executed as a standalone program. A function may have parameters of IN, OUT and IN OUT types, but the primary use of a function is to return value with an explicit RETURN statement. The general syntax is: Create [or replace] function function_name [(Parameters)] Return data type is [Constant / variable declarations] Begin Executable statements Return ReturnValue Exception Exception handling statements Return ReturnValue End; where arguments can be in, out, or in out. FUNCTION CALL The function call is similar to the procedure call. The procedure call does not have an explicit RETURN statement, so a procedure call can be an independent statement on a separate line. A function does return a value back, and hence the function call must be made via an executable statement. FUNCTION HEADER The function header comes before the is keyword .The header contains the name of the function, the list of the parameters and the return data type. FUNCTION BODY A function body must contain at least one executable statement .If there is no declaration , the reserved word BEGIN follows the reserved word IS .There can be more than one return statement , but only one is executed in a function call. Example: create or replace function items ( it varchar2) return number is args number; qtyhand number; relevel number; maxlevel number;

Page 44

begin select qty_hand, re_level, max_level into qtyhand, relevel, maxlevel from itemfile where itemcode= it; if(qtyhand+relevel)>maxlevel then args := maxlevel; return args; else args := (qtyhand+relevel); return args; end if; end; To execute the function items the following block of code is executed. declare a varchar2(5); b number; begin a := &a; b := items(a); dbms_output.put_line(the value returned is || b); end; PACKAGES A package is a database object, which is an encapsulation of related PL/SQL types, subprograms, cursors, exceptions, variables and constants. Packages have - package specification: PL/SQL types, subprograms, cursors, exceptions, variables and constants are declared here. - package body: implements cursors, subprograms defined in package specification. Note: packages can not be called we can not pass parameters to packages nesting of packages is not possible COMMANDS TO CREATE PACKAGES create package command Used to declare the package specification. Syntax: create package <package_name> is <declarations> begin (executable statements) end [package_name]; create package body command Procedures and cursors declared in the create package command is defined and implemented by the package body.

Page 45

Syntax: create package body <package_name> is <declarations> begin (executable statements) end [body_name]; Example: Package specification: create or replace package pack_me is procedure order_proc (orno varchar2); function order_fun (ornos varchar2) return varchar2; end pack_me; Package body: create or replace package body pack_me as procedure order_proc ( orno varchar2 ) is stat char(1); begin select ostatus into stat from order_master where orderno = orno; if stat = p then dbms_output.put_line(pending order); else dbms_output.put_line(completed order); end if; end order_proc; function order_fun( ornos varchar2) return varchar2 is icode varchar2(5); ocode varchar2(5); qtyord number; qtydeld number; begin select qty_ord, qty_deld, itemcode, orderno into qtyord, qtydeld, icode, ocode from order_detail where orderno = ornos; if qtyord<qtydeld then return ocode; else return icode; end if; end order_fun; end pack_me; Syntax for calling a Packaged Subprogram: exec package_name. subprogram_name; Example: exec pack_me.order_no(o001);

Page 46

To execute the function that is given in the package a block of code is written as shown below, declare a varchar2(5); b varchar2(5); begin b := pack_me.order_fun(o202); dbms_output.put_line(the value is || b); end; TRIGGERS A database trigger is a PL/SQL block. It is stored in the database and is called implicitly when a triggering event occurs. The user does not call the trigger explicitly. The triggering event is based on the data manipulation language statement such as delete, insert, and update. A trigger can be created to fire before or after the triggering event. The triggering event is also called firing of the trigger. They can be used to - generate data automatically - audit data modifications - customize complex security authorizations The general syntax of the trigger is: Create [or replace] trigger Trigger_name [Before / after] [Insert/update/delete] On Table_name [For each row] [When condition] Declare Declaration statements Begin Executable statements Exception Exception handling statements End; A trigger is very useful in generating values for derived columns, for keeping track of table access, for preventing invalid entries, for performing validity checks, or for maintaining security. However, it cannot use a transaction control language statement such as commit, rollback, or savepoint. PARTS OF A TRIGGER It has three parts. They are: Trigger statement

a trigger statement a trigger body a trigger restriction

Page 47

This specifies the DML statements like update, delete and insert and it fires the trigger body. It specifies the table to which the trigger is associated. Trigger body This is a PL/SQL block that is executed when a triggering statement is issued. Trigger restriction Restrictions on a trigger is achieved using the WHEN clause. The WHEN clause is evaluated for each row that is affected by the trigger. TYPES OF TRIGGERS Triggers can be classified based on when they are fired. Before After For each row For each statement (default) Before/After Options These are used to specify when the trigger body should be fired with respect to the triggering statement. The trigger body will be fired either before or after executing the triggering statement. For each row/statement This statement indicates that the trigger fires once per row. By default it fires for each statement. Using the various combinations, we can assign a total of 12 different types of triggers to a database table. They are: Before update row/statement Before delete row/statement Before insert row/statement After update row/statement After delete row/statement After insert row/statement Example: create or replace trigger orders before insert on order_detail for each row declare orno order_detail.orderno%type; begin select orderno into orno from order_detail where qty_ord < qty_deld; if orno = o001 then raise_application_error (-20001,enter some other number); end if; end; When rows are inserted into the order_detail table with a value of o001 then the trigger is fired and this trigger fires before every row that is inserted into the table.

Page 48

Enabling and disabling triggers A trigger can be either enabled or disabled. By default, triggers are enabled. An enabled trigger executes the trigger body if the triggering event has been encountered. A disabled trigger does not execute the trigger body even if the triggering event is issued. Syntax for disabling a trigger: alter trigger <Trigger_name> disable; Example: Syntax for disabling all triggers: alter table <Table_name> disable all triggers; Syntax for enabling a disabled trigger: alter table <Table_name> enable <Trigger_name>; Syntax for enabling all the disabled triggers: alter table <Table_name> enable all Triggers; Syntax for dropping triggers: Drop Trigger <Trigger_name>;

BUILT-IN PACKAGES The database user SYS owns all the supplied packages. They are public synonyms and can be accessed by any user. EXECUTE permission on the package is necessary for users other than SYS to call the procedures and functions within the packages. Some of the packages are discussed below. DBMS_STANDARD The DBMS_STANDARD package provides language facilities that help applications to interact with the administrator. For instance, a procedure named raise_pplication_error allows issuing of user defined error messages. This ensures, reporting of errors to an application and the returning unhandled exceptions are also avoided. DBMS_OUTPUT This package enables displaying of output from PL/SQL blocks and subprograms, which makes it easier to test and debug them. Some of the procedures in this package are: Enable This procedure is used to enable calls to put, put_line, new_line, get_line and get_lines. Disable This is to disable all calls to put, put_line, new_line, get_line and get_lines. Put This is used to place a piece of information in the buffer.

Page 49

Put_line This is used to place a piece of information in the buffer followed by an end-of-line marker. New_line It is used to add a newline character to the buffer. Get_line This is to get a single line back that has been buffered. Get_lines This is to accept multiple lines from the buffer

Page 50

PRO*C
OVERVIEW Embedded SQL is a method of combining the computing power of a high-level language like C/C++ and the database manipulation capabilities of SQL. It allows you to execute any SQL statement from an application program. Oracle's embedded SQL environment is called Pro*C. A Pro*C program is compiled in two steps. First, the Pro*C precompiler recognizes the SQL statements embedded in the program, and replaces them with appropriate calls to the functions in the SQL runtime library. The output is pure C/C++ code. Then, a regular C/C++ compiler is used to compile the code and produces the executable. PRO*C SYNTAX SQL All SQL statements need to start with EXEC SQL and end with a semicolon ";". You can place the SQL statements anywhere within a C/C++ block, with the restriction that the declarative statements do not come after the executable statements. As an example: { int a; /* ... */ EXEC SQL SELECT salary INTO :a FROM Employee WHERE SSN=876543210; /* ... */ printf("The salary is %d\n", a); /* ... */ } PREPROCESSOR DIRECTIVES The C/C++ preprocessor directives that work with Pro*C are #include and #if. Pro*C does not recognize #define. For example, the following code is invalid: #define THE_SSN 876543210 /* ... */ EXEC SQL SELECT salary INTO :a FROM Employee WHERE SSN = THE_SSN; /* INVALID */ STATEMENT LABELS You can connect C/C++ labels with SQL as in: EXEC SQL WHENEVER SQLERROR GOTO error_in_SQL; /* ... */ error_in_SQL: /* do error handling */

Page 51

HOST VARIABLES BASICS Host variables are the key to the communication between the host program and the database. A host variable expression must resolve to an lvalue (i.e., it can be assigned). You can declare host variables according to C syntax, as you declare regular C variables. The host variable declarations can be placed wherever C variable declarations can be placed. You cannot use register storage-class specifier for the host variables. A host variable reference must be prefixed with a colon ":" in SQL statements, but should not be prefixed with a colon in C statements. When specifying a string literal via a host variable, the single quotes must be omitted. C function calls and most of the pointer arithmetic expressions cannot be used as host variable references even though they may indeed resolve to lvalues. POINTERS Pointers can be defined using the regular C syntax, and use them in embedded SQL statements. As usual, prefix them with a colon: int *x; /* ... */ EXEC SQL SELECT xyz INTO :x FROM ...; The result of this SELECT statement will be written into *x, not x. STRUCTURES Structures can be used as host variables, as illustrated in the following example: typedef struct { char name[21]; /* one greater than column length; for '\0' */ int SSN; } Emp; /* ... */ Emp bigshot; /* ... */ EXEC SQL INSERT INTO emp (ename, eSSN) VALUES (:bigshot); ARRAYS Host arrays can be used in the following way: int emp_number[50]; char name[50][11]; /* ... */ EXEC SQL INSERT INTO emp(emp_number, name) VALUES (:emp_number, :emp_name); which will insert all the 50 tuples in one go. Arrays can only be single dimensional. You can also have arrays of structures. When using arrays to store the results of a query, if the size of the host array (say n) is smaller than the actual number of tuples returned by the query, then only the first n result tuples will be entered into the host array.

Page 52

INDICATOR VARIABLES Indicator variables are essentially "NULL flags" attached to host variables. You can associate every host variable with an optional indicator variable. An indicator variable must be defined as a 2-byte integer (using the type short) and, in SQL statements, must be prefixed by a colon and immediately follow its host variable. Or, you may use the keyword INDICATOR in between the host variable and indicator variable. Here is an example: short indicator_var; EXEC SQL SELECT xyz INTO :host_var:indicator_var FROM ...; /* ... */ EXEC SQL INSERT INTO R VALUES(:host_var INDICATOR :indicator_var, ...); You can use indicator variables in the INTO clause of a SELECT statement to detect NULL's or truncated values in the output host variables. ERROR HANDLING WHENEVER Statement This statement allows you to do automatic error checking and handling. The syntax is: EXEC SQL WHENEVER <condition> <action>; Oracle automatically checks SQLCA for <condition>, and if such condition is detected, your program will automatically perform <action>. <condition> can be any of the following:

SQLWARNING - sqlwarn[0] is set because Oracle returned a warning SQLERROR - sqlcode is negative because Oracle returned an error NOT FOUND - sqlcode is positive because Oracle could not find a row that meets your WHERE condition, or a SELECT INTO or FETCH returned no rows

<action> can be any of the following:


CONTINUE - Program will try to continue to run with the next statement if possible DO - Program transfers control to an error handling function GOTO <label> - Program branches to a labeled statement STOP - Program exits with an exit() call, and uncommitted work is rolled back

Some examples of the WHENEVER statement: EXEC SQL WHENEVER SQLWARNING DO print_warning_msg(); EXEC SQL WHENEVER NOT FOUND GOTO handle_empty;

Page 53

APPENDIX A

Page 54

ALGORITHMS & SOLVED QUESTIONS SQL RELATIONS USED IN SQL QUERIES SQL> select * from customer; CUST_ID c-101 c-102 c-103 c-104 c-105 c-106 c-107 c-108 c-109 9 rows selected. SQL> select * from branch; BRAN_NAME Kottayam Kanjikzhy Nalanchra Palayam Plvattom Adoor 6 rows selected. SQL> select * from borrower; BORROW_NA Martin Merlyn Justin Sherry Joshua Merlyn Jeff 7 rows selected. SQL> select * from loan;
Page 55

CUST_NAME Martin Merlyn Justin Joshua Christie Charlie Jim Jeff Sherry

CUST_STREET MC Road MG Road KK Road MG Road TM Road MC Road KK Road MG Road MC Road

CUST_CITY Kottayam Adoor Kottayam Ernakulam Thodpuzha Chenganur Ponkunnam Ernakulam Tiruvalla

BRAN_CITY Kottayam Kottayam Trvdm Trvdm Ernakulam Adoor

BRAN_ASSET 21 Lakhs 10 Lakhs 25 Lakhs 20 Lakhs 15 Lakhs 18 Lakhs

LOAN_NO l-01 l-02 l-03 l-04 l-05 l-06 l-07

CUST_ID c-101 c-102 c-103 c-109 c-104 c-102 c-108

LOAN_NO l-01 l-02 l-03 l-04 l-05 l-06 l-07 7 rows selected. SQL> select * from account; ACCO_NO a-101 a-216 a-102 a-304 a-201 a-207 a-225 7 rows selected. SQL> select * from depositor; ACCO_NO a-101 a-216 a-102 a-304 a-201 a-207 a-225 7 rows selected.

BRAN_NAME Kottayam kanjikzhy Nalanchra Kottayam Palayam Plvattom Adoor

AMOUNT 1500 2000 3000 2500 800 900 1800

BRAN_NAME Kottayam Palayam Nalanchra Plvattom Adoor Kanjikzhy Adoor

AMOUNT 540 720 450 3300 450 720 750

CUST_ID c-101 c-102 c-103 c-106 c-109 c-101 c-107

CUST_NAME Martin Merlyn Justin Charlie Sherry Martin Jim

Page 56

RELATION CREATION & CONSTRAINTS ON RELATION ATTRIBUTES SQL> create table customer(cust_id varchar2(7),cust_name varchar2(9), cust_street varchar2(11),cust_city varchar2(9), primary key(cust_id)); Table created. SQL> create table branch(bran_name varchar2(9),bran_city varchar2(9), bran_asset varchar2(10),primary key(bran_name)); Table created. SQL> create table borrower(borrow_name varchar2(9),loan_no varchar2(7), cust_id varchar2(7),primary key(loan_no)); Table created. SQL> create table account(acco_no varchar2(7),bran_name varchar2(9), amount number(5),primary key(acco_no)); Table created. SQL> create table loan(loan_no varchar2(7),bran_name varchar2(9), amount number(5),primary key(loan_no)); Table created. SQL> create table depositor(acco_no varchar2(7),cust_id varchar2(7), cust_name varchar2(9),foreign key (acco_no) references account); Table created.

Page 57

QUERIES 1). Aim: To select name and sum loan for a borrower in descending order. Query: select borrow_name,sum(amount) from loan,borrower where loan.loan_no=borrower.loan_no group by borrow_name order by sum(amount) desc;

Result: BORROW_NA Martin Justin Sherry Merlyn Joshua Jeff SUM(AMOUNT) 3300 3000 2000 2000 900 800

2) a. Aim: To insert a tuple into loan and update the borrower table. Query: insert into loan values('l-08','Nalanchra',2200); insert into borrower values('Sherry','l-08','c-109'); Result: SQL> select * from loan; LOAN_NO l-01 l-02 l-03 l-04 l-05 l-06 l-07 l-08 8 rows selected.

BRAN_NAME Kottayam Kanjikzhy Nalanchra Kottayam Palayam Plvattom Adoor Nalanchra

AMOUNT 1500 2000 3000 2500 800 900 1800 2200

Page 58

SQL> select * from borrower; BORROW_NA LOAN_NO CUST_ID -------------------------------------------------Martin l-01 c-101 Merlyn l-02 c-102 Justin l-03 c-103 Sherry l-04 c-109 Joshua l-05 c-104 Merlyn l-06 c-102 Jeff l-07 c-108 Sherry l-08 c-109 8 rows selected. 2) b. Aim: Update branch city to 'Kozhikode' where branch name is Palayam. Query: update branch set bran_city='Kozhikode' where bran_name='Palayam'; Result: 1 row updated. SQL> select * from branch; BRAN_NAME BRAN_CITY BRAN_ASSET --------------------------------------------------------Kottayam Kottayam 21 Lakhs Kanjikzhy Kottayam 10 Lakhs Nalanchra Trvdm 25 Lakhs Palayam Kozhikode 20 Lakhs Plvattom Ernakulam 15 Lakhs Adoor Adoor 18 Lakhs 6 rows selected. 3). Aim: Update account table to make balance of Merlyn to 0. Query: update account set amount=0 where acco_no=(select acco_no from depositor where cust_name='Merlyn'); Result: 1 row updated. SQL> select * from account;

Page 59

ACCO_NO BRAN_NAME AMOUNT -----------------------------------------------a-101 Kottayam 540 a-216 Palayam 0 a-102 Nalanchra 450 a-304 Plvattom 3300 a-201 Adoor 450 a-207 Kanjikzhy 720 a-225 Adoor 750 7 rows selected. 4). Aim: To display the name and total amount from the tables depositor and account. Query: select cust_name,sum(amount) from depositor, account where depositor.acco_no=account.acco_no group by cust_name; Result: CUST_NAME SUM(AMOUNT) ----------------------------------------Charlie 3300 Jim 750 Justin 450 Martin 1260 Merlyn 0 Sherry 450 6 rows selected. 5). Aim: To display sum of loan amount of borrowers grouping by name ordering by sum of amount Query: select borrow_name,sum(amount) from borrower,loan where borrower.loan_no=loan.loan_no group by borrow_name order by sum(amount); Result: BORROW_NA SUM(AMOUNT) ----------------------------------------Joshua 800 Martin 1500 Jeff 1800 Merlyn 2900 Justin 3000 Sherry 4700 6 rows selected.
Page 60

6). Aim: To display name and distinct count of depositor. Query: select cust_name,count(distinct acco_no) from depositor group by cust_name; Result: CUST_NAME COUNT(DISTINCTACCO_NO) -----------------------------------------------------------Charlie 1 Jim 1 Justin 1 Martin 2 Merlyn 1 Sherry 1 6 rows selected. 7). Aim: To display the avg and max of balance of a customer having more than one account. Query: select cust_name, avg(amount),max(amount) from depositor, account where depositor.acco_no=account.acco_no group by cust_name having count(distinct depositor.acco_no)> 1. Result: CUST_NAME AVG(AMOUNT) MAX(AMOUNT) ---------------------------------------------------------------------------Martin 630 720 8). Aim: To find customers having both loan and account. Query: select cust_name from depositor intersect select borrow_name from borrower; Result: CUST_NAME --------Justin Martin Merlyn Sherry

Page 61

9). Aim: To find customers having either loan or account. Query: select cust_name from depositor union select borrow_name from borrower; Result: CUST_NAME --------Charlie Jeff Jim Joshua Justin Martin Merlyn Sherry 8 rows selected. 10). Aim: To find customers having only loan. Query: select borrow_name from borrower minus select cust_name from depositor; Result: BORROW_NA -------------------Jeff Joshua 11). Aim: To find customers having only account. Query: select cust_name from depositor minus select borrow_name from borrower. Result: CUST_NAME -----------------Charlie Jim

Page 62

12). Aim: Create view such that it contains branch name and the total amount balance. Query: create or replace view bnk(bran_name,tot_balance) as select bran_name,sum(amount) from account group by bran_name;

Result: View created. SQL> select * from bnk; BRAN_NAME TOT_BALANCE ----------------------------------------Adoor 1200 Kanjikzhy 720 Kottayam 540 Nalanchra 450 Palayam 0 Plvattom 3300 6 rows selected. 12) a. Aim: To find the customer having the maximum loan using view. Query: create or replace view max_loan(borrow_name,amount) as select borrow_name,amount from borrower,loan where loan.loan_no=borrower.loan_no; select borrow_name,amount from max_loan where amount=(select max(amount) from max_loan); Result: View created. SQL> select * from max_loan; BORROW_NA Martin Merlyn Justin Sherry Joshua Merlyn Jeff Sherry AMOUNT 1500 2000 3000 2500 800 900 1800 2200
Page 63

8 rows selected. BORROW_NA AMOUNT ----------------------------------Justin 3000 12) b. Aim: To find the customer having the maximum account balance. Query: create or replace view max_account(cust_name,amount) as select cust_name,sum(amount) from depositor,account where depositor.acco_no=account.acco_no group by cust_name; select * from max_account; select cust_name,amount from max_account where amount=(select max(amount) from max_account); Result: View created. CUST_NAME AMOUNT --------------------------------Charlie 3300 Jim 750 Justin 450 Martin 1260 Merlyn 0 Sherry 450 6 rows selected. CUST_NAME AMOUNT --------------------------------Charlie 3300 12) c. Aim: To find the branch having the maximum asset. Query: create or replace view max_bran_asset(bran_name,asset) as select bran_name,bran_asset from branch; select * from max_bran_asset; select bran_name,asset from max_bran_asset where asset=(select max(asset) from max_bran_asset);

Page 64

Result: View created. BRAN_NAME Kottayam Kanjikzhy Nalanchra Palayam Plvattom Adoor 6 rows selected. BRAN_NAME ASSET --------- ---------Nalanchra 25 Lakhs ASSET 21 Lakhs 10 Lakhs 25 Lakhs 20 Lakhs 15 Lakhs 18 Lakhs

Page 65

PL/SQL

Experiment 1:
Aim: To verify whether a triangle is formed or not. Algorithm: Step 1: Start. Step 2: Declare variables a,b and c as integers and initialize them. Step 3: Check whether: sum of a and b greater than c, sum of b and c greater than a, sum of a and c greater than b Step 4: If Check evaluates to true then Print Triangle is formed. Else Print Triangle is not formed. Step 5: Stop. Program: Declare a number(10):='&a'; b number(10):='&b'; c number(10):='&c'; Begin if ((a+b)>c and (b+c)>a and (a+c)>b) then dbms_output.put_line('Triangle is formed'); else dbms_output.put_line('Triangle is not formed'); end if; End; Output: Enter value for a: 1 old 2: a number(10):='&a'; new 2: a number(10):='1'; Enter value for b: 3 old 3: b number(10):='&b'; new 3: b number(10):='3'; Enter value for c: 4 old 4: c number(10):='&c'; new 4: c number(10):='4'; Triangle is not formed PL/SQL procedure successfully completed.

Page 66

SQL> / Enter value for a: 4 old 2: a number(10):='&a'; new 2: a number(10):='4'; Enter value for b: 7 old 3: b number(10):='&b'; new 3: b number(10):='7'; Enter value for c: 6 old 4: c number(10):='&c'; new 4: c number(10):='6'; Triangle is formed PL/SQL procedure successfully completed.

Experiment 2:
Aim: To accept values for two variables and swap them. Algorithm: Step 1: Start. Step 2: Declare a and b as integers and initialize them. Step 3: Print current values for variables a and b. Step 4: Set a as sum of current a and b. Step 5: Set b as difference between current a and b. Step 6: Set a as difference between current a and b. Step 7: Print current values for variables a and b. Step 8: Stop. Program: Declare a number(2):='&a'; b number(2):='&b'; Begin dbms_output.put_line('Value of A before swapp : '||a); dbms_output.put_line('Value of B before swapp : '||b); a:=a+b; b:=a-b; a:=a-b; dbms_output.put_line('Value of A after swapp : '||a); dbms_output.put_line('Value of B after swapp : '||b); End; Output: SQL> / Enter value for a: 3 old 2: a number(2):='&a'; new 2: a number(2):='3';
Page 67

Enter value for b: 5 old 3: b number(2):='&b'; new 3: b number(2):='5'; Value of A before swapp : 3 Value of B before swapp : 5 Value of A after swapp : 5 Value of B after swapp : 3 PL/SQL procedure successfully completed.

SQL> / Enter value for a: 7 old 2: a number(2):='&a'; new 2: a number(2):='7'; Enter value for b: 8 old 3: b number(2):='&b'; new 3: b number(2):='8'; Value of A before swapp : 7 Value of B before swapp : 8 Value of A after swapp : 8 Value of B after swapp : 7 PL/SQL procedure successfully completed.

Experiment 3:
Aim: To find the sum of digits of a given number. Algorithm: Step 1: Start. Step 2: Declare variables n(the number),s(initialized to 0) and b as integers, get value to n. Step 3: Set variable b as the number(n). Step 4: Check if n non zero,if false goto Step 8. Step 5: Set s as sum of current s and MOD(n/10). Step 6: Set n as (n-MOD(n/10))/10. Step 7: Goto Step 4. Step 8: Print sum(s) of digits of number(n). Step 9: Stop. Program: Declare n number(20):='&n'; s number(30):=0; b number(20); Begin b:=n; while (n<>0)
Page 68

Loop s:=s+mod(n,10); n:=(n-mod(n,10))/10; End Loop; dbms_output.put_line('Sum of digits of '||b||' is '||s); End; Output: Enter value for n: 45 old 2: n number(20):='&n'; new 2: n number(20):='45'; Sum of digits of 45 is 9 PL/SQL procedure successfully completed. SQL> / Enter value for n: 567 old 2: n number(20):='&n'; new 2: n number(20):='567'; Sum of digits of 567 is 18 PL/SQL procedure successfully completed. SQL> / Enter value for n: 789 old 2: n number(20):='&n'; new 2: n number(20):='789'; Sum of digits of 789 is 24 PL/SQL procedure successfully completed.

Experiment 4:
Aim: To evaluate sum of odd numbers below a given number. Algorithm: Step 1: Start. Step 2: Declare n(the number),i(initialized to 1),s(initialized to 0) as integers, get value to n. Step 3: Check if variable i is lesser than n, if false goto Step 7. Step 4: Check if MOD(i/2) is non zero,if true set s as sum of current s and i. Step 5: Increment variable i by unity. Step 6: Goto Step 3. Step 7: Print sum(s) of odd numbers below number(n). Step 8: Stop. Program: Declare n number(10):='&n';
Page 69

i number(10):=1; s number(20):=0; Begin while (i<n) Loop if (mod(i,2)<>0) then s:=s+i; end if; i:=i+1; End Loop; dbms_output.put_line('Sum of odd numbers below '||n||' is :- '||s); End; Output: SQL> / Enter value for n: 6 old 2: n number(10):='&n'; new 2: n number(10):='6'; Sum of odd numbers below 6 is :- 9 PL/SQL procedure successfully completed. SQL> / Enter value for n: 8 old 2: n number(10):='&n'; new 2: n number(10):='8'; Sum of odd numbers below 8 is :- 16 PL/SQL procedure successfully completed.

Experiment 5:
Aim: To write a PL/SQL block to accept two numbers and find the largest and smallest among them. Algorithm: Step 1: Start. Step 2: Declare and initialize variables a and b. Step 3: Check if a greater than b If true then Print message a is larger than b. Else check if b greater than a If true then Print message b is larger then a. Else Print message a and b are same. Step 4: Stop. Program: Declare a number(2):='&a'; b number(2):='&b';
Page 70

Begin if (a>b) then dbms_output.put_line(a||' is larger than '||b); else if (b>a) then dbms_output.put_line(b||' is larger than '||a); else dbms_output.put_line(a||' and '||b||' are same'); end if; end if; End; Output: Enter value for a: 2 old 2: a number(2):='&a'; new 2: a number(2):='2'; Enter value for b: 3 old 3: b number(2):='&b'; new 3: b number(2):='3'; 3 is larger than 2 PL/SQL procedure successfully completed.

SQL> / Enter value for a: 1 old 2: a number(2):='&a'; new 2: a number(2):='1'; Enter value for b: 6 old 3: b number(2):='&b'; new 3: b number(2):='6'; 6 is larger than 1 PL/SQL procedure successfully completed. SQL> / Enter value for a: 4 old 2: a number(2):='&a'; new 2: a number(2):='4'; Enter value for b: 4 old 3: b number(2):='&b'; new 3: b number(2):='4'; 4 and 4 are same PL/SQL procedure successfully completed.

Page 71

Experiment 6:
Aim: To write a PL/SQL block to compute the gross salary given the employee id. Table used: EMP_ID c-101 c-102 c-103 c-104 Algorithm: Step 1: Start. Step 2: Declare variables bs(basic salary),da(dearence allowence),hra(house rent allowence),la,gross and e_id(employee id),get value to e_id. Step 3: Select field value to emp_sal from emply relation into program variable bs for the employee with employee id as e_id. Step 4: Compute da as 30% of bs, Compute hra as 20% of bs, Compute la as 5% of bs. Step 5: Insert into empgross relation values to e_id,da,hra,la and gross. Step 6: Stop. Program: Declare bs number(6); da number(8,2); hra number(8,2); la number(8,2); gross number(8,2); e_id varchar2(7):='&e_id'; Begin select emp_sal into bs from emply where emp_id=e_id; da:=.3*bs;hra:=.2*bs;la:=.05*bs; gross:=bs+da+hra+la; insert into empgross values(e_id,da,hra,la,gross); end; Output: SQL> / Enter value for e_id: c-101 old 7: e_id varchar2(7):='&e_id';
Page 72

EMP_NA Mahadevan Sobhana Princy Santosh

EMP_DESIG Principal HOD Lecturer Labasst

EMP_SAL

EMP_DEPT

28000 Administer 18000 CompSci 13000 Elecronics 8000 Mechanical

new 7: e_id varchar2(7):='c-101'; PL/SQL procedure successfully completed. SQL> / Enter value for e_id: c-102 old 7: e_id varchar2(7):='&e_id'; new 7: e_id varchar2(7):='c-102'; PL/SQL procedure successfully completed. SQL> / Enter value for e_id: c-103 old 7: e_id varchar2(7):='&e_id'; new 7: e_id varchar2(7):='c-103'; PL/SQL procedure successfully completed. SQL> / Enter value for e_id: c-104 old 7: e_id varchar2(7):='&e_id'; new 7: e_id varchar2(7):='c-104'; PL/SQL procedure successfully completed. SQL> select * from empgross; EMP_ID c-101 c-102 c-103 c-104 EMP_DA 8400 5400 3900 2400 EMP_HRA 5600 3600 2600 1600 EMP_LA 1400 900 650 400 GROSS 43400 27900 20150 12400

Experiment 7:
Aim: To write a PL/SQL block to print fibonacci series below a given number. Algorithm: Step 1: Start. Step 2: Declare variables n(the number),x(initialized to 0),y(initialized to1),z(initialized to 1),get value to n. Step 3: Check if z lesser than n,if false then goto Step 5. Print value to z. Set z as sum of x and y. Set x as y. Set y as z.
Page 73

Step 4: Goto Step 3. Step 5: Stop. Program: Declare n number(10):='&n'; x number(10):=0; y number(10):=1; z number(10):=1; Begin dbms_output.put_line('Fibonacci Series upto '||n||':-'); dbms_output.put_line(x); while (z<n) Loop dbms_output.put_line(z); z:=x+y; x:=y; y:=z; End Loop; End; Output: Enter value for n: 5 old 2: n number(10):='&n'; new 2: n number(10):='5'; Fibonacci Series upto 5: -0 1 1 2 3 PL/SQL procedure successfully completed.

Experiment 8:
Aim: To write a PL/SQL code for factorial of a number. Algorithm: Step 1: Start. Step 2: Declare variables n(the number),i(initialized to 1) and f(initialized to 1) get value to n. Step 3: Check if i is lesser than or equal to n, if not then goto Step 6. Step 4: Set f as product of current f and i. Increment value to i by 1. Step 5: Goto Step 3. Step 6: Print factorial(f) of n. Step 7: Stop.

Page 74

Program: Declare n number(2):='&n'; i number(2):=1; f number(30):=1; Begin while (i<=n) Loop f:=f*i; i:=i+1; End Loop; dbms_output.put_line('Factorial of '|| n ||' :-'||f); End; Output: Enter value for n: 5 old 2: n number(2):='&n'; new 2: n number(2):='5'; Factorial of 5 :-120 PL/SQL procedure successfully completed.

Experiment 9:
Aim: To write a PL/SQL block to accept customer id as input from the customer table and prepare an electricity bill. Table used: CUST_ID c-101 c-102 c-103 c-104 c-105 c-106 c-107 Algorithm: Step 1: Start. Step 2: Declare variables cid(customer id),consumed(no of units consumed), charge(payment),v_read(previous reading),p_read(present reading),get value to cid. Step 3: Select field values to prev_read and pres_read from relation elec_cust into program variables v_read and p_read. Step 4: Compute variable consumed as difference between p_read and v_read.
Page 75

PREV_READ 25 100 75 100 0 10 150

PRES_READ 35 125 169 215 350 500 750

Step 5: Check if consumed is lesser than 20 If true set charge to 0. Else check if consumed is lesser than 100 If true set charge to value .5*consumed. Else check if consumed is lesser than 300 If true set charge to value 50+.75*(consumed-100). Else check if consumed is lesser than 500 If true set charge to value 200+2*(consumed-300). Else set charge to value 3.5*consumed. Step 6: Print the electricity bill(with fields customer id and charge). Step 7: Stop. Program: Declare cid varchar2(7):='&cid'; consumed number(4); charge number(6,2); v_read number(4); p_read number(4); Begin select prev_read,pres_read into v_read,p_read from elec_cust where cust_id=cid; consumed:=p_read-v_read; if (consumed<20) then charge:=0; else if (consumed<100) then charge:=.5*consumed; else if (consumed<300) then charge:=50+.75*(consumed-100); else if (consumed<500) then charge:=200+2*(consumed-300); else charge:=3.5*consumed; end if; end if; end if; end if; dbms_output.put_line(' ELECTRICITY BILL'); dbms_output.put_line(' Cust_id Charge'); dbms_output.put_line(cid||' '||charge); End; Output: SQL> / Enter value for cid: c-101 old 2: cid varchar2(7):='&cid'; new 2: cid varchar2(7):='c-101'; ELECTRICITY BILL Cust_id Charge c-101 0 PL/SQL procedure successfully completed. SQL> / Enter value for cid: c-102 old 2: cid varchar2(7):='&cid';
Page 76

new 2: cid varchar2(7):='c-102'; ELECTRICITY BILL Cust_id Charge c-102 12.5 PL/SQL procedure successfully completed. SQL> / Enter value for cid: c-103 old 2: cid varchar2(7):='&cid'; new 2: cid varchar2(7):='c-103'; ELECTRICITY BILL Cust_id Charge c-103 47 PL/SQL procedure successfully completed. SQL> / Enter value for cid: c-104 old 2: cid varchar2(7):='&cid'; new 2: cid varchar2(7):='c-104'; ELECTRICITY BILL Cust_id Charge c-104 61.25 PL/SQL procedure successfully completed. SQL> / Enter value for cid: c-105 old 2: cid varchar2(7):='&cid'; new 2: cid varchar2(7):='c-105'; ELECTRICITY BILL Cust_id Charge c-105 300 PL/SQL procedure successfully completed. SQL> / Enter value for cid: c-106 old 2: cid varchar2(7):='&cid'; new 2: cid varchar2(7):='c-106'; ELECTRICITY BILL Cust_id Charge c-106 580 PL/SQL procedure successfully completed. SQL> / Enter value for cid: c-107 old 2: cid varchar2(7):='&cid'; new 2: cid varchar2(7):='c-107'; ELECTRICITY BILL Cust_id Charge c-107 2100
Page 77

PL/SQL procedure successfully completed.

Experiment 10:
Aim: To accept the library id number of a member and to check whether membership is expired if not enter into the issue table. Table used: ID_NO s-01 s-02 s-03 s-04 s-05 s-06 Algorithm: Step 1: Start. Step 2: Declare exception mem_exe,program variables ino(identity no),edt(expire date) and sdt(sysrem date) ,get value to ino. Step 3: Select field value for exp_date from membership relation into program variable edt for the member with the entered value to identity number(ino). Step 4: Select system date into program variable sdt. Step 5: Check if edt is greater than or equal to sdt, If true then Invoke exception mem_exe which prints message Membership Expired. Else Insert into relation issue values to ino,bno,edt and dor(date of return). Step 6: Stop. Program: Declare mem_exe exception; ino varchar2(5):='&ino'; bno varchar2(7); edt date; sdt date; Begin select exp_date into edt from membership where id_no=ino; select sysdate into sdt from dual; NAME Neethu Sinsila Neenu Nigee Ushus Sreeja EXP_DATE 12-JUN-04 02-JUN-04 04-DEC-04 02-OCT-04 05-AUG-04 03-MAR-03

Page 78

if edt>=sdt then raise mem_exe; else insert into issue values(ino,'&bno',edt,add_months(edt,1)); end if; exception when mem_exe then dbms_output.put_line('Membership Expired'); End; Output: Enter value for ino: s-01 old 3: ino varchar2(5):='&ino'; new 3: ino varchar2(5):='s-01'; Enter value for bno: b-01 old 13: insert into issue values(ino,'&bno',edt,add_months(edt,1)); new 13: insert into issue values(ino,'b-01',edt,add_months(edt,1)); PL/SQL procedure successfully completed. SQL> / Enter value for ino: s-02 old 3: ino varchar2(5):='&ino'; new 3: ino varchar2(5):='s-02'; Enter value for bno: b-02 old 13: insert into issue values(ino,'&bno',edt,add_months(edt,1)); new 13: insert into issue values(ino,'b-02',edt,add_months(edt,1)); PL/SQL procedure successfully completed. SQL> / Enter value for ino: s-03 old 3: ino varchar2(5):='&ino'; new 3: ino varchar2(5):='s-03'; Enter value for bno: b-03 old 13: insert into issue values(ino,'&bno',edt,add_months(edt,1)); new 13: insert into issue values(ino,'b-03',edt,add_months(edt,1)); Membership Expired PL/SQL procedure successfully completed. SQL> / Enter value for ino: s-04 old 3: ino varchar2(5):='&ino'; new 3: ino varchar2(5):='s-04'; Enter value for bno: b-04 old 13: insert into issue values(ino,'&bno',edt,add_months(edt,1)); new 13: insert into issue values(ino,'b-04',edt,add_months(edt,1)); PL/SQL procedure successfully completed.

Page 79

SQL> / Enter value for ino: s-05 old 3: ino varchar2(5):='&ino'; new 3: ino varchar2(5):='s-05'; Enter value for bno: b-05 old 13: insert into issue values(ino,'&bno',edt,add_months(edt,1)); new 13: insert into issue values(ino,'b-05',edt,add_months(edt,1)); PL/SQL procedure successfully completed. SQL> / Enter value for ino: s-06 old 3: ino varchar2(5):='&ino'; new 3: ino varchar2(5):='s-06'; Enter value for bno: / old 13: insert into issue values(ino,'&bno',edt,add_months(edt,1)); new 13: insert into issue values(ino,'/',edt,add_months(edt,1)); PL/SQL procedure successfully completed. SQL> select * from issue; ID_NO s-01 s-02 s-04 s-05 s-06 10 rows selected. BOOKNO b-01 b-02 b-04 b-05 b-06 DOI 12-JUN-04 02-JUN-04 02-OCT-04 05-AUG-04 03-MAR-03 DOR 12-JUL-04 02-JUL-04 02-NOV-04 05-SEP-04 03-APR-03

Experiment 11:
Aim: To calculate whether commission is entitled to a salesman or not. Table used: ID_NO NAME COM_RATE MIN_SALES TOT_SALES s1 s2 s3 s4 s5 s6 Shiju Shinjo Shafi Anoop Arun Asha 11 8 5 20 17 8
Page 80

500 800 100 2500 800 1925

700 300 900 1750 850 1947

Algorithm: Step 1: Start. Step 2: Declare exception(com_rate),identity no(n),employee name(name),minimum sales(m_s),total sales(t_s),commission rate(rate) and commission amount(x),get value to n. Step 3: Select field values for name,com_rate,min_sales,tot_sales within salesman relation into program variables(name,rate,m_s,t_s) where id_no is as n. Step 4: If t_s is greater than m_s then Set x as rate percent of t_s. Insert into relation commission values for n,name and x. Else Invoke exception com_rate(which prints Not entitled to commn). Step 5: Stop. Program: Declare com_rate exception; n varchar2(7):='&n'; name varchar2(10); m_s number(5); t_s number(5); rate number(3); x number(10,3); Begin select name,com_rate,min_sales,tot_sales into name,rate,m_s,t_s from salesman where id_no=n; if t_s>m_s then x:=(rate/100)*t_s; insert into commision values(n,name,x); else raise com_rate; end if; exception when com_rate then dbms_output.put_line('Not entitled to commn'); End; Output: SQL> / Enter value for n: s1 old 3: n varchar2(7):='&n'; new 3: n varchar2(7):='s1'; PL/SQL procedure successfully completed. SQL> / Enter value for n: s2 old 3: n varchar2(7):='&n'; new 3: n varchar2(7):='s2'; Not entitled to commn PL/SQL procedure successfully completed.
Page 81

SQL> / Enter value for n: s3 old 3: n varchar2(7):='&n'; new 3: n varchar2(7):='s3'; PL/SQL procedure successfully completed. SQL> / Enter value for n: s4 old 3: n varchar2(7):='&n'; new 3: n varchar2(7):='s4'; Not entitled to commn PL/SQL procedure successfully completed. SQL> / Enter value for n: s5 old 3: n varchar2(7):='&n'; new 3: n varchar2(7):='s5'; PL/SQL procedure successfully completed. SQL> / Enter value for n: s6 old 3: n varchar2(7):='&n'; new 3: n varchar2(7):='s6'; PL/SQL procedure successfully completed. SQL> select * from commision; ID_NO s5 s6 s5 s6 NAME Arun Asha Arun Asha COM 144.5 155.76 144.5 155.76

Page 82

Experiment 12:
Aim: To write a PL/SQL block to insert into a new table new employee, the contents of the table employee using cursor. Table used: EMP_ID EMP_NA c-101 c-102 c-103 c-104 Mahadevan Sobhana Princy Santosh EMP_DESIG Principal HOD Lecturer Labasst EMP_SAL EMP_DEPT

28000 Administer 18000 CompSci 13000 Elecronics 8000 Mechanical

Algorithm: Step 1: Start. Step 2: Declare cursor emp_cur which selects tuples from emply relation,variables e_id(employee id),e_name(employee name),e_desig(employee designation), e_sal(employee salary),e_dept(employee department). Step 3: Point to first tuple of relation emply by opening the cursor emp_cur. Step 4: Fetch tuple(pointed to by emp_cur) contents into program variables (e_id,e_name,e_desig,e_sal,e_dept). Step 5: Check if emp_cur has reached the end of relation emply If check is true then goto Step 7. Step 6: Insert into relation newemply values to program variables. Goto Step 4 Step 7: Close cursor emp_cur. Step 8: Stop. Program: Declare CURSOR emp_cur IS select * from emply; e_id varchar2(7);e_name varchar2(10);e_desig varchar2(10); e_sal number(7);e_dept varchar2(10); Begin OPEN emp_cur; Loop FETCH emp_cur into e_id,e_name,e_desig,e_sal,e_dept; EXIT when NOT emp_cur %FOUND; insert into newemply values(e_id,e_name,e_desig,e_sal,e_dept); End Loop; CLOSE emp_cur; End;

Page 83

Output: SQL> select * from newemply; E_ID c-101 c-102 c-103 c-104 E_NAME Mahadevan Sobhana Princy Santosh E_DESIG Principal HOD Lecturer Labasst E_SAL 28000 18000 13000 8000 E_DEPT Administer CompSci Elecronics Mechanical

Experiment 13:
Aim: To evaluate student grade using procedure accepting student roll no. Algorithm: Step 1: Start procedure. Step 2: Define(create or replace) procedure stud_grade taking parameter roll no and program variable mk(marks). Step 3: Select mark of student into an integer(mk) whose roll no had been passed. Step 4: If mk greater than 90 then Print Grade:=X. Else if mk greater than 80 then Print Grade:=A. Else if mk greater than 60 then Print Grade:=B. Else if mk greater than 50 then Print Grade:=C. Else Print Grade:=F. Step 5: Stop procedure. Procedure code: create or replace procedure stud_grade(r_no IN number) IS mk number(3); Begin select marks into mk from students where reg_no=r_no ; if mk>90 then dbms_output.put_line('Grade:=X'); else if mk>80 then dbms_output.put_line('Grade:=A'); else if mk>60 then dbms_output.put_line('Grade:=B');

Page 84

else if mk>50 then dbms_output.put_line('Grade:=C'); else dbms_output.put_line('Grade:=F'); end if; end if; end if; end if; End stud_grade;

Output: SQL> execute stud_grade(63); Grade:=B PL/SQL procedure successfully completed.

Experiment 14:
Aim: To implement a procedure in PL/SQL to check if employee is eligible to a salary increment depending on his period of service. Table used: E_ID e-01 e-02 e-03 e-04 e-05 Algorithm: Step 1: Start procedure. Step 2: Define(create or replace) procedure sal_icr taking parameter employee id (v_id). Step 3: Declare variables dt(no of months of service),jd(joining date),sd(system date). Step 4: Select doj field value from relation emptb into program variable jd for an employee(whose employee id is v_id). Step 5: Select system date into program variable sd. Step 6: Compute the number of months between jd and sd dates. Step 7: Check if dt greater than or equal to 60, if true then Increment bas field value by 10 percent for employee whose id had been passed to the procedure. Print New Salary. Else Print Salary Unchanged.
Page 85

E_NAME Renju Jimmy Sajeev Anwar Santhosh

E_DEPT d-11 d-12 d-10 d-12 d-10

DOJ 01-JAN-99 03-MAY-96 14-JUL-98 05-MAY-00 10-FEB-02

BAS 4000 5000 2500 4500 3000

Step 8: Stop procedure. Procedure Code: create or replace procedure sal_icr(v_id IN varchar2) IS dt number; jd date; sd date; Begin select doj into jd from emptb where e_id=v_id; select sysdate into sd from dual; dt:=months_between(jd,sd); if dt>=60 then update emptb set bas=bas+(.1*bas) where e_id=v_id; dbms_output.put_line('New Salary '); else dbms_output.put_line('Salary unchanged'); end if; End sal_icr; Output: Procedure created. SQL> execute sal_icr('e-01'); New Salary PL/SQL procedure successfully completed. SQL> execute sal_icr('e-05'); Salary unchanged PL/SQL procedure successfully completed. SQL> execute sal_icr('e-02'); New Salary PL/SQL procedure successfully completed. SQL> execute sal_icr('e-03'); New Salary PL/SQL procedure successfully completed. SQL> execute sal_icr('e-04'); Salary unchanged PL/SQL procedure successfully completed.

Experiment 15:
Aim: To evaluate student grade using functions accepting student rollno. Algorithm: Step 1: Start function. Step 2: Define (create or replace) function stud_grade taking parameter roll no.
Page 86

Step 3: Declare program variables mk(marks) and g(grade). Step 4: Select mark of student into an integer(mk) whose roll no had been passed. Step 5: If mk greater than 90 then Set g as X. Print Grade:=X. Else if mk greater than 80 then Set g as A. Print Grade:=A. Else if mk greater than 60 then Set g as B. Print Grade:=B. Else if mk greater than 50 then Set g as C. Print Grade:=C. Else Set g as F. Print Grade:=F. Step 6: Return value to grade g . Step 7: Stop function. Function Code: create or replace function stud_grad(r_no IN number ) return varchar2 IS mk number(3); g varchar2(1); Begin select marks into mk from students where reg_no=r_no ; if mk>90 then g:='X'; dbms_output.put_line('Grade:=X'); else if mk>80 then g:='A'; dbms_output.put_line('Grade:=A'); else if mk>60 then g:='B'; dbms_output.put_line('Grade:=B'); else if mk>50 then g:='C'; dbms_output.put_line('Grade:=C'); else g:='F'; dbms_output.put_line('Grade:=F'); end if; end if; end if; end if; return g; End stud_grad;

Page 87

Output: Function created. SQL> execute stud_grade(64); Grade:=B PL/SQL procedure successfully completed. SQL> execute stud_grade(61); Grade:=B PL/SQL procedure successfully completed. SQL> execute stud_grade(62); Grade:=X PL/SQL procedure successfully completed. SQL> execute stud_grade(56); Grade:=C PL/SQL procedure successfully completed. SQL> execute stud_grade(57); Grade:=B PL/SQL procedure successfully completed. SQL> execute stud_grade(1); Grade:=F PL/SQL procedure successfully completed.

Experiment 16:
Aim: To write a database trigger before delete for each row, not allowing deletion and giving an appropriate message, for the employee table.

Algorithm: Step 1: Start. Step 2: Define(create or replace) trigger emply_trigg whose function is to raise an error message Deletion not allowed on emply before an attempt is made to delete any row in emply table. Step 3: Stop. Trigger: create or replace trigger emply_trigg before delete on emply for each row Begin raise_application_error(-20768,'Deletion not allowed on emply') End; Result: SQL> / Trigger created.
Page 88

SQL> delete emply where emp_id='c-101'; delete emply where emp_id='c-101' * ERROR at line 1: ORA-20768: Deletion not allowed on emply ORA-06512: at "SCOTT.EMPLY_TRIGG", line 2 ORA-04088: error during execution of trigger 'SCOTT.EMPLY_TRIGG'

Experiment 17:
Aim: Generate a report for the following table TICK_NO 1 2 2 3 1 4 3 7 Algorithm: Step 1: Start. Step 2: Set format for displaying ticket fare(space=5,underline=-,space on, pagesize=20,heading on,linesize=20). Step 3: Set title display BUS RESERVATION SYSTEM and THANK YOU. Step 4: Compute sum of ticket fares based on ticket number . Step 5: Display ticket details inorder of ticket number. Step 6: Stop. Program: set space 5; set underline '-'; set space on; set pagesize 20; set heading on; set linesize 60; ttitle 'BUS RESERVATION SYSTEM'; btitle right 'THANK YOU'; break on tick_no skip1; compute sum of tick_fare on group by tick_no; select * from tick_details order by tick_no; NAME Sajeena Santosh Ajith Rajesh Dhanya Jimmy Sumesh Sobhana AGE 28 30 31 33 32 25 25 35 TICK_FARE 15 13 12.5 11 17.75 20.5 5.5 7.25

Page 89

Output: Wed Oct 20 page 1 BUS RESERVATION SYSTEM TICK_NO NAME --------- --------------1 Sajeena Dhanya ********* sum 2 ********* sum 3 ********* sum 4 Jimmy ********* sum 7 Sobhana ********* sum 25 Rajesh Sumesh 33 25 Santosh Ajith AGE --------28 32 TICK_FARE --------15 17.75 --------32.75 13 12.5 --------25.5 11 5.5 --------16.5 20.5 --------20.5 7.25 --------7.25 THANK YOU 8 rows selected.

30 31

35

Page 90

APPENDIX B

Page 91

EXERCISES Q1. Consider the Insurance database given below, where the primary keys are underlined. Construct the following SQL queries for this relational database? person ( driver_id, name, address) Car (license, model, year) Accident (report_no, date, location) Owns (driver_id, license) Participated (driver_id, car, report-no, damage_amount) DB 1 a) Find total no. of owners involved in accidents in 1989. b) Find no. of accidents in which cars belonging to John Smith where involved. c) Delete the Mazda belonging to John Smith. d) Update damage amount for the car with license no: AABB2000 in the accident with report no: AR21072 to $3000. Q2. Consider the employee database of fig. given below, where primary keys are underlined. Write an expression in SQL for each of the following queries? Employee (ename, street, city) Works (ename, company_name, sal) Company (company_name, city) Manages (ename, manager_name) DB 2 a) Find names and cities of all employees who work for City Bank Corp. b) Find all employees who donot work for City Bank Corp. c) Find all companies located in every city in which City Bank Corp is located. d) Find all employees who earn more than each employee of Small Bank Corp?

Q3. Consider the relational database given above. Write an expression in SQL for each of the following queries? a) Modify the database so that Jones now lives in Newton. b) Give all employees of First Bank Corp a 10% raise. c) Give all managers of First Bank Corp a 10% raise unless the salary becomes greater than $100,000; in such cases give only 3% raise.

Page 92

Q4. The Library data base is as follows Book Record (book_no, title, cost) Author Record (book_no, author) User Record (user_id, name, category) Ciculation Record(user_id, book_no, issuedate, returndate) DB 3 Write SQL query for each of the following? a) Find titles of all books where Henry is one of the author. b) Find titles of all books where Henry is the only author. c) Find names of all user who have not returned books costing above $500. d) Find names of authors of books costing above $500. Q5. Consider the relational database DB 2. Using SQL, define a view consisting of manager_name and average salary of all employees who works for that manager. Q6. Write SQL query without using a with clause, to find all branches where the total account deposit is less than the average total account deposit at all branches, a) Using a nested query in the from clause. b) Using a nested query in a having clause. Q7. Write a PL/SQL procedure to print odd numbers below a given number? Q8. Write a PL/SQL procedure to count no. of occurrences of a given character in a string? Q9. Write a PL/SQL procedure using cursors to insert into Dept10 the content of employee table where department number=10? Q10. Write a database trigger before delete or update for each row. If updated or deleted insert old record in to table OldEmp and new record (only when updated) into table Newemp and allow changes in the orginal table?

Page 93

EXAMINATION QUESTIONS 1. For a library database memberrec (id-no, name, class) issuerec (id-no, bookno, date) bookrec (bookno, author, copies) create trigger/triggers to do the following. i. Do not issue books on second Saturdays or Sundays. ii. Issue book only if the student has a membership. iii. The maximum number of books that can be issued a student is 3. 2. When a record is placed in the table Registered (reg-no, name, date-birth, qualification, experience) automatically update Shortlist (reg-no, name) considering the following factors. i.. Age should be between 18 & 35 years. ii. If qualification is PG , minimum experience should be 2 years. iii. If qualification is UG, minimum experience should be 5 years 3. Consider the tables Customer(customer-name, customer-street, customer-city); Account(account-number, branch-name, balance 0); Depositer(customer-name, account-number); Branch(branch-name, branch-city, assets 0). After updating the account table,following table should be created automatically. Customer-status (account-number, balance, customer-name, customerstreet,branch-name). If balance =0, a message should be displayed. 4. When details of an employee is entered into the table Employee-Details(Id-no, Name, Dept, Date-of-entry, Date-of-birth) automatically generate the following details for each department. i. Id-no ii. Name iii. Date of next increment (Eg: For date of entry 12/08/03 , Date of next increment is 1/08/04 iv. Date of retirement, which is the last day of the month in which the age becomes 55yrs. If the last day is Sunday or a public holiday take the next day as the Date of retirement. 5. For the updation and deletion on table account (acc- no, branch name, balance) automatically create an audit table (acc- no, operation, date of last transaction) 6. Following are the tables of a data base. Item master (Item-code, Item-name, unit-price, recorder-level) Inventory (Item-code, Quantity) Order (Item-code, Quantity) When the quantity in inventory reaches the reorder level specified, an order should be automatically placed on the order table.

Page 94

APPENDIX C

Page 95

MCA 303 Data Base Management System

UNITI Purpose of data base systems data abstraction data models, instances and schemas data independence data definition language, data manipulation language, database manager, database administrator, database users, overall system structure E-R model, E-R diagrams, reducing E-R diagrams to tables, generalization, aggregation, design of an E-R database schema.

UNITII Relational model structure of relational databases, the relational algebra, fundamental operations, additional operation, tuple relational calculus, domain relational calculus, modifying the database, deletion, insertion, updating views. Relational commercial language SQL, Query by Example, QUEL, integrity constraints, domain constraints, referential integrity, functional dependencies, assertions, triggers.

UNITIII Relational database design pitfalls in relational database design, normalization using functional dependencies, normalization using multi-valued dependencies, join dependency, domain key normal form, mapping relational data into files, data dictionary, storage buffer management. Crash recovery failure classifications storage hierarchy transaction model log based recovery buffer management check points - shadow paging, failure with loss of non volatile storage stable storage implementation. Database security, integrity and control security ad integrity threats defense mechanisms, security specification in SQL statistical databases. Salient features of Oracle I Sybase, Client server models.

Text Book: Data Base Management System Concepts, Korth and A. Silberschatz, Second Edition, McGraw Hill Inc., 1991 Chapters: 1,2,3,4,5,6,7,8, 10 &16 Reference Books: 1. An Introduction to Data Base Systems, B. C. Desai, West Publishing Company,1990 2. Fundamentals of Data Base Systems, R. Elmaori and S.B. Navathe, Benjamin Cummings, Redwood city, 1994
Page 96

3. Relational Databases, Theory and Practice, Occardi, BPB 4. Books from Oracle Pres and Sybase Corporation 5. Introduction to Database Systems, Edn., C.J. Date, Addison Wesley, 1995 6. Principles of Database Management, James Martin, PHI, 1998

Page 97

Das könnte Ihnen auch gefallen