DBMS

Department of Computer Science Data Base Management Systems Laboratory Manual

Data Base Management System lab manual

CONTENTS
1. 2. Creating tables for various relations. Implementing the queries in SQL for a) Insertion. b) Retrieval. c) Updation. d) Deletion. SQL Reporting. Creating views. Introduction to pl/sql Implementing operations on relations. Writing Cursors. Exception handling. Writing function. Writing procedure Writing package. Writing Triggers. Creating Forms and Generating Reports

3. 4. 5. 6. 7. 8. 9. 10. 11. 12.

1

DBMS

Department of Computer Science Data Base Management Systems Laboratory Manual

Introduction to Database Management System
All database management systems (oracle is a DBMS) allows users to create containers for data storage and management. These containers are called ‘cells’. The minimum information that has to be given to oracle for suitable container to be constructed which can hold free form human data is  The cell/field name  The cell/field length  The type of data that can be placed in to the cell. We imagine that each field was an object created for us by oracle. Then number of fields created in same horizontal plane would be another object created for us by oracle. Multiple fields placed in the same horizontal plane is an object called a Record by oracle. Several ‘Records’, of equal length, placed one below the other to enable users to continue to store data is called a ’Table’(consists of rows and columns used for storing data). The table therefore becomes the third object after fields and rows. A GROUP of ‘Tables’ with ‘related’ data in them is called a ’database’. Relational data base management system Relational data base management system uses only its relational capabilities to manage the information stored in its database.

2

DBMS

Department of Computer Science Data Base Management Systems Laboratory Manual

Introduction to SQL SQL stands for Structured Query Language. Oracle provides many extensions to ANSI SQL.SQL is standard language for interfacing with a relational database. A table is primary database object of SQL ,which is used to store the data in the form of rows and columns. SQL developed by IBM is used as standard language to access data from database. In order to communicate with database SQL has been divided into three sub languages and each sub language consists of different commands, they are

a) Data Definition Language DDL COMMANDS: CREATE ALTER DROP b) Data Manipulation Language DML COMMANDS: SELECT INSERT UPDATE DELETE c) Transaction Commit Language TCL COMMANDS: COMMIT ROLLBACK SAVEPOINT

3

2.  Varchar2(size) variable length character data.s) Variable-length numeric data (fixed or floating point).DBMS Department of Computer Science Data Base Management Systems Laboratory Manual EXERCISE -1 DATA TYPES In order to create a data base object (table) we need to specify a data type of that particular columns while creation of that table itself. A data type associates a fixed set of properties with the values that can be used in a column of a table or in an argument of a procedure or function. Internal data type. Composite data type. Oracle supplies the following built-in data types: CHARACTER DATATYPES  Char(size) Fixed-length character data of length size bytes(maximum 2000 bytes per row . NUMBER DATATYPE  Number(p. Oracle mainly supports two types of data types.default size is 1 byte per row). These properties cause oracle to treat values of one data type different from values of another data type. 4 . 1.

SYNTAX: for creating a table create table <table name>(columnname data type(size).DBMS Department of Computer Science Data Base Management Systems Laboratory Manual DATE DATATYPE  Date Fixed length date and time date. 5 .columnname datatype(size)). USER DEFINE DATATYPES: Like the oracle internal data types that are already present the user can create new data type. The standard format is dd-mon-yy. LONG DATATYPE  Long Cell/field defined as LONG can store variable length character strings containing upto 65.use the appropriate functions. When we define the data type we use create or replace command.535 characters. To enter dates other than standard format .

Column cccccccolname empname emp no.2)). varchar2(6).address varchar2(30).2 Its code is as followed SQL> CREATE TABLE employee (empname varchar2(20). Address Pin code Salary data type varchar2 varchar2 varchar number number size 20 6 30 6 10.pin code number(6).salary number(10.emp no.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual For example: create a table which describes employee particulars. 6 .

constraint constraint_specification). Constraint clauses can appear in either CREATE TABLE or ALTER TABLE commands. SYNTAX to define an integrity constraint . Integrity constraints: An integrity constraint is the rule that restricts the values for one or more columns in a table. 7 . NOTE: Column_constraint table that appears in an ALTER Table statement can only define or remove a NOT NULL constraint. column_name datatype . Table_constraint::= create table <table_name>(column_name datatype . Column_constraint::= create table <table_name>(column_name datatype .constraint constraint_name constraint_definition (column_names)). NOTE: This syntax can define any type of integrity constraint except a NOT NULL constraint.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual CONSTRAINTS Constrains are the mechanism used in oracle in order to prevent invalid data or to avoid the duplicacy of the data being entered by the user.

 Check constraint Syntax: create table <table_name> (column_name datatype check <condition>). Domain Integrity Constraint.<constraint> [constraint-name] primary key).DBMS Department of Computer Science Data Base Management Systems Laboratory Manual There are three types of constraints 1.  Unique_constrain syntax: create table <table_name>(column definitions .  Primary key syntax: create table <table_name>(column definitons .  Not Null Constraint Syntax: create table <table_name> (column_name datatype Not Null). Entity Integrity Constraint. 2. Note: The DISABLE option oracle to define the constraint but not enforce it.constraint [constraintname] unique). 8 .

Syntax: create table <table_name>(column definitons . Foreign key This identifies the column or combination of columns in the child table that makes up of the foreign key . Syntax: create table <table_name>(column definitons . create the following tables with the help of above example.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual 3.. Referential Integrity Constraint. 4. 9 .<constraint> [constraintname] reference <parents table_name>< column_name>).<constraint> [constraintname] reference <parents table_name>< column_name>). On Delete Cascade Allows deletion of referenced key values in the parent table that have dependent rows in the child table and causes oracle to automatically delete dependent rows from the child table to maintain referential integrity.

DBMS Department of Computer Science Data Base Management Systems Laboratory Manual TABLE STRUCTURE FOR DBMS LAB I DEPARTMENT: DCODE number DNAME varchar2 EMPLOYEE: ECODE number ENAME varchar2 GCODE varchar2 DOB date DOJ date DCODE number SEX char BASIC number REPORTTO number (Same as ecode) PROGRAME: PCODE varchar2 ECODE number PROGSEC: PCODE PNAME DURATION DESCRIPTION GRADE: GCODE GNAME MAXBASIC MINBASIC RAISE varchar2 varchar2 number varchar2 varchar2 varchar2 number number number II III IV V 10 .

group by clause can also have not selected columns..] [desc] this clause is used to get the result in sorting order of columns specified in the same clause.] this clause is used to diplay selected columns. GROUP BY column1..column2. OPTIONAL CLAUSES: WHERE condition1 [and condition2 [or condition3]] this clause is used to give some condition which can be imposed on selected columns...colum2[.. ORDER BY column1[.. FROM table1[..column3..column2 Whenever you want to select column name along with group funcitons you should include those columns in group by clause..table2..DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise -2 BASIC CLAUSES IN SQL: SELECT colum1..] this clause is used to select the source tables. 11 .

RTRIM. MAX.SQRT. LENGTH. MONTHS_BETWEEN. STRING FUNCTIONS: LOWER.using this usually we will check the funcitons.LPAD.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual HAVING condition. ROWID. This cluase should preceded by group by clause. COUNT NUMBER FUNCTIONS : ABS.POWER. RPAD DATE FUNCTIONS : ADD_MONTHS. We use this to give column selection conditions which cannot be achieved by where clause(row selection condition). LAST_DAY 12 . LTRIM. INITCAP. MIN. LEVEL. UPPER. The following in built functions in oracle are just a few selected from many functions that are most commonly used in commercial application development.ROUND. SUM. SYSDATE AGGREGATE OR GROUP FUNCTIONS : AVG. NEXT_DAY. PSEUDO COLUMNS: ROWNUM. DUAL is a table which consists single column and single row. SUBSTR.

2. TO_NUMBER MISLENIOUS FUNCITONS: DECODE. Insert values into one table using other table. Delete specific rows from a table. Exercise-2(D) 1. 2. 1. 3.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual CONVERSION FUNCTIONS: TO_CHAR. Select specific columns from a table. Exercise-2(C) Update a single column value in a table. Insert values into your table for all columns. Select distinct columns from a table. 2. Exercise-2(A) Insert values into your table for specific columns. Exercise-2(B) 1. 2. 4. Update more than one column value in a table. Delete all rows from a table. Select specific columns by changing column headings. 13 . 3. Note: For the detailed information of above mentioned functions refer to complete reference Or sql/pl/sql by Oracle press write the following queries 1. Select today's date using dual table. TO_DATE. TRANSLATE.

DEPTNO<>DEPT.MGR FROM EMP A. NORMAL JOIN CARTISIAN PRODUCT SELECT * FROM EMP.DEPTNO=DEPT.EMPNO=B.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual JOINS Introduction to Joins different or same tables(is done using concept called JOINS): Examples are shown below which covers different types of joins.DEPTNO 3. DEPT WHERE EMP. EQUI JOIN & NON EQUI JOIN SELECT * FROM EMP. EMP B WHERE A. DEPT WHERE EMP. 1. SELF JOIN SELECT EMPNO.MGR 14 .DEPT 2.DEPTNO SELECT * FROM EMP.

Get list of all employees in a particular age group. Get the program code at runtime.DEPTNO SELECT EMPNO. DEPT WHERE EMP.ENAME FROM EMP. lpad(string.ENAME FROM EMP. Get list of all employees who had attended a particular training program. Specify the age group like 22-30 yrs (hint:months_between). 3. grade description.total no of characters.DEPTNO(+) Write the following queries. DEPT WHERE EMP. Get the number of employees. OUTER JOIN  LEFT OUTER JOIN  RIGHT INNER JOIN SELECT EMPNO.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual 4.apply lpad to gcode to get like g1--------------------. current basic and maximum basic in current grade. 1.format) 2.DEPTNO=DEPT. Get a list of all employees in a particular department along with their gradecode. 15 .and average basic in each department for every grade.in total 35 characters along with gcode.DEPTNO(+)=DEPT. 5. Get the list of all employees whose first letters of the names have been specified. 4.

' set pause on Output: Solution to the first query list of all employees Employees Name ... SET PAUSE 'more.... . SET HEADSEP * SET FEEDBACK off SET NEWPAGE 2 TTITLE 'Solution to the first query * list of all employees' BTITLE 'CMRCET' COLUMN ename HEADING 'Employees * Name' format a10 SET PAGESIZE 24 select ename from emp order by ename desc. CMRCET 16 .DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exerice:3 SQL REPORTING: EXAMPLE: Q: To get the list of all employees in their of order of employee names REM first programe..

Get the following report on emp table where paydate(first salary taken date) should be the last friday of the month if employee's hiredate is before 15th of that month otherwise first friday of next month. ename as Employee Code Department Name Get the gname at runtime and give the following report rem set headsep set feedback ttitle btitle column ename column dname accept gname prompt like enter grade name break on department name duplicate skip set pause Employee Name 3.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Generate SQL Report for the following queries using above sql report commands 1. employee name.dcode as Employee . Get the details of employee number. 5. empno ename hiredate paydate 4. employee's department name. employee grade name using above sql reporting commands Get the departments which do not have employees. Get the list of all employees in reverse order of employee code. 17 . Department Name 2. display ecode as Employee .

distinct clause. We can rename the base table column in our view with column alias in the select query. 5. even numbered rows of employee table. 18 . 3. Example: create view dsk as select empno eno from emp. Create a view with ename. 1. Write queries for following .gname. Delete duplicate rows from a table except last occurrence.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise -4 INTRODUCTION TO SIMPLE VIEWS: VIEW is a logical object. should not have aggregate functions. this will be created by using other tables with select statement. maximum basic for ecode 3 and ename='CMRCET'. Create a view to get a list of training programs attended by employee 'CMRCET' or another with ecode 2. To create a view to get the current grade. increment step. We use views to hide the table names and query coplexity from user.group by or having clause. UPDATABLE VIEWS: This View should contain the mandatory columns of base tables. Create views which should contain odd. 2.dname. 4. current basic. Using drop view <viewname> we can destroy a view.

19 . Number  Float  Integer character type  char  varchar2 Boolean Date 2. 3. 4.%ROWTYPE) <Executable statements> Exception <Exception handling> End.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise -5 Introduction to PL/SQL: Pl/sql is a completely portable .high performance transaction processing language . The basic pl/sql program structure is as following Declare <All declarations> Begin (%TYPE. DATA TYPES BUILT-IN DATA TYPES 1.

If <condition> then <statements> elsif <condition> then <statements> else <statements> End if.. 20 . While loop: While <condition> loop <statements> end loop.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Control Structures: 1. 2. Loops: 1. <end value> loop <statements> end loop 4. If <condition> then <statements> End if. 2. Simple loop: loop <statements> exit <condition> end loop 3. GOTO: <<lablename>> <statements> go to lablename. For loop: for <counter> in <startvalue> .

3. 21 . To print prime numbers between 100 and 500. To find whether the given number is palindrome or not ? To find all Armstrong number below given number.value_error and your exceptions. 2.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Write the following specified programs 1. 4. consonants and length of the given string (Hint: substr). To handle zero_divide. vowels. To count the words. 5.

That is. 5. Few of the pre defined oracle errors are 1. When an error occurs . Invalid_number Login_denined No_data_found Not_logged_on Program_error Zero_divide 22 . dup_val_on_index: Try to store duplicate values in a database column that is constrained by a unique index. 3. Internal exceptions are raised implicitly (automatically) by runtime system.Unlike internal exceptions. 7.a warning or error condition is called an exception. Ect. user defined exceptions must be given names. exception is raised.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise –6 Exceptions In pl/sql . normal execution stops and control transfers to the exception-handling part of that pl/sql block or subprogram. 6. User-defined exceptions must be raised explicitly by RAISE statements. Exceptions can be internally defined (by the runtime system) Or user defined . which can also predefined exceptions.. 2. 4.

DBMS Department of Computer Science Data Base Management Systems Laboratory Manual USER_DEFINED EXCEPTION A USER_DEFINED EXCEPTION should be declared and raised explicitly by a raise statement. It can be declared only in the declarative part of the pl/sql block.write a pl/sql block to raise an exception if employee number read is not found when employee details are displayed. The syntax is as follows: <exception_name> exception. 23 . 2. The syntax for ‘raise’ statement follows. Raise<exception_name>. Write a program to implement Not_logged_on exception. 1.

These parameters are to substitute in cursor declaration. BEGIN < Select statements>. DECLARE CURSOR <Cursorname> IS <Select statement>. We use OPEN. PARAMETRIC CURSORS: Parameterized cursors is used to give parameters while opening the cursor.which is its name. 24 . A PL/SQL construct called cursor lets us you name a work area and access its stored information.  EXPLICIT CURSORS These cursors are always defined by the user in PL/SQL block with the following syntax.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise –7 CURSORS Oracle uses work areas to execute SQL statements and store processing information. END. We can use the Implicit cursor as SQL .  IMPLICIT CURSOR: Is the cursor which is always generated Implicitly by the oracle. There are 2 types of cursors. FETCH. CLOSE statements to control a Cursor.

CURRENT OF <cursorname> Is used in where clause to update the current record of cursor but cursor should have for update clause.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual CURSOR ATTRIBUTES: %FOUND %NOTFOUND %ISOPEN %ROWCOUNT Using the above attributes we can Know the different states of cursor. FOR UPDATE CLAUSE: Is used to restrict update on particular columns by selecting those columns in for update clause. CURSOR FOR LOOP: FOR VARIABLE IN CURSOR LOOP <statements> END LOOP. 25 .

If Basic is greater than Rs.3000. 26 . If Basic is between Rs. 1.500. 2.200.00. Write a program to update the database using cursors based on the following conditions handling exceptions. 5 6 Write a program to delete a particular row using cursor. Write a program to print rows from last to first using cursor.1501. If Basic is greater than Rs.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual EXERCISE 1 2 3 4 Write a program to display employee table using cursor also handle cursor exceptions.3000.750. 3. Write a program to find experience of each employee using parameterized cursor.00 and Rs.00 then give increment of Rs. Write a program to display employee name and department name using one cursor.00 then give increment of Rs.00.00.1500.00 then give increment of Rs.

so we write the same set of statements as a subprogram. b number)return number is C number. 2. A subprogram can be a function or procedure in PL/SQL which has to be created separately as a database object. Write a function to check the existing of employee for given employee number. Return C. End. To get the function result we have to assign function to returntype variable. we use the same set of statements to be executed for the different values. FUNCTION Basically function is to return a value of various data types available. Example: Create or replace function add(a number. Write a function to get the factorial of given number. Exercise: 1. Begin C:=a+b. 27 .DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise-8 SUBPROGRAMS A subprogram is used to reduce the program in size. Function can't return more than one value.

b in number. 2. Write a procedure to insert a particular record in some other table while deleting from a table. MODES OF PARAMETER: IN Read only value Right side of := literal. Write a procedure to insert a row into your table. Read&Write Value Left & Right side of := Only Initialized variable 28 .expression. c out number) is Begin C:=a+b. End. Exercise: 1. Write only value Left side of := Only Un initialized variable.variable OUT IN OUT Example: Create or replace procedure add(a in number. we use parameters to get the result of procedures.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise-9 PROCEDURE Basically a procedure is used to perform some task which may return one value or more than one value or no value.

(by discarding create or replace as in ordinary function). Before creating the package body there should be package specification for that package. cursors that are common for the entire package. (by discarding create or replace as in ordinary procedure). The functions and procedures in that packages are treated as members of that package object but not as database objects. procedure prototype declaration of a procedure. PACKAGE SPECIFICATION: create or replace package <packagename> as variable that you want to include in this package. function prototype declaration of a function with return type. end <packagename> PACKAGE BODY: create or replace package body <packagename> as body of a function . end <packagename> 29 . body of a procedure .DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise -10 PACKAGE: Package is used to group the related functions and procedures of a database. A Package will be created as 2 different objects package specification and package body.

negative respectively. Include following procedures. a) Procedure that displays a number in words for a given integer. 2. ispositive.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise: 1. variables: a)Pi value b)e value cusors: a)cursor that with all the columns of employee table. Armstrong. variables in the above package. 30 . isarmstrong. b) Procedure that deletes the records in a table based on the parameter. Write a package with functions isprime. b)cursor that can have only department 10 employee details. isnegative to check whether the given number is prime. positive.

31 . INSTEAD OF trigger is only for views.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise-11 TRIGGER A Trigger is PL/SQL block which can be executed without explicit calling at the time of DML operations on a table.. Types of Triggers: Triggers are categorized base on when they are fired:     Before After For each row For each statement(default) Syntax: create or replace trigger <triggername> {before/after/instead of} {insert/delete/update[of column1[.column2.]]} on <table name/view name > [for each statement/ row] [when <condition>] DECLARE <declarations> BEGIN <executable statements> END.

2. selected(appno. phno. enmail. address. Create a trigger before insert/update/delete of employee details to stop the transactions on Saturdays and Sundays. 2) A sub query cannot be included in when clause. hiredate. ename. dob. 3. 1. appno). designation).DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Note: 1) A Database trigger can also have declarative and exception Handling parts. sal. dob. qualification. application(appno. Create a trigger to check detail records while deleting or updating master records at master table. email). Alter table <tablename> disable all. dateofInterview). 32 . address. phno. personal(empno. create necessary triggers which insert employees personal details in personal table after inserting in employee table. EXERCISE TABLES FOR NEXT EXERCISE employee(empno. Enable/Disable: Alter trigger <triggername> enable/disable.

Block . change or delete data from oracle database in A form based environment. submenu items And PL/SQL Code blocks. Form A Form module is nothing but collection of objects such as windows. Item These are objects contained in blocks. button.. items. checkbox. They can be span over many canvases. access. event based PL/SQL Code blocks called Form Triggers Menu Collection of Objects such as menu items. This library file is then attached to a form/menu.. canvas. that present data values to the user depending upon the item type(text. list . PL/SQL Libraries Collection of PL/SQL functions and procedures stored in a single Library file.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Exercise-12 FORMS Developer 2000 Forms is used to develop Client/Server applications by which can be used to enter. submenus.). Data block: Is associated with data(tables) with in the database Control block: Is not associated with any of the data in the database.radio group. 33 . Block A block is group of related items.

next increment date ( assume that every year from the joining date each employee get increment). 4. Trigger A forms object it associates a Pl/SQL block with an event. Develop a form to contain 3 different blocks on emp. salary. Generate a master details report with the department name and total no.DBMS Department of Computer Science Data Base Management Systems Laboratory Manual Canvasview A canvasview is a "surface" where visual objects are arranged. Create simple report in tabuler model with the details of employee ename. 5. 3. department name. which can hold the canavasview and allows to resize.of employees and total salary of that department. dept. Window window is similar to an empty picture frame. 34 . Enforce the constraints on this Develop a form to display the time and college name in a form using control block. 2. Exercise 1. move the canvaseview. emp tables along with navigation items. REPORTS Data model which is used to give the query and Data model-> editor -> SQL -> click in the editor: Q1 -> properties Select the necessary columns from tables to get the report. salgrade tables. Develop a master detail blocks form for dept.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.