P. 1
Dbms Complete Lab Manual

Dbms Complete Lab Manual

|Views: 89|Likes:
Published by Jugal K Sewag

More info:

Published by: Jugal K Sewag on Nov 15, 2011
Copyright:Attribution Non-commercial

Availability:

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

09/28/2015

pdf

text

original

DataBaseManagementSystems LAB MANUAL

A Helpful Hand

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING CSEROCKZ

1

WWW.CSEROCKZ.COM

DataBaseManagementSystems LAB MANUAL
How to Write and execute sql, pl/sql commands/programs:
1). Open your oracle application by the following navigation Start->all programs->Oracle Database 10g Express Edition ->Run SQL Command Line 2). You will be asked for user name, password. You have to enter user name, pass word. 3). Upon successful login you will get SQL prompt (SQL>). In two ways you can write your programs: a) directly at SQL prompt (or) b) in sql editor. If you type your programs at sql prompt then screen will look like follow: SQL> SELECT ename,empno, 2 sal from 3 emp; where 2 and 3 are the line numbers and rest is the command /program…… to execute above program/command you have to press ‘/’ then enter. Here editing the program is somewhat difficult; if you want to edit the previous command then you have to open sql editor (by default it displays the sql buffer contents). By giving ‘ed’ at sql prompt.(this is what I mentioned as a second method to type/enter the program). in the sql editor you can do all the formatting/editing/file operations directly by selecting menu options provided by it.

2

WWW.CSEROCKZ.COM

DataBaseManagementSystems LAB MANUAL
To execute the program which saved; do the following SQL> @ programname.sql (or) SQL> Run programname.sql Then press ‘\’ key and enter. To save the day`s session ;do the following SQL>commit; This how we can write, edit and execute the sql command and programs. Always you have to save your programs in your own logins. Background Theory
Oracle workgroup or server is the largest selling RDBMS product.it is estimated that the combined sales of both these oracle database product account for aroud 80% of the RDBMSsystems sold worldwide. These products are constantly undergoing change and evolving. The natural language of this RDBMS product is ANSI SQL,PL/SQL a superset of ANSI SQL.oracle 8i and 9i also under stand SQLJ. Oracle corp has also incorporated a full-fledged java virtual machine into its database engine.since both executable share the same memory space the JVM can communicate With the database engine with ease and has direct access to oracle tables and their data. SQL is structure query language.SQL contains different data types those are 1. char(size) 2. varchar(size) 3. varchar2(size) 4. date 5. number(p,s) //** P-PRECISION S-SCALE **// 6. number(size) 7. raw(size) 8. raw/long raw(size)

Different types of commands in SQL:
3

WWW.CSEROCKZ.COM

Syntax: Alter table <tablename> modify(<col><newdatatype>(<newsize>)).To retrieve the data from a database.DCL/DTL commands: . Syntax: Create table <table name> (<col1> <datatype>(<size>).<new col>datatype(size)).<col2> <datatype><size>)).it defines each column of the table uniquely. 4 WWW.DQL command: . 3. data type and size. Ex: create table emp(empno number(4) primary key. Dropping a column from a table. Modifying the structure of tables.To manipulate data of a database objects C).DDL commands: . Ex: alter table emp add(sal number(7.To create a database objects B). ename char(10)). Modifying existing columns.DML commands: .COM . 4.To control the data of a database… DDL commands: 1. Ex: alter table emp drop column sal. D). 2. Syntax: Alter table <tablename> drop column <col>.DataBaseManagementSystems LAB MANUAL A).CSEROCKZ. a name .2)). Each column has minimum of three attributes. The Create Table Command: . a)add new columns Syntax: Alter table <tablename> add(<new col><datatype(size).

Renaming the tables Syntax: Rename <oldtable> to <new table>. Ex: rename emp to emp1. Syntax 1: 5 WWW.once a table is created the most natural thing to do is load this table with data to be manipulated later. Inserting Data into Tables: . Ex: drop table emp.DataBaseManagementSystems LAB MANUAL Ex: alter table emp modify(ename varchar2(15)). 5. Syntax: Truncate table <tablename>. 7.CSEROCKZ. Ex: trunc table emp1. Destroying tables. 6. DML commands: 8.COM . Syntax: Drop table <tablename>. truncating the tables.

Syntax 2: insert into <tablename> values(&<col1>.’104B’. Ex 3: insert into skc values(‘sri’.’27-feb-05’.00).DataBaseManagementSystems LAB MANUAL insert into <tablename> (<col1>. <val 2>……. Delete operations.COM .&<col n>).&class)..<val n>). 9.&roll no. Syntax 3: insert into <tablename> values(<val 1>.<val n>).10000.CSEROCKZ.’104B’.cse’.’27-feb-05’.10000.<col n>) values(<val 1>.class.dob. enter sname:’sri’ enter roll no:’104B’ enter class:’cse’ 1 row created.fee_paid) values(‘sri’.. Ex 1: Insert into skc (sname.<val 2>……. Ex 2: insert into skc values(&sname.00).&<col2>……. b) removal of a specified row/s Syntax: 6 WWW.rollno.<col2>…. a) remove all rows Syntax: delete from <tablename>.’cse’.

unique(<col1>. Syntax: <col><datatype>(size)not null b) unique constraint Syntax: Unique constraint at column level.<col>=<exp> where <condition>.<col2>).col=format. Updating the contents of a table. d) primary key constraint at column level 7 WWW. a) not null constraint at column level. 11.CSEROCKZ. Types of data constrains.DataBaseManagementSystems LAB MANUAL delete from <tablename> where <condition>.COM . 10. <col><datatype>(size)unique. c) unique constraint at table level: Syntax: Create table tablename(col=format. a) updating all rows Syntax: Update <tablename> set <col>=<exp>. b) updating seleted records. Syntax: Update <tablename> set <col>=<exp>.<col>=<exp>.

CSEROCKZ.<col2>). Viewing data in the tables: .<col>) h) check constraint check constraint constraint at column level. e) primary key constraint at table level. Syntax: Create table tablename(col=format.<col>]) references <tablename>[(<col>.COM .DataBaseManagementSystems LAB MANUAL Syntax: <col><datatype>(size)primary key. Syntax: check(<logical expression>) DQL Commands: 12. Syntax: <col><datatype>(size>) references <tablename>[<col>]. g) foreign key constraint at table level Syntax: foreign key(<col>[.col=format primary key(col1>. the next most logical operation would be to view what has been inserted. Syntax: <col><datatype>(size) check(<logical expression>) i) check constraint constraint at table level.once data has been inserted into a table. f) foreign key constraint at column level. 8 WWW.

<col2> <[sortorder]>.The rights that allow the user of some or all oracle resources on the server are called privileges. 14.while viewing data from a table. Sorting data in a table. Hence. Filtering table data: .COM . a) Grant privileges using the GRANT statement The grant statement provides various types of access to database objects such as tables.CSEROCKZ. Select * from tablename.<col2> from <tablename>. b) selected rows and all columns: Syntax: select * from <tablename> where <condition>. Syntax: Select * from <tablename> order by <col1>. DCL commands: Oracle provides extensive feature in order to safeguard information stored in its tables from unauthoraised viewing and damage. it is rare that all the data from table will be required each time.views and sequences and so on. Syntax: GRANT <object privileges> ON <objectname> 9 WWW. 13. a) Selected columns and all rows: Syntax: select <col1>.DataBaseManagementSystems LAB MANUAL a) all rows and all columns Syntax: Select <col> to <col n> from tablename. sql must give us a method of filtering out data that is not required data. c) selected columns and selected rows Syntax: select <col1>.<col2> from <tablename> where<condition>.

sname varchar(20). WEEK-1 CREATING. Name Null? Type ----------------------------------------. dob date. b) Reoke permissions using the REVOKE statement: The REVOKE statement is used to deny the Grant given on an object. Syntax: REVOKE<object privilege> ON FROM<user name>. EXAMPLE 1: CREATING A STUDENT RELATION TABLE WITH ALL DATATYPES: SQL> create table student252( sid number(5).DataBaseManagementSystems LAB MANUAL TO<username> [WITH GRANT OPTION]. RELATIONAL SCHEMA FOR STUDENT RELATION : SQL> desc student252.CSEROCKZ. sbranch char(5).-------.---------------------------SID NUMBER(5) 10 WWW. spercent number(3.ALTERING AND DROPPING TABLES AND INSERTING ROWS INTO A TABLE (USE CONSTRAINTS WHILE CREATING TABLES) EXAMPLES USING SELECT COMMAND .COM . Table created.2)).

sbranch.--------------------.&dob.dob.‘sri’.’27-feb-05’. ‘&sname’.’&sbranch’.sbranch. SID -----130 131 129 104 SNAME SBRANCH DOB SPERCENT --------------.. 1 row created.70).’cse’.CSEROCKZ.70). 1 row created. QUERY THE TABLE VALUES: ALL ROWS AND ALL COLUMNS: SQL> select * from student252.’27feb-05’.‘sri’. METHOD 4: SQL>Insert into Student252(sid.. 1 row created.DataBaseManagementSystems LAB MANUAL SNAME SBRANCH DOB SPERCENT VARCHAR2(20) CHAR(5) DATE NUMBER(5.&spercent).spercent) values(&sid. METHOD 3: SQL>Insert into Student252(sid.dob. METHOD 2: SQL>Insert into Student252 values(104.sname.sname.sbranch.spercent) values(&sid.sname.COM .&sbranch.2) INSERT THE RECORDS INTO STUDENT RELATION: METHOD 1: SQL>Insert into Student252(sid. &sname. 1 row created.’cse’.--------------.dob.&spercent).-------------------ravi it 30-1-95 60 teja cse 21-07-87 55 kiran mech 12-05-92 60 sri cse 30-07-90 70 11 WWW.’&dob’.spercent) values(104.

CSEROCKZ. ENO ENAME ESAL DEPTNO AGE ----. Table altered.---------.---------.-------------------.DataBaseManagementSystems LAB MANUAL 133 137 sajith ram ece eee 12-06-89 07-07-85 55 40 WEEK 2 (cont…1) 1) Creation. MODIFYING EXISTING COLUMN SQL> ALTER TABLE Emp252 MODIFY (phno varchar(20)). DROPING A COLUMN SQL> ALTER TABLE Emp252 DROP COLUMN phno. altering and dropping tables and inserting rows into a table (use constraints while creating tables) examples using SELECT command.COM . QUERY FOR THE TABLE VALUES SQL> SELECT * FROM Emp252. Table altered.---------30 ravi 51000 3 31 teja 31000 2 12 WWW. Table altered. phno number(10)). MODIFYING THE STRUCTURE OF TABLE ADDING A NEW COLUMN SQL> ALTER TABLE Emp252 ADD (age number(3).

---------. QUERY THE TABLE VALUES SQL> SELECT * FROM Emp252. Table renamed.---------30 ravi 51000 3 18 31 teja 31000 2 18 29 kiran 31200 1 18 45 allen 41000 3 18 33 sajith 51000 4 18 46 geetha 11000 4 18 90 veena 16000 3 18 85 pragna 61000 1 18 84 harsha 91000 3 18 40 sanjeev 1500 13 18 10 rows selected. UPDATING ENTIRE COLUMN SQL> UPDATE Emp252 SET age=18.-------------------. RENAMING THE TABLE: SQL> RENAME Emp252 TO Emp1252.CSEROCKZ. ENO ENAME ESAL DEPTNO AGE ----. 10 rows updated.COM .---------.DataBaseManagementSystems LAB MANUAL 29 45 33 46 90 85 84 40 kiran allen sajith geetha veena pragna harsha sanjeev 31200 41000 51000 11000 16000 61000 91000 1500 1 3 4 4 3 1 3 13 10 rows selected. 13 WWW.

---------------------------DNAME VARCHAR2(10) DNO CHAR(5) DLOC VARCHAR2(25) DROPING THE TABLE SQL> DROP TABLE Dept252.-------. Example 3 CREATING A DEPARTMENT RELATION TABLE CREATING A DEPARTMENT TABLE SQL> CREATE TABLE Dept252( dname VARCHAR(10). Name Null? Type ----------------------------------------. dno CHAR(5). WEEK 3 (cont…1) 1) Creation.DataBaseManagementSystems LAB MANUAL SELECTING THE TABLE VALUES SQL> SELECT * FROM Emp1252. dloc VARCHAR(25)). altering and dropping tables and inserting rows into a table (use constraints while creating tables) examples using SELECT command. Table dropped. DESCRIBE A STUDENT TABLE SQL> desc Dept252. 14 WWW. Table created.CSEROCKZ.COM .

10000) 1 row created. 20000) 1 row created. Table created.DataBaseManagementSystems LAB MANUAL CREATING A TABLE WITH KEY CONSTRAINTS Example 1 CREATING A TABLE WITH ‘UNIQUE ‘. SQL> / Enter value for eid: 2 Enter value for ename: 'teja' Enter value for age: 18 Enter value for esal: 20000 old 1: INSERT INTO emp252 VALUES (&eid. 18. &age. &ename. &age. &ename. &age. &esal). &ename. INSERTING RECORDS INTO TABLE: SQL> INSERT INTO emp252 VALUES (&eid. esal NUMBER(7) CHECK(esal > 1000)). age NUMBER(3) NOT NULL.CSEROCKZ. &esal) new 1: INSERT INTO emp252 VALUES (1. ename VARCHAR(10) DEFAULT(‘UNKNOWN’). ‘CHECK’ AND ‘DEFAULT’ CONSTRAINT: SQL> CREATE TABLE emp252 (eid NUMBER(5) UNIQUE. 'teja'. 15 WWW.COM . 'ravi'. 18. Enter value for eid: 1 Enter value for ename: 'ravi' Enter value for age: 18 Enter value for esal: 10000 old 1: INSERT INTO emp252 VALUES (&eid. ‘NOT NULL’. &esal) new 1: INSERT INTO emp252 VALUES (2.

&ename. 30000) 1 row created. 19. 29000) [SHOWING AN ERROR WHILE VIOLATING UNIQUE KEY CONSTRAINT] * ERROR at line 1: ORA-00001: unique constraint (SYSTEM. SQL> / Enter value for eid: 1 Enter value for ename: 'alan' Enter value for age: 19 Enter value for esal: 29000 old 1: INSERT INTO emp252 VALUES (&eid. &age. 25000) 1 row created. 'kiran'.DataBaseManagementSystems LAB MANUAL SQL> / Enter value for eid: 3 Enter value for ename: 'kiran' Enter value for age: 19 Enter value for esal: 25000 old 1: INSERT INTO emp252 VALUES (&eid. 19. &ename. 29000) INSERT INTO emp252 VALUES (1.CSEROCKZ. 19. 'alan'.SYS_C003875) violated SQL> / Enter value for eid: 7 Enter value for ename: 'dravid' Enter value for age: null 16 WWW. &esal) new 1: INSERT INTO emp252 VALUES (1. SQL> / Enter value for eid: 4 Enter value for ename: 'srinivas' Enter value for age: 19 Enter value for esal: 30000 old 1: INSERT INTO emp252 VALUES (&eid. &age. &age. &esal) new 1: INSERT INTO emp252 VALUES (3.COM . 'srinivas'. &esal) new 1: INSERT INTO emp252 VALUES (4. 19. 'alan'. &ename.

&esal) new 1: INSERT INTO emp252 VALUES (7.COM . &ename. 'dravid'. PRIMARY KEY (dno)). dname CHAR(10). 100000) INSERT INTO emp252 VALUES (7.DataBaseManagementSystems LAB MANUAL Enter value for esal: 100000 old 1: INSERT INTO emp252 VALUES (&eid.SYS_C003874) violated Example 2 CREATING A TABLE WITH ‘PRIMARY KEY’ CONSTRAINT: SQL> CREATE TABLE mdept252 (dno NUMBER(5). &age. &ename. 100000) [SHOWING AN ERROR AS NOT NULL KEY CONSTRAINT IS VIOLATED] * ERROR at line 1: ORA-01400: cannot insert NULL into ("SYSTEM"."AGE") SQL> / Enter value for eid: 8 Enter value for ename: 'sachin' Enter value for age: 35 Enter value for esal: 100 old 1: INSERT INTO emp252 VALUES (&eid.CSEROCKZ."EMP230". null. dloc VARCHAR(10). 17 WWW. 100) INSERT INTO emp252 VALUES (8. 35. Table created. 100) * [NOT ALLOWING AS IT VOILATES CHECK CONSTRAINT FOR esal > 1000 VALUE] ERROR at line 1: ORA-02290: check constraint (SYSTEM. &esal) new 1: INSERT INTO emp252 VALUES (8. 'sachin'. 35. null. 'dravid'. 'sachin'. &age.

-------. 'kmm') 18 WWW. Name Null? Type ----------------------------------------. 'sajithulhuq'. &dloc) new 1: INSERT INTO mdept252 VALUES (1. SQL> / Enter value for dno: 1 Enter value for dname: 'teja' Enter value for dloc: 'sec' old 1: INSERT INTO mdept252 VALUES (&dno.---------------------------DNO NOT NULL NUMBER(5) DNAME CHAR(10) DLOC VARCHAR2(10) INSERTING RECORDS INTO MASTER DEPARTMENT TABLE: SQL> INSERT INTO mdept252 VALUES (&dno.COM . 'teja'. 'hyd') 1 row created. Enter value for dno: 1 Enter value for dname: 'ravi' Enter value for dloc: 'hyd' old 1: INSERT INTO mdept252 VALUES (&dno. 'teja'. &dname.DataBaseManagementSystems LAB MANUAL SQL> desc mdept252. &dloc). &dloc) new 1: INSERT INTO mdept252 VALUES (1. 'sajithulhuq'.CSEROCKZ. &dloc) new 1: INSERT INTO mdept252 VALUES (null. &dname. &dname.SYS_C003876) violated SQL> / Enter value for dno: null Enter value for dname: 'sajithulhuq' Enter value for dloc: 'kmm' old 1: INSERT INTO mdept252 VALUES (&dno. 'sec') * ERROR at line 1: ORA-00001: unique constraint (SYSTEM. 'sec') INSERT INTO mdept252 VALUES (1. 'kmm') INSERT INTO mdept252 VALUES (null. 'ravi'. &dname.

'ravi'."MDEPT230". esal NUMBER(7)).CSEROCKZ. 50000). 50000) * ERROR at line 1: 19 WWW. ALTER TABLE emp252 ADD PRIMARY KEY (eid) * [ GIVING AN ERROR AS ONE TABLE CAN HAVE A SINGLE PRIMARY KEY AT COLUMN LAVEL] ERROR at line 1: ORA-02261: such unique or primary key already exists in the table Example 3 CREATING A TABLE WITH ‘FORIEGN KEY’ CONSTRAINT: SQL> CREATE TABLE detailemp252 (eid NUMBER(5) REFERENCES mdept230 (dno).DataBaseManagementSystems LAB MANUAL * ERROR at line 1: ORA-01400: cannot insert NULL into ("SYSTEM".COM . Table altered."DNO") ADDING A PRIMARY KEY TO AN EXISTING TABLE: SQL> ALTER TABLE student252 ADD PRIMARY KEY (sid). INSERING RECORDS INTO DETAIL EMPLOYEE TABLE: SQL> INSERT INTO detailemp252 VALUES (2. Table created. ename VARCHAR(10). 'ravi'. INSERT INTO detailemp252 VALUES (2. SQL> ALTER TABLE emp252 ADD PRIMARY KEY (eid).

DataBaseManagementSystems LAB MANUAL
ORA-02291: integrity constraint (SYSTEM.SYS_C003877) violated - parent key not found SQL> INSERT INTO detailemp252 VALUES (1, 'teja', 60000); 1 row created. SQL> DELETE FROM mdept252 where dno=1; DELETE FROM mdept252 where dno=1 * ERROR at line 1: ORA-02292: integrity constraint (SYSTEM.SYS_C003877) violated - child record found SQL> SELECT * FROM detailemp252; EID ENAME ESAL ---------- ---------- ---------1 teja 60000 SQL> SELECT * FROM mdept252; DNO DNAME DLOC ---------- ---------- ---------1 ravi hyd

20

WWW.CSEROCKZ.COM

DataBaseManagementSystems LAB MANUAL
Exercise CREATING A CUSTOMER TABLE USING CONSTRAINTS : SQL> CREATE TABLE cust252 (cnum NUMBER(5), cname VARCHAR(10), state VARCHAR(10) DEFAULT ('ap'), phno NUMBER(5), CONSTRAINT cnum_pkkey PRIMARY KEY (cnum)); Table created. SQL> INSERT INTO cust252 VALUES (&cnum, &cname, &state, &phno); Enter value for cnum: 1 Enter value for cname: 'ravi' Enter value for state: 'bihar' Enter value for phno: 001 old 2: (&cnum, &cname, &state, &phno) new 2: (1, 'ravi', 'bihar', 001) 1 row created. SQL> / Enter value for cnum: 2 Enter value for cname: 'teja' Enter value for state: 'up' Enter value for phno: 007 old 2: (&cnum, &cname, &state, &phno) new 2: (2, 'teja', 'up', 007) 1 row created. SQL> / Enter value for cnum: 2 Enter value for cname: 'yama' Enter value for state: 'ap' Enter value for phno: 006
21

WWW.CSEROCKZ.COM

DataBaseManagementSystems LAB MANUAL
old 2: (&cnum, &cname, &state, &phno) new 2: (2, 'yama', 'ap', 006) INSERT INTO cust252 VALUES * ERROR at line 1: ORA-00001: unique constraint (SYSTEM.CNUM_PKKEY) violated SQL> / Enter value for cnum: 4 Enter value for cname: 'huu' Enter value for state: 'ap' Enter value for phno: 101 old 2: (&cnum, &cname, &state, &phno) new 2: (4, 'huu', 'ap', 101) 1 row created. SQL> SELECT * FROM cust252; CNUM CNAME STATE ---------- ---------- ---------- ---------1 ravi bihar 1 2 teja up 7 4 huu ap 101 PHNO

CREATING AN ITEM TABLE USING CONSTRAINTS: SQL> CREATE TABLE itm252 (ino NUMBER(3), iname VARCHAR(10), iprice NUMBER(4,3), qtyonhand VARCHAR(5), CONSTRAINT itm252_ino_pkkey PRIMARY KEY (ino), CONSTRAINT itm230_qtyoh_chk CHECK (qtyonhand>1)); Table created.
22

WWW.CSEROCKZ.COM

&qtyonhand) new 1: INSERT INTO itm252 VALUES (1.ITM230_INO_PKKEY) violated SQL> / Enter value for ino: 2 Enter value for iname: 'powder' Enter value for iprice: 3. &qtyonhand) new 1: INSERT INTO itm252 VALUES (2. &iname. &iname. &qtyonhand). 'pencil'.00. 0) INSERT INTO itm252 VALUES (2. 3) * ERROR at line 1: ORA-00001: unique constraint (SYSTEM. SQL> / Enter value for ino: 1 Enter value for iname: 'pencil' Enter value for iprice: 1. 1.00. &iprice.00 Enter value for qtyonhand: 0 old 1: INSERT INTO itm252 VALUES (&ino. 'powder'.CSEROCKZ. 1.COM . &iprice. 3. 3) INSERT INTO itm252 VALUES (1. 'rubber'. 3.00.00.50 Enter value for qtyonhand: 3 old 1: INSERT INTO itm252 VALUES (&ino.00 Enter value for qtyonhand: 3 old 1: INSERT INTO itm252 VALUES (&ino. 3) 1 row created. &iprice. &qtyonhand) new 1: INSERT INTO itm252 VALUES (1.50. 3. 'pencil'. 0) 23 WWW.DataBaseManagementSystems LAB MANUAL SQL> INSERT INTO itm252 VALUES (&ino. Enter value for ino: 1 Enter value for iname: 'rubber' Enter value for iprice: 3. &iprice. &iname. &iname. 'powder'.

24 WWW. Name Null? Type ----------------------------------------. qty NUMBER(5) NOT NULL. CONSTRAINT invoice252_ivnno_pkkey PRIMARY KEY (ivnno). qty NUMBER(5) NOT NULL. itemno NUMBER(5). itemno NUMBER(5).-------. SQL> CREATE TABLE invitm252 (invno NUMBER(5).ITM230_QTYOH_CHK) violated 1* CREATE TABLE invoice252(ivnno NUMBER(5). itmno)).---------------------------CNUM NOT NULL NUMBER(5) CNAME VARCHAR2(10) STATE VARCHAR2(10) PHNO NUMBER(5) CREATING A INVOICE TABLE USING CONSTRAINTS: SQL> CREATE TABLE invoice252 (ivnno NUMBER(5). itmno NUMBER(5). CONSTRAINT invitm252_invno_itmno_pkkey PRIMARY KEY (invno. CONSTRAINT fk_inv252 FOREIGN KEY (itemno) REFERENCES cust252 (cnum)) Table created.COM . qty NOT NULL. CONSTRAINT invoice252_ivnno_pkkey PRIMARY KEY(ivnno). CONSTRAINT FOREIGN KEY(itemno) REFERENCES cust252) SQL> desc cust252.DataBaseManagementSystems LAB MANUAL * ERROR at line 1: ORA-02290: check constraint (SYSTEM.CSEROCKZ.

address1 VARCHAR2(20). Constraints. EXISTS. ALL. IN. pin VARCHAR2(6). UNIQUE. address2 VARCHAR2(20). Table created. birth_date DATE. Insert the following data: 1 row created.CSEROCKZ. first_name VARCJHAR2(20) NOT NULL. INTERSECT. CUST NO 1001 1002 1003 LAST NAME UDUPI KUMAR BAHADUR FIRST NAME RAJ RAJ RAJ ADDRESS1 UPENDRABAU G SHANTHI VILLA ADDRESS2 NEAR KALPANA NEAR CITY UDP P UDP STATE KARNARAT A KARNATAK PIN 57610 1 57610 BIRTH DATE 12DEC-62 1-AUGSTATUS A A V 25 WWW. status VARCHAR2(1). ‘I’.COM . state VARCHAR2(20). last_name VARCHAR2(20). CHECH (status IN (‘V’. ‘A’)) ). NOT EXISTS.DataBaseManagementSystems LAB MANUAL Table created. Example: select the rollno and name of the student who secured 4th rank in the class TABLE DEFINITIONS SQL> CREATE TABLE Customer ( cust_no NUMBER(4) PRIMARY KEY. city VARCHAR2(3). WEEK 4 2) Queries (along with subqueries) using ANY.

COM . SELECT first_name. 4) To list all the columns for invalid persons. last_name FROM Customer WHERE state = ‘KARNATAKA’. SELECT first_name. SELECT first_name || ‘ ‘ || last_name. last_name FROM Customer WHERE status = ‘A’. SELECT first_name. SEELCT * FROM Customer. To list the name and address using concatenation. To select records where the pin code has not been entered.’ || city || ‘.DataBaseManagementSystems LAB MANUAL 1004 1005 1006 1007 SIMON KUTTY PAI JAIN FELIX RAJAN SHILPA RAKSHIT M-J-56 A1 TRADERS 12/4B BOSCO MALLIKA ALTOBETIM NEAR RLY STATION POLICE QUARTERS R.’ || address2 || ‘.CSEROCKZ. last name. last_name FROM Customer.K PLAZA PJM KNR MNG BNG A GOA KERALA KARNATAK A KARNATAK A 1 40300 2 67001 57415 4 57620 1 70 12-FEB71 9-JUN71 11DEC-70 1-JAN71 A A I A QUERIES 1) To list all the fields from the table Customer.’ || state || ‘-‘ || pin FROM Customer. To list the names of active customers. 2) To list the first name. SELECT * FROM Customer WHERE status = ‘I’. address1 || ‘. 3) To list the first name and last name of persons in Karnataka. SELECT * FROM Customer 26 5) 6) 7) WWW.

DataBaseManagementSystems LAB MANUAL
WHERE pin IS NULL;
8)

To select the single occurrence of any value from the table. SELECT DISTINCT state FROM Customer; To select rows of valid customers from Karnataka. SELECT * FROM Customer WHERE state = ‘KARNATAKA’ AND status = ‘V’; To select rows of customers from Karnataka or Kerala. SELECT * FROM Customer WHERE state = KARNATAKA’ OR state = ‘KERALA’; To sort the customer data in the alphabetic order of state. SELECT state, first_name, last_name, pin FROM Customer ORDER BY state; To sort in the descending order. SELECT state, first_name, last_name, pin FROM Customer ORDER BY state DESC; To sort the customer data, state wise and within state by the last name. SELECT state, first_name, last_name, pin FROM Customer ORDER BY state, last_name; To retrieve records of Karnataka customers who are valid. SELECT * FROM Customer WHERE UPPER(state) = ‘KARNATAKA’ AND UPPER(status) = ‘V’; To retrieve records of Karnataka/Kerala customers. SELECT * FROM Customer WHERE UPPER(state) = ‘KARNATAKA’
27

9)

10)

11)

12)

13)

14)

15)

WWW.CSEROCKZ.COM

DataBaseManagementSystems LAB MANUAL
OR UPPER(state) = ‘KERALA’;
16)

To retrieve records of Karnataka/Kerala customers who are active. SELECT * FROM Customer WHERE (UPPER(state) = ‘KARNATAKA’ OR UPPER(state) = ‘KERALA’) AND UPPER(status) = ‘A’; To retrieve records of Karnataka customers with pin code 576101. SELECT * FROM Customer WHERE LOWER(state) = ‘karnataka’ AND pin = ‘576101’; To retrieve rows where the state name begins with K and followed by any other character. SELECT first_name, last_name, state FROM Customer WHERE state LIKE ‘K%’; To retrieve rows where the first name contains the word RAJ embedded in it. SELECT first_name, last_name, state FROM Customer WHERE first_name LIKE ‘%RAJ%’; To retrieve rows where the address2 contains the word UDUPI or UDIPI in which the 3rd character may be anything. SELECT first_name, last_name, state FROM Customer WHERE address2 LIKE ‘UD_PI’; To retrieve rows where the cust_no has data representing any value between 1003 and 1005, both numbers included. SELECT * FROM Customer WHERE cust_no BETWEEN 1003 AND 1005; To retrieve rows of persons born after 9-JAN-70 and before 1-AUG-96. SELECT * FROM Customer WHERE birth_date BETWEEN ’10-JAN-70’ AND ’31-JUL-96’;

17)

18)

19)

20)

21)

22)

28

WWW.CSEROCKZ.COM

DataBaseManagementSystems LAB MANUAL
23)

To retrieve rows where the city has data which is equal to UDP or MNG or BNG or PJM or MAR. SELECT * FROM Customer WHERE city IN (‘UDP’, ‘MNG’, ‘BNG’, ‘PJM’, ‘MAR’);

TABLE DEFINITIONS SQL> CREATE TABLE Emp ( emp_no NUMBER, emp_name VARCHAR(20), join_date DATE, join_basic NUMBER(7, 2), PRIMARY KEY (emp_no) ); Table created.
Insert the following data: EMP NO 1001 1002 1003 1004 1005 EMP NAME Subhas bose Nadeem shah Charles babbage Shreyas kumar George boole JOIN DATE 01-JUN-96 01-JUN-96 01-JUN-96 01-JUL-96 01-JUL-96 JOIN BASIC 3000 2500 3000 2500 2800

SQL> CREATE TABLE Salary ( emp_no NUMBER, basic NUMBER(7, 2), commission NUMBER(7, 2), deduction NUMBER(7, 2), salary_date DATE, FOREIGN KEY (emp_no) REFERENCES Emp ); Table created. Insert the following data: EMP NO 1001 1002 1003 BASIC 3000 2500 3000 COMMISSION 200 120 500 DEDUCTION 250 200 290 SALARY DATE 30-JUN-96 30-JUN-96 30-JUN-96 29

WWW.CSEROCKZ.COM

emp_no ORDER BY SUM(s.emp_no. AVG(s. SUM(s. SUM(basic) FROM salary GROUP BY emp_no ORDER BY SUM(basic) DESC.emp_name). e. emp e WHERE s.basic) FROM salary s. 6) To group the basic by month. SELECT s. INITCAP(e.emp_no ORDER BY AVG(s. To sum the salary of each employee and sort it in descending order on the sum of basic.CSEROCKZ.DataBaseManagementSystems LAB MANUAL 1004 1005 1001 1002 1003 1004 1005 2500 2800 3000 2500 3000 2500 2800 200 100 200 120 500 200 100 300 250 250 200 290 300 150 30-JUN-96 30-JUN-96 31-JUL-96 31-JUL-96 31-JUL-96 31-JUL-96 31-JUL-96 QUERIES 1) To sum the salary of each employee.basic) FROM salary s.emp_no. SELECT emp_no. 30 WWW. e. e.emp_name. To sum the salary of each employee and sort it in descending order on the sum of basic.basic). 2) To sum the salary of each employee and sort it on the sum of basic.basic) DESC. 3) 4) 5) To group the data by average salary of each employee. Display name also SELECT s.COM . SELECT emp_no.emp_no = e.emp_no.emp_no GROUP BY s. SUM(basic) FROM salary GROUP BY emp_no ORDER BY SUM(basic).emp_no GROUP BY s. SUM(basic) FROM salary GROUP BY emp_no. SELECT emp_no.emp_no.emp_no = e. emp e WHERE s.

DataBaseManagementSystems LAB MANUAL SELECT TO_CHAR(salary_date.emp_no.emp_no = e. 7) To group the data by average salary of each employee and display where average basic is more than 2000.COM . WEEK 5 31 WWW.emp_no = e.emp_no.CSEROCKZ. emp e WHERE s.basic) >= 2000 ORDER BY AVG(s. SUM(basic) “TOTAL BASIC” FROM salary GROUP BY TO_CHAR(salary_date. SELECT s. ‘MONTH’).basic) FROM salary s. SUBQUERIES 8) To list the employees who earn less than the average salary. SELECT * FROM salary WHERE emp_no IN (SELECT emp_no FROM salary WHERE deduction = 150). emp e WHERE s.emp_name FROM salary s. AVG(s. SELECT * FROM salary WHERE basic < (SELECT AVG(basic) FROM salary).emp_name).. ‘MONTH’) “MONTH”. INITCAP(e. SELECT s.basic). 10) To list the names of employees and salary details.emp_no AND s. 9) To list the employees whose deduction is 150.*.emp_no GROUP BY s. whose basic is less than the average salary. e. e.emp_no HAVING AVG(s.basic < (SELECT AVG(basic) FROM salary).

MAX and MIN). HAVING and Creation and Dropping of Views. initcap. trunk. 2). next_day. substr. AVG. emp_name VARCHAR(20). add_months. rpad. greatest. UNIQUE. ALL.DataBaseManagementSystems LAB MANUAL 2) Queries (along with subqueries) using ANY. deduction NUMBER(7. to_date). salary_date DATE. Example: select the rollno and name of the student who secured 4th rank in the class. date functions (sysdate. and instr). join_date DATE. NOT EXISTS. 4) Queries using Conversions. length. SUM. Constraints. rtrim. 3) Queries using Aggregate functions (COUNT. basic NUMBER(7. round. EXISTS. Table created. lpad. lower. PRIMARY KEY (emp_no) ). IN. 2). FOREIGN KEY (emp_no) REFERENCES Emp ). functions (to_char.CSEROCKZ. 2). 32 WWW. ltrim. to_char.COM . to_num. months_between. upper. and to_date). string function (Conactenation. last_day. Insert the following data: EMP NO 1001 1002 1003 1004 1005 EMP NAME Subhas bose Nadeem shah Charles babbage Shreyas kumar George boole JOIN DATE 01-JUN-96 01-JUN-96 01-JUN-96 01-JUL-96 01-JUL-96 JOIN BASIC 3000 2500 3000 2500 2800 SQL> CREATE TABLE Salary ( emp_no NUMBER. GROUP BY. TABLE DEFINITIONS SQL> CREATE TABLE Emp ( emp_no NUMBER. join_basic NUMBER(7. 2). commission NUMBER(7. least. INTERSECT.

e. To sum the salary of each employee and sort it in descending order on the sum of basic.basic) DESC.emp_no.emp_no.DataBaseManagementSystems LAB MANUAL Table created.COM . To sum the salary of each employee and sort it in descending order on the sum of basic. emp e WHERE s.emp_name. SELECT emp_no. 33 WWW.emp_name ORDER BY SUM(s. SELECT emp_no.CSEROCKZ.emp_no GROUP BY s. Insert the following data: EMP NO 1001 1002 1003 1004 1005 1001 1002 1003 1004 1005 BASIC 3000 2500 3000 2500 2800 3000 2500 3000 2500 2800 COMMISSION 200 120 500 200 100 200 120 500 200 100 DEDUCTION 250 200 290 300 250 250 200 290 300 150 SALARY DATE 30-JUN-96 30-JUN-96 30-JUN-96 30-JUN-96 30-JUN-96 31-JUL-96 31-JUL-96 31-JUL-96 31-JUL-96 31-JUL-96 QUERIES 11) To sum the salary of each employee. SUM(basic) FROM salary GROUP BY emp_no. e.basic) FROM salary s. SELECT emp_no. SUM(basic) FROM salary GROUP BY emp_no ORDER BY SUM(basic). 12) To sum the salary of each employee and sort it on the sum of basic. Display name also SELECT s. 13) 14) 15) To group the data by average salary of each employee. SUM(basic) FROM salary GROUP BY emp_no ORDER BY SUM(basic) DESC. SUM(s.emp_no = e.

emp_no GROUP BY s.emp_no. 19) To list the employees whose deduction is 150.basic) FROM salary s. SUBQUERIES 18) To list the employees who earn less than the average salary.DataBaseManagementSystems LAB MANUAL SELECT s.COM . SELECT * FROM salary WHERE emp_no IN (SELECT emp_no FROM salary WHERE deduction = 150).basic < (SELECT AVG(basic) FROM salary).basic). emp e WHERE s.emp_no = e.emp_no. INITCAP(e.emp_name).emp_no. SELECT TO_CHAR(salary_date.basic).emp_name FROM salary s. 16) To group the basic by month. whose basic is less than the average salary. 34 WWW.emp_no = e.emp_no = e.emp_no HAVING AVG(s. SELECT s. e. ‘MONTH’).emp_no GROUP BY s.emp_no.emp_no ORDER BY AVG(s. e. e.CSEROCKZ. SELECT s. 17) To group the data by average salary of each employee and display where average basic is more than 2000.emp_no AND s. 20) To list the names of employees and salary details.emp_name). emp e WHERE s.basic) FROM salary s. AVG(s. SELECT * FROM salary WHERE basic < (SELECT AVG(basic) FROM salary). emp e WHERE s.basic) >= 2000 ORDER BY AVG(s. SUM(basic) “TOTAL BASIC” FROM salary GROUP BY TO_CHAR(salary_date.*. AVG(s. ‘MONTH’) “MONTH”. INITCAP(e..

lpad. round. NOT EXISTS. branch-city. amount> Borrower Schema <customer-name. customer-city> Loan Schema <loan-number. add_months. account-number> BRANCH TABLE Branch Name Brighton Downtown Mianus North Town Perryridge Pownal Redwood Round Hill Branch City Brooklyn Brooklyn Horseneck Rye Horseneck Bennington Palo Alto Horseneck Assets 7100000 9000000 400000 3700000 1700000 300000 2100000 800000 35 WWW. Example: select the rollno and name of the student who secured 4th rank in the class. initcap. HAVING and Creation and Dropping of Views. IN. to_char. string function (Conactenation. customer-street.CSEROCKZ. MAX and MIN). 4) Queries using Conversions. branch-name. substr. trunk. Constraints. GROUP BY. branch-name. functions (to_char. TABLE DEFINITIONS Branch Schema <branch-name. and to_date). UNIQUE. last_day. 3) Queries using Aggregate functions (COUNT. SUM.COM . rpad. lower. EXISTS. rtrim. balance> Depositor Scheme <customer-name. INTERSECT. and instr). date functions (sysdate. ltrim. length. upper. to_num. AVG. next_day. months_between.DataBaseManagementSystems LAB MANUAL WEEK 6 2) Queries (along with subqueries) using ANY. loan-number> Account Scheme <account-number. ALL. to_date). greatest. least. assets> Customer Schema <customer-name.

DataBaseManagementSystems LAB MANUAL CUSTOMER TABLE Customer Name Adams Brooks Curry Glenn Green Hayes Johnson Jones Lindsay Smith Turner Williams LOAN TABLE Loan Number L-11 L-14 L-15 L-16 L-17 L-23 L-93 Branch Name Round Hill Downtown Perryridge Perryridge Downtown Redwood Mianus Amount 900 1500 1500 1300 1000 2000 500 Customer Street Spring Senator North Sand Hill Walnut Main Alma Main Park North Putnam Nassau Customer City Pittsfield Brooklyn Rye Woodside Stamford Harrison Palo Alto Harrison Pittsfield Rye Stamford Princeton BORROWER TABLE Customer Name Adams Curry Hayes Jackson Jones Smith Smith Loan Number l-16 L-93 L-15 L-14 L-17 L-11 L-23 36 WWW.COM .CSEROCKZ.

L-17 Branch Name Downtown Perryridge Brighton Mianus Brighton Redwood Round Hill Balance 500 400 900 700 750 700 350 Account Number A102 A-101 A-201 A-217 A-222 A-215 A-305 SELECT branch_name FROM Loan. including duplicates. 4) To list fields after applying arithmetic operations.COM . SELECT all branch_name FROM Loan. branch_name. SELECT loan_number. amount *100 37 WWW. 3) To explicitly list rows.DataBaseManagementSystems LAB MANUAL Williams ACCOUNT TABLE Account Number A-101 A-102 A-201 A-215 A-217 A-222 A-305 DEPOSITOR TABLE Customer Name Hayes Johnson Johnson Jones Lindsay Smith Turner QUERIES 1) To list all the fields from the table Customer. SELECT distinct branch_name FROM Loan. 2) To list rows after eliminating duplicates.CSEROCKZ.

COM . 7) Find all loan numbers for loans with loan amounts not between Rs90.loan_number AS loan_id.loan_number = Loan. Or SELECT customer_name.DataBaseManagementSystems LAB MANUAL FROM Loan. Or SELECT loan_number FROM Loan WHERE amount <= 100000 AND amount >= 90000. Loan WHERE Borrower. SELECT loan_number FROM Loan WHERE amount BETWEEN 90000 AND 100000. SELECT loan_number FROM Loan WHERE branch_name = ‘Perryridge’ AND amount > 1200. SELECT customer_name.loan_number.000 and Rs100. Borrower. Borrower.000 and Rs100. Loan 38 WWW. loan numbers and loan amounts.000.000. amount FROM Borrower. find their names. amount FROM Borrower. 6) Find all loan numbers for loans with loan amounts between Rs90.loan_number.CSEROCKZ. SELECT loan_number FROM Loan WHERE amount NOT BETWEEN 90000 AND 100000. 8) For all customers who have a loan from the bank. 5) Find all loan numbers for loans made at the Perryridge branch with loan amounts greater than Rs1200.

DataBaseManagementSystems LAB MANUAL
WHERE Borrower.loan_number = Loan.loan_number;
9) Find the customer names, loan numbers and loan amounts for all loans

at the Perryridge branch. SELECT customer_name, Borrower.loan_number, amount FROM Borrower, Loan WHERE Borrower.loan_number = Loan.loan_number AND branch_name = ‘Perryridge’; Or SELECT customer_name, T.loan_number, S.amount FROM Borrower AS T, Loan AS S WHERE T.loan_number = S.loan_number AND branch_name = ‘Perryridge’;
10) Find the names of all branches that have assets greater than atleast

one branch located in Brooklyn. SELECT DISTINCT T.branch_name FROM Branch as T, Branch as S WHERE T.assets > S.assets AND S.branch_city = ‘Brooklyn’;
11) Find the names of all customers whose street address includes the

substring ‘Main’. SELECT customer_name FROM Customer WHERE customer_street LIKE ‘%Main%’;
12) To list in alphabetic order all customers who have a loan at the

Perryridge branch. SELECT DISTINCT customer_name FROM Borrower B, Loan L WHERE B.loan_number = L.loan_number AND branch_name = ‘Perryridge’ ORDER BY customer_name;

13) To list the entire loan info in descending order of amont.
39

WWW.CSEROCKZ.COM

DataBaseManagementSystems LAB MANUAL
SELECT * FROM Loan ORDER BY amount DESC, loan_number ASC;
14) To find all customers having a loan, an account or both at the bank,

without duplicates. (SELECT customer_name FROM Depositor) UNION (SELECT customer_name FROM Borrower);

15) To find all customers having a loan, an account or both at the bank,

with duplicates. (SELECT customer_name FROM Depositor) UNION ALL (SELECT customer_name FROM Borrower);
16) To find all customers having both a loan and an account at the bank,

without duplicates. (SELECT customer_name FROM Depositor) INTERSECT (SELECT customer_name FROM Borrower);
17) To find all customers having a loan, an account or both at the bank,

with duplicates. (SELECT customer_name FROM Depositor) INTERSECT ALL (SELECT customer_name FROM Borrower);

40

WWW.CSEROCKZ.COM

DataBaseManagementSystems LAB MANUAL
18) To find all customers who have an account but no loan at the bank,

without duplicates. (SELECT DISTINCT customer_name FROM Depositor) EXCEPT (SELECT customer_name FROM Borrower);
19) To find all customers who have an account but no loan at the bank,

with duplicates. (SELECT DISTINCT customer_name FROM Depositor) EXCEPT ALL (SELECT customer_name FROM Borrower);

20) Find the average account balance at the Perryridge branch

SELECT branch_name, AVG(balance) FROM Account WHERE branch_name = ‘Perryridge’;
21) Find the average account balance at the each branch

SELECT AVG(balance) FROM Account GROUP BY branch_name;
22) Find the number of depositors for each branch .

SELECT branch_name, COUNT(DISTINCT customer_name) FROM Depositor D, Account A WHERE D.account_number = A.account_number GROUP BY branch_name;
23) Find the number of depositors for each branch where average account

balance is more than Rs 1200. SELECT branch_name, COUNT(DISTINCT customer_name) FROM Depositor D, Account A
41

WWW.CSEROCKZ.COM

account_number GROUP BY branch_name HAVING AVG(balance) > 1200.customer_name FROM Borrower B.customer_city = ‘Harrison’ GROUP BY D.account_number = A. SELECT loan_number FROM Loan WHERE amount IS NULL.account_number AND D. 28) Find all customers who have both a loan and an account at the bank. Account A. SELECT D.customer_name. 29) Find all customers who have both an account and a loan at the Perryridge branch SELECT DISTINCT B.customer_name = C. Loan L 42 WWW. SELECT AVG(balance) FROM Account.customer_name HAVING COUNT(DISTINCT D. 26) Find the average balance for each customer who lives in Harrision and has at least three accounts. SELECT COUNT(*) FROM Customer.DataBaseManagementSystems LAB MANUAL WHERE D.account_number = A.CSEROCKZ.customer_name AND C. SELECT customer_name FROM Borrower WHERE customer_street IN (SELECT customer_name FROM Depositor). 24) Find the average balance for all accounts. AVG(balance) FROM Depositor D.account_number) >= 3. 27) Find all the loan number that appear in loan relation with null amount values.COM . Customer C WHERE D. 25) Find the number of tuples in the customer relation.

SELECT DISTINCT customer_name FROM Borrower WHERE customer_name NOT IN (SELECT customer_name FROM Depositor).branch_name FROM Branch AS T.loan_number AND branch_name = ‘Perryridge’ AND (branch_name. customer_name) IN (SELECT branch_name. or SELECT customer_name FROM Borrower B WHERE EXISTS (SELECT * FROM Depositor D WHERE D.customer_name). but do not have an account the bank.account_number = A. SELECT branch_name 43 WWW.loan_number L. ‘Jones’). customer_name FROM Depositor D.account_number). SELECT DISTINCT T. 30) Find all customers who do not have a loan at the bank.customer_name = B. 31) Find the names of customers who do have a loan at the bank. 32) Find the names of all branches that have assets greater than those of at least one branch located in Brooklyn.CSEROCKZ. and whose names are neither Smith nor Jones.branch_city = ‘Brooklyn’. 33) Find the names of all branches that have assets greater than that of each branch located in Brooklyn.assets > S.COM . Branch AS S WHERE T.DataBaseManagementSystems LAB MANUAL WHERE B. Account A WHERE D.assets AND S. SELECT DISTINCT customer_name FROM Borrower WHERE customer_name NOT IN (‘Smith’.

34) Find all customers who have an account at all the branches located in Brooklyn.customer_name FROM Depositor AS T WHERE UNIQUE (SELECT R. SELECT T.customer_name AND R.customer_name FROM Depositor AS R. 35) Find all customers who have at most one account at the Perryridge branch. Account AS A WHERE T.account_number AND D.customer_name)). Account AS A WHERE T.customer_name AND R.customer_name FROM Depositor AS R.account_number 44 WWW.DataBaseManagementSystems LAB MANUAL FROM Account GROUP BY branch_name HAVING AVG(balance) >= ALL (SELECT AVG(balance) FROM Account GROUP BY branch_name). SELECT DISTINCT T.CSEROCKZ.account_number = A.account_number = R.customer_name FROM Depositor AS T WHERE NOT UNIQUE (SELECT R.customer_name = t.branch_name FROM Depositor AS T.COM .customer_name = R. SELECT DISTINCT S.account_number = A.branch_name = ‘Perryridge’).customer_name FROM Depositor AS D WHERE NOT EXISTS ((SELECT branch_name FROM Branch WHERE branch_city = ‘Brroklyn) EXCEPT (SELECT R. Account AS R WHERE T.customer_name = R. 36) Find all customers who have at least two accounts at the Perryridge branch.account_number AND A.

SELECT branch_name. 37) Find the average account balance of those branches where the average account balance is greater than 1200.DataBaseManagementSystems LAB MANUAL AND A.branch_name = ‘Perryridge’). SELECT d-CN FROM (Depositor LEFT OUTER JOIN Borrower ON Depositor.COM .customer_name) AS db1(d-CN. b-CN. account_number. SELECT customer_name FROM (Depositor NATURAL FULL OUTER JOIN Borrower) WHERE account_number IS NULL OR loan_number IS NULL.customer_name = Borrower. avg_balance FROM (SELECT branch_name. AVG(balance) FROM Account GROUP BY branch_name) AS Branch_avg(branch_name. 38) Find the maximum across all branches of the total balance at each branch. SUM(balance) FROM Account GROUP BY branch_name) AS Branch_total(branch_name. WEEK 7 45 WWW. SELECT MAX(tot_balance) FROM (SELECT branch_name. loan_number) WHERE b-CN is null. tot_balance). 39) Find the all customers who have an account but no loan at the bank.CSEROCKZ. 40) Find the all customers who have either an account or a loan (but not both) at the bank. avg_balance) WHERE avg_balance > 1200.

last_day. functions (to_char. SUM. NOT EXISTS. add_months. EXISTS. ALL. and instr).DataBaseManagementSystems LAB MANUAL 5) Queries (along with subqueries) using ANY. DUAL (ORACLE WORK TABLE): 1) To display system date. SELECT SYSDATE FROM DUAL. ltrim. SELECT 2*2 FROM DUAL. date functions (sysdate. SELECT TO_CHAR(SYSDATE. INTERSECT. upper. least. rpad. rtrim. greatest. ‘MM’) FROM DUAL. string function (Conactenation. GROUP BY. initcap. ‘MONTH’) FROM DUAL. to_num. 2) To display arithmetic calculations. ‘HH:MI:SS’) FROM DUAL. 5) To display current month. 4) To display system time. to_char. 7) To display system date in specified format. length. round. months_between. 3) To display the logged user. 6) Queries using Aggregate functions (COUNT. IN. ‘DD/MM/YY’) FROM DUAL. SELECT TO_CHAR(SYSDATE. 8) To display date arithmetic. next_day.CSEROCKZ. Example: select the rollno and name of the student who secured 4th rank in the class. UNIQUE. to_date).COM . 46 WWW. HAVING and Creation and Dropping of Views. 7) Queries using Conversions. SELECT TO_CHAR(SYSDATE. and to_date). 6) To display system date in specified format. SELECT USER FROM DUAL. lpad. AVG. SELECT TO_CHAR(SYSDATE. lower. Constraints. substr. MAX and MIN). trunk.

19) To display a field value after converting to lower case. SELECT SUM(basic) FROM salary. 18) To display a field value after left padding. To display a field value after converting to initial capital case. '*') FROM DUAL. GROUP FUNCTIONS: 12) To display average basic salary of the employees. ’01-APR-09’) FROM DUAL. SELECT MAX(basic) FROM salary. STRING FUNCTIONS: 17) To display a field value after left padding. SELECT LOWER(‘a’) FROM DUAL. To display a field value after converting to upper case. SELECT LOWER(‘A’) FROM DUAL.CSEROCKZ. SELECT LAST_DAY(SYSDATE) FROM DUAL. SELECT NEXT_DAY(SYSDATE. ‘MON’) FROM DUAL. 15) To display sum of basic salaries of all the employees. 9) To display date arithmetic.COM . SELECT RPAD('PAGE-1'. 16) To display the number of records in salary table. SELECT MONTHS_BETWEEN(SYSDATE. 11) To display date arithmetic. SELECT MIN(basic) FROM salary. 10. 10. 47 20) 21) WWW. 10) To display date arithmetic. 5) FROM DUAL.DataBaseManagementSystems LAB MANUAL SELECT ADD_MONTHS(SYSDATE. SELECT SUM(basic) FROM salary. SELECT COUNT(*) FROM salary. SELECT LPAD('PAGE-1'. 13) To display minimum basic salary of the employees. 14) To display maximum basic salary of the employees. '*') FROM DUAL.

Develop a program that includes the features NESTED IF. (ii) Insert data into student table and use COMMIT. The program can be extended using the NULLIF and COALESCE functions. SELECT RTRIM(‘CSE2A’. WEEK 8 (PL/SQL) (i) Creation of simple PL/SQL program which includes declaration section. To display a field value after trimming the right side. CASE and CASE expression. 4. SELECT SUBSTR(‘CSE2A’. 22) To display a substring of a field value. To display the length of a field value. SELECT LENGTH(’HOW LONG AM I?’) FROM DUAL. executable section and exception handling section ( ex: Student marks can be selected from the table and printed for those who secured first class and an exception can be raised if no records were found). ROLLBACK and SAVEPOINT in SQL block.COM .CSEROCKZ. 6) 7) 48 WWW. ‘2A’) FROM DUAL. SELECT LTRIM(‘CSE2A’. 23) 24) 25) To display a field value after trimming the left side. 2) FROM DUAL.DataBaseManagementSystems LAB MANUAL SELECT INITCAP(‘HOW ARE YOU?’) FROM DUAL. ‘CSE’) FROM DUAL.

FOR UPDATE CURSOR. 9) Program development using creation of procedure. RAISE APPLICATION ERROR. invoke functions in SQL statements and write complex functions. 12) Develop programs using features of parameters in a CURSOR. package variables and cursors and calling stored packages. BUILT IN exceptions.CSEROCKZ. WHERE CURRENT of clause and CURSOR variables. Syntax to write a sql program Declare <declaration stmts> Begin <executable stmts> [exception <exceptional stmts>]----.COM . package bodies. numeric FOR LOOPS. nested loops using ERROR handling. 10) Program development using creation of stored function. /---end of buffer Example: 1 49 WWW.DataBaseManagementSystems LAB MANUAL 8) Program development using WHILE LOOPS. 11) Program development using creation of package specification. private objects. USER defined exceptions.optional End. passing parameters IN and OUT procedures.

<endnum> loop <statement(s). / set serveroutput off Save the file and at SQL prompt run as: Execution SQL>set serveroutput on SQL> start dbfor (press enter) OR SQL> @dbfor OUTPUT:This ia a demo of FOR loop loop number 1 loop number 2 loop number 3 loop number 4 loop number 5 PS: For syntax: For <var> in <start_num> .put_line('loop number ' || cnt).put_line('This is a demo of FOR loop ').. ed dbfor to open notepad and type the below program: Program declare cnt number. for cnt in 1.5 loop dbms_output. to execute the FOR loop and display the variable. begin dbms_output. At SQL Prompt type..> 50 WWW.SQL.CSEROCKZ.COM . end loop. end.DataBaseManagementSystems LAB MANUAL Create a file DBFOR.

Program begin dbms_ouput. Other forms of if syntax are: If <condition> then <action(s).10 loop if mod(cnt. end loop. If <condition> then <action(s). end if. end. for cnt in reverse 1.. Example: 2 Create a file DBREVFOR.CSEROCKZ.put_line(‘loop counter ‘ || cnt).> End if.> End loop. <endnum> loop <statement(s).. to execute the REVERSE FOR loop and display the variable.SQL.DataBaseManagementSystems LAB MANUAL End loop. / OUTPUT:This is a demo of REVERSE FOR loop loop loop loop loop loop counter counter counter counter counter 10 8 6 4 2 PS: Reverse For syntax: For <var> in reverse <start_num> . 2) = 0 then dbms_output.put_line(‘This is a demo of REVERSE FOR loop’).COM .> Else 51 WWW.

DataBaseManagementSystems LAB MANUAL <action(s). begin dbms_ouput. / set serveroutput off OUTPUT:This is the demo of LOOP loop loop counter 1 loop counter 2 52 WWW. dbms_output. end loop. loop cnt := cnt + 1. end.COM . exit when cnt > 10. to execute the LOOP loop and display the variable.> else <action(s).SQL. Program set serveroutput on declare cnt number(2) := 0.> Elsif <condition> then <action(s). Example: 3 Create a file DBLOOP.> End if.put_line(‘loop counter ‘ || cnt). If <condition> then <action(s).CSEROCKZ.put_line(‘This is a demo of LOOP loop’).> End if.

Example: 4 Create a file DBWHILE.COM . end loop. ‘999’)).CSEROCKZ. cnt := cnt + 1.SQL. end.put_line(‘loop counter: ‘ || to_char(cnt.> Exit when <condition>. begin dbms_ouput. Program set serveroutput on declare cnt number(2) := 1.DataBaseManagementSystems LAB MANUAL loop loop loop loop loop loop loop loop counter counter counter counter counter counter counter counter 3 4 5 6 7 8 9 10 PS: Loop syntax: loop <statement(s). End loop. while cnt <= 10 loop dbms_output. to execute the WHILE loop and display the variable.put_line(‘This is a demo of WHILE loop’). / set serveroutput off OUTPUT:This is a demo of WHILE loop loop counter : 1 loop counter : 2 53 WWW.

end.CSEROCKZ. to retrieve the employee details of an employee whose number is input by the user . ddesig from emp where emp_no = &n. dbms_output. Example: 4 Write a program EMPDATA.put_line(‘Designation: ‘ || ddesig). dbms_ouput. basic. dbasic.> End loop.PROGRAM TO RETRIEVE EMP DETAILS set serveroutput on prompt Enter Employee Number: accept n declare dname emp. / OUTPUT:54 WWW.put_line(‘Employee Details:). dbms_output. ddesig emp.emp_basic%type.emp_name%type.put_line(‘Basic: ‘ || dbasic). Program -. begin select emp_name.put_line(‘Name: ‘ || dname).desig%type.COM . design into dname.SQL.DataBaseManagementSystems LAB MANUAL loop loop loop loop loop loop loop loop counter counter counter counter counter counter counter counter : : : : : : : : 3 4 5 6 7 8 9 10 PS: while syntax: while <condition> loop <statement(s). dbasic emp. dbms_output.

EX_INVNO. begin 55 WWW. d number(3):=1. block for inverting a number using all forms of loops. s number(13):=0. new 9:where eno=13. employee details Name:allen basic:9500 desig:mech set serveroutput off PS: Similarly you can use other SQL statements in the PL/SQL block Exercises: 1) Write a PL/SQL code. r number(3):=10.COM .DataBaseManagementSystems LAB MANUAL enter employee number: 13 old 9:where eno =&n.CSEROCKZ. ANSWER:declare n number(20):=123.SQL.

s:=(s*r)+d. while n>0 loop d:=mod(n.CSEROCKZ. / OUTPUT:the number is:123 inverted value is:321 2) Write a PL/SQL code.put_line('inverted values' || s). ANSWER:prompt enter number: accept number n declare isum number(2):=0.10). end.DataBaseManagementSystems LAB MANUAL dbms_output.put_line('the number is :' || n). end loop. 56 WWW.SQL that prints the sum of ‘n’ natural numbers. EX_SUMNO. dbms_output. i number. n:=n/r.COM .

Store the radius and the corresponding values of calculated area in the table AREA_VALUES.put_line('sum is ' || isum). of block to calculate the area of the circle for the values of radius varying from 3 to 7..COM . dbms_output. end loop.CSEROCKZ. 57 WWW. EX_AREA.SQL. / OUTPUT:enter the number:7 sum is 28 3) Write a PL/SQL code. begin for i in 1.DataBaseManagementSystems LAB MANUAL n number:=&n.n loop isum:=isum+i. ANSWER:set serveroutput on declare area number(5). end.

DataBaseManagementSystems LAB MANUAL rad number(3). dbms_output.. pi number(4):=3. begin for rad in 3.CSEROCKZ. / OUTPUT:area area area area area is is is is is :27 :48 :75 :108 :147 SQL>select * from area_values. end. end loop.14.put_line('area is' || area).rad). insert into area_values values(area. area rad ____ ____ 27 3 48 4 75 5 108 6 147 7 58 WWW.COM .7 loop area:=pi*rad*rad.

FOR UPDATE CURSOR. private objects. passing parameters IN and OUT procedures. executable section and exception handling section ( ex: Student marks can be selected from the table and printed for those who secured first class and an exception can be raised if no records were found). BUILT IN exceptions. nested loops using ERROR handling. WHERE CURRENT of clause and CURSOR variables. 16) Program development using creation of procedure. The program can be extended using the NULLIF and COALESCE functions. Develop a program that includes the features NESTED IF. USER defined exceptions.DataBaseManagementSystems LAB MANUAL WEEK 9 (PL/SQL) 13) (i) Creation of simple PL/SQL program which includes declaration section. 18) Program development using creation of package specification. package bodies. CASE and CASE expression. invoke functions in SQL statements and write complex functions. RAISE APPLICATION ERROR. 19) Develop programs using features of parameters in a CURSOR. (ii) Insert data into student table and use COMMIT. 59 WWW. numeric FOR LOOPS. package variables and cursors and calling stored packages. ROLLBACK and SAVEPOINT in SQL block. 17) Program development using creation of stored function.COM .CSEROCKZ. 14) 15) Program development using WHILE LOOPS.

ddate. if sql%rowcount > 0 then insert into newemp values (dno. Execute the program as SQL> start newins Example: 2 Create a file (NEWINS2. begin select emp_no. 60 WWW. basic). the record of any employee whose number is input by the user. ddate date. basic into dno. dbasic number(10). 1. ddate. end. Open an editor and type the following program. the record of any employee whose number is input by the user. NEWEMP.DataBaseManagementSystems LAB MANUAL Example: 1 Create a file (NEWINS. NEWEMP. emp_name. dname. Also display on the screen the employee details and to handle errors like user entering a number which does not exist in the table. end if. emp_name. / 3. join_date. dname. dbaisc). dbasic from emp where emp_no = &userno. 2. Create the table NEWEMP <emp_no. Program prompt Enter Employee Number: accept userno number declare dno number(4). to insert into a new table.COM . to insert into a new table. dname varchar2(30).SQL). Save the file as NEWINS 4. join_date.SQL).CSEROCKZ.

number(10.put_line(DNO || ‘ ‘ || DNAME || ‘ ‘ || DDATE || ‘ ‘ || DBASIC). dbms_output. end.CSEROCKZ. ddate. ddate date. dname varchar2(30).SQL).COM . ddate. exception when no_data_found then dbms_output. 2). dbasic number(10). basic dno. end if. begin select into from where emp_no. dbasic). 61 WWW. / Example: 3 Create a file (CALCTAX. 2).put_line (‘Record ‘ || &userno || ‘ does not exist’). emp_name. varchar2(30). to calculate tax for a specific employee and display name and tax. join_date. dname. dbasic emp emp_no = &userno. dname.put_line(‘Record inserted into NEWEMP’).DataBaseManagementSystems LAB MANUAL Program prompt Enter Employee Number: accept userno number declare dno number(4). if sql%rowcount > 0 then insert into newemp values (dno. dbms_output. Program prompt Enter Employee Number: accept userno number declare tot_basic tax name number(10.

put_line(NAME || ‘ TOTAL TAX: ‘ || TAX).CSEROCKZ.put_line(‘NO BASIC’). dbms_output. Certain system exceptions raise the following flags: CURSOR_ALREADY_OPEN – Displayed when the user tries to open a cursor that is already open DUP_VAL_ON_INDEX – when user tries to insert a duplicate value into a unique column INVALID_CURSOR – when user references an invalid cursor or attempts an illegal cursor operation INVALID_NUMBER – when user tries to use something other than a number where one is called for LOGIN_DENIED – when connect request for user has been denied 62 WWW. dbms_output. exception when no_data_found then dbms_output.DataBaseManagementSystems LAB MANUAL begin select into from where emp_name.put_line(NAME || ‘ TOTAL BASIC: ‘ || TOT_BASIC). dbms_output. end. Exceptions can be either System defined or User defined.COM .04. basic name. / PS: EXECPTIONS When a program is executed certain errors are automatically recognized and certain error situations must be recognized by the program itself. Errors in general are referred to as Exceptions.put_line(NAME || ‘ TOTAL BASIC: ‘ || TOT_BASIC). else tax := tot_basic * . tot_basic emp emp_no = &userno. if tot_basic = 0 or tot_basic is null then dbms_output.02. end if.put_line (‘Record ‘ || &userno || ‘ does not exist’). dbms_output. elsif tot_basic <= 2000 then tax := tot_basic * .put_line(NAME || ‘ TOTAL TAX: ‘ || TAX).

processing control is passed to the EXCEPTION section of the PL/SQL block. truncation or constraint error ZERO_DIVIDE – flag becomes TRUE if SQL select statement tries to divide a number by 0 OTHERS – this flag is used to catch any error situations not coded by the programmer In the exception section and must appear last in the exception section User defined exceptions must be declared in the declare section with the reserved word. If the 63 WWW. This exception can be brought into action by the command.CSEROCKZ. EXCEPTION.DataBaseManagementSystems LAB MANUAL NO_DATA_FOUND – this flag becomes TRUE when SQL select statement failed to retrieve any rows NOT_LOGGED_ON – user is not connected to ORACLE PROGRAM_ERROR – user hits a PL/SQL internal error STORAGE_ERROR – user hits a PL/SQL memory error TIMEOUT_ON_RESOURCE – user has reached timeout while waiting for an Oracle resource TRANSACTION_BACKED_OUT – a remote server has rolled back the transaction TOO_MANY_ROWS – the flag becomes TRUE when SQL select statement retrieves more than one row and it was supposed to retrieve only 1 row VALUE_ERROR – user encounters an arithmetic.COM . WHEN <exception-name> THEN <action>. RAISE <exception-name> When the exception is raised. Exercises: 1) Write a PL/SQL code block that will accept an account number from the user and debit an amount of RS2000 from the account. Syntax for user defined exception: <exception-name> EXCEPTION. conversion. The code for the exception must be defined in the EXCEPTION section of the PL/SQL block.

status) Write a PL/SQL block of code to achieve the following: If the price of the product is >4000 then change the price to 4000. ROLLBACK and SAVEPOINT in SQL block. balance. (use table schemas Product(pno. 25) Program development using creation of package specification. oldprice) WEEK 10 (PL/SQL) (i) Creation of simple PL/SQL program which includes declaration section. (use table schema Accounts (acno. Develop a program that includes the features NESTED IF. The program can be extended using the NULLIF and COALESCE functions. price) and Old_Price(pno. invoke functions in SQL statements and write complex functions.COM .DataBaseManagementSystems LAB MANUAL account has a minimum balance of 500 after amount is debited the process should set a freeze on the account by setting the status to F. package variables and cursors and calling stored packages. private objects. date_of_change. 64 WWW. passing parameters IN and OUT procedures.CSEROCKZ. 24) Program development using creation of stored function. executable section and exception handling section ( ex: Student marks can be selected from the table and printed for those who secured first class and an exception can be raised if no records were found). nested loops using ERROR handling. package bodies. CASE and CASE expression. The price change is to be recorded in the old price table along with product number and date on which the price was last changed. 23) Program development using creation of procedure. USER defined exceptions. numeric FOR LOOPS. (ii) Insert data into student table and use COMMIT. BUILT IN exceptions. 2) 20) 21) 22) Program development using WHILE LOOPS. RAISE APPLICATION ERROR.

65 WWW. cursor c1 is select * from dept.DataBaseManagementSystems LAB MANUAL 26) Develop programs using features of parameters in a CURSOR. end. dname. vdname dept. vloc dept. begin open c1.dname%type. Example: 1 Create a PL/SQL program using cursors.CSEROCKZ. / PS: Cursors are used when the SQL select statement is expected to return more than 1 row.put_line('vdno = ' ||vdno|| ' vdname = '||vdname||' vloc = '||vloc). FOR UPDATE CURSOR.loc%type. close c1. dbms_output. or // cursor c1 is select * from dept where rowno = 1. loc)) Program declare vdno dept. (use table dept(dno.vdname.COM . WHERE CURRENT of clause and CURSOR variables. to retrieve first tuple from the department relation.vloc. fetch c1 into vdno.deptno%type.

<VAR2>. dname. begin for vdept in c1 loop dbms_output. end.DataBaseManagementSystems LAB MANUAL A cursor must be declared and its definition contains a query and is defined in the DECLARE section of the program.CSEROCKZ. Syntax to define a cursor: CURSOR <CURSOR-NAME> IS <SELECT STATEMENT> Syntax to open the cursor: OPEN <CURSOR-NAME> Syntax to store data in the cursor: FETCH <CURSOR-NAME> INTO <VAR1>. (use table dept(dno. loc)) Program declare vdept dept%rowtype. cursor c1 is select * from dept.deptno|| ' vdname = '|| vdept. OR FETCH <CURSOR-NAME> INTO <RECORD-NAME> Syntax to close the cursor: CLOSE <CURSOR-NAME> Example: 2 Create a PL/SQL program using cursors.dname||' vloc = '||vdept. A cursor must be opened before processing and closed after processing. <VAR3>…. to retrieve each tuple from the department relation. (Similar to how files are opened and closed in a C program).put_line('vdno = ' ||vdept.COM . end loop.loc). / 66 WWW.

salary.sal)) Program declare no emp.CSEROCKZ. salary of the three highest paid employees. ename. Syntax for cursor FOR LOOP: FOR <VARIABLE> IN <CURSOR-NAME> LOOP <STATEMENTs> END LOOP.name. The advantage of cursor for loop is that the loop itself will open the cursor.DataBaseManagementSystems LAB MANUAL PS: The cursor for loop can be used to process multiple records. 67 WWW. begin open c1. loop fetch c1 into no. name emp. end loop.put_line(no||name||salary). Example: 3 Create a PL/SQL program using cursors. exit when c1 %rowcount >3. name. ename. salary emp.ename%type. read the records into the cursor from the table until end of file and close the cursor.COM . to display the number. exit when c1 %notfound. (use table emp(empno. dbms_output.sal%type.empno%type. close c1. cursor c1 is select empno. sal from emp order by sal desc.

delete from emp where current of c1. 68 WWW. end loop. Program declare vrec emp%rowtype. exit when c1 %notfound.put_line('Record deleted'). to delete the employees whose salary is more than 3000.DataBaseManagementSystems LAB MANUAL end. Used after FETCH FOUND is TRUE if row is retrieved FOUND is FALSE if row is not retrieved %ROWCOUNT – To determine the number of rows retrieved ROWCOUNT is 0 when cursor is opened ROWCOUNT returns the number of rows retrieved %ISOPEN – To determine the cursor is open ISOPEN is TRUE if a cursor is open ISOPEN is FALSE if a cursor is not open Example: 4 Create a PL/SQL program using cursors.COM . / PS: Cursors Attributes: There are 4 cursor attributes used to provide information on the status of a cursor. begin open c1. %NOTFOUND – To determine if a row was retrieved Used after FETCH NOTFOUND is TRUE if row is not retrieved NOTFOUND is FALSE if row is retrieved %FOUND – To determine if a row was retrieved. loop fetch c1 into vrec. cursor c1 is select * from emp where sal>3000 for update. dbms_output.CSEROCKZ.

/ PS: In order to DELETE or UPDATE rows. end if.sal where current of c1. begin select avg(sal) into avgsal from emp. avgsal number(10. end loop.put_line('Record updated').BASIC%TYPE. TOTBASIC SALARY. the cursor must be defined with the FOR UPDATE clause. Program declare vrec emp%rowtype. 69 WWW.2). end. will declare TOTBASIC of the same type as BASIC column from the table SALARY. for vrec in c1 loop if vrec. / PS: Variable Attributes: %TYPE .is used in PL/SQL to declare a variable to be of the same type as a previously declared variable or to be of the same type as a column in a table.CSEROCKZ. end.COM . Example: 5 Create a PL/SQL program using cursors.sal < avgsal then vrec.DataBaseManagementSystems LAB MANUAL close c1. update emp set sal = vrec. to update the salary of each employee by the avg salary if their salary is less than avg salary.sal := avgsal. dbms_output. cursor c1 is select * from emp for update.

will declare SALREC as a record variable equivalent to the row from the table SALARY. NAME. (use table emp(emp_no.DataBaseManagementSystems LAB MANUAL %ROWTYPE – declares a variable which is actually a record which has the same structure as a row from a table. NEWEMP. SALREC SALARY%ROWTYPE. 70 WWW. join_date from emp where upper(desig) = ‘MGR’. JOIN_DATE. exit when cur_mgr%notfound. cursor cur_mgr is select emp_no. loop fetch cur_mgr into dno.COM . dname. to insert into a table. dname varchar2(30). desig)) Program set serveroutput on declare ctr number(2) := 2. emp_name.CSEROCKZ. the record of ALL MANAGERS. no_manager_found begin open cur_mgr. Handle any user defined exceptions. ddate. dno number(4). exception. Example: 6 Create a PL/SQL program using cursors. emp_name. Also DISPLAY on the screen the NO. ctr := ctr + 1. ddate date. join_date.

dbms_output. end if. NEWEMP. end loop.put_line(‘TOTAL number of records’ || ctr). / Exercises: 1) Create a PL/SQL program using cursors.put_line(dno || ‘ ‘ || dname || ‘ ‘ ddate). raise no_manager_found. WEEK 11 (PL/SQL) 71 WWW. close cur_mgr.put_line(‘NO RECORS FOUND’). Handle any user defined exceptions. dbms_output. end. to insert into a table. insert into new emp values (dno. Display appropriate error message if data does not exist in the table. dname.COM .DataBaseManagementSystems LAB MANUAL dbms_output. for any designation input by the user from the keyboard.CSEROCKZ. ddate). 2) Code a program to calculate Tax for any employee whose number is input from the keyboard. if cur_mgr%rowcount = 0 then close cur_mgr.put_line(ctr || ‘Record inserted into NEWEMP’). exception when no_manager_found then dbms_output.

numeric FOR LOOPS. nested loops using ERROR handling. create table itmmast (itmid itmprice number(10). USER defined exceptions. package variables and cursors and calling stored packages. Develop a program that includes the features NESTED IF. trnqty number(10)). ROLLBACK and SAVEPOINT in SQL block. private objects. (ii) Insert data into student table and use COMMIT. The program can be extended using the NULLIF and COALESCE functions. 28) 29) Program development using WHILE LOOPS. BUILT IN exceptions. FOR UPDATE CURSOR. 32) Program development using creation of package specification. package bodies.CSEROCKZ. RAISE APPLICATION ERROR. number(10.COM . WHERE CURRENT of clause and CURSOR variables. 72 WWW.2)). cstid number(10).DataBaseManagementSystems LAB MANUAL 27) (i) Creation of simple PL/SQL program which includes declaration section. Example: 1 Code a procedure to calculate the sales made to a particular customer. { create table trn (itmid number(10). executable section and exception handling section ( ex: Student marks can be selected from the table and printed for those who secured first class and an exception can be raised if no records were found). 33) Develop programs using features of parameters in a CURSOR. passing parameters IN and OUT procedures. 30) Program development using creation of procedure. 31) Program development using creation of stored function. invoke functions in SQL statements and write complex functions. CASE and CASE expression.

end. close cur_tr. sales NUMBER(10. cursor cur_tr is select trn.ITMID%TYPE. exit when cur_tr%notfound.COM .itmid = itmmast. itmprice from trn. end loop. 2) := 0. loop fetch cur_tr into id. Program CREATE OR REPLACE PROCEDURE TOTSALES (CID IN CSTMAST.} Step 1: Open the editor Step 2: Type the code below in a file named. if cur_tr%rowcount = 0 then raise_application_error(-20020.CSEROCKZ. qty TRN.itmid. itmmast where trn. trnqty. ‘ERREOR!!!THERE IS NO DATA’). name varchar2(30)).cstid = cid and trn. / 73 WWW. TOTSALES. end if. price.DataBaseManagementSystems LAB MANUAL create table cstmast ( cstid number(10). sales := sales + qty * price. SAL OUT NUMBER) IS id TRN.TRNQTY%TYPE.CSTID%TYPE. begin open cur_tr.itmid. qty.ITMPRICE%TYPE. price ITMMAST. sal := sales.

SQL file. which will perform an action and functions are subprograms that are generally coded to compute some value. It behaves like a constant inside the procedure. The OUT parameter is used to pass values out of a procedure to the caller of the procedure. the parameters passed can be declared to be IN. When calling a procedure. i. OUT or IN OUT. The IN parameter is used to pass values to the procedure being called.COM . It behaves like a uninitialized variable inside the procedure. Procedures: Procedures are sub-programs.e. If you have errors type SQL> show errors Step 6: To execute the procedure at SQL prompt type SQL> variable sl number SQL> execute totsales(2001. Packages. Procedures and functions are also referred to as sub-programs as they can take parameters and be invoked.DataBaseManagementSystems LAB MANUAL Step 3: Save the TOTSALES. cannot be assigned values inside the procedure. Since the code is in the database. :sl) SQL> print sl PS: Procedural Objects Groups of SQL and PL/SQL statements can be stored in the database. Step 4: Return to SQL Prompt and compile as SQL> start TOTSALES. 74 WWW. processing is faster. The clients execute the procedure or function and the processing is done in the server. The code stored once in the database can be used by multiple applications. Procedures can receive and return values from and to the caller. (press enter) Step 5: On the screen you will get the message Procedure created.CSEROCKZ. Functions. Communication is passed to a procedure through a parameter and communication is passed out of a procedure through a parameter. which is in the server.. Various types of procedural objects are: Procedures.

variables and SQL statements in a single unit. Functions: Functions are also a collection of SQL and PL/SQL code which can return a value to the caller. Functions do not allow the OUT and IN OUT arguments. It consists of the package definition/specification and package body. It may also include code that is run every time the package is invoked. A package specification consists of the list of functions. This value is returned through the use of the RETURN keyword within the function. functions. Packages: Packages are groups of procedures. The IN OUT variable behaves like a regular variable inside the procedure. Unlike procedures.CSEROCKZ. procedures. constants. 75 WWW. A package body consists of the PL/SQL blocks and specifications for all of the public objects listed in the package specification. To delete procedural objects: SQL> drop procedure <procedure-name> SQL> drop function <function-name> SQL> drop package<package-name> Example: 2 Code a function to return the square of a given number. The name of the package body should be the same as the name of the package specification. functions can return a value to the caller. variables. regardless of the part of the package that is executed.DataBaseManagementSystems LAB MANUAL The IN OUT parameter is used to pass values to the procedure being called and it is used to pass values to the caller of the procedure. A function can return a single value to the caller. cursors and exceptions that will be available to users of the package.COM .

/ Step 3: To test the function: a. At SQL prompt type: SQL> select sqr(10) from dual. / set serveroutput off Example: 3 76 WWW. At SQL prompt. type the following SQL> variable sq number SQL> execute :sq := sqr(10) c. b. In the editor. end.DataBaseManagementSystems LAB MANUAL Step 1: Open the editor Step 2: Type the code below in a file named. type the following set serveroutput on begin dbms_output. END.CSEROCKZ.put_line(‘Square of 10 is ‘ || sqr(10)). Program CREATE OR REPLACE FUNCTION SQR (NO NUMBER) RETURN NUMBER IS BEGIN return no*no.COM . SQR.

emp_no%type) return number.CSEROCKZ.COM . BEGIN select sum(basic) + sum(commission) – sum(deduction) into netsal from salary where emp_no = id. Program CREATE OR REPLACE FUNCTION NETSAL (id in salary.emp_no%type. return (netsal). Program CREATE OR REPLACE PACKAGE MAHEPACK AS function netsal (id in salary. / To test the function: At SQL prompt. procedure tax (id in salary.emp_no%type) RETURN NUMBER IS netsal salary. procedure totsales 77 WWW. type SQL> variable sal number SQL> execute :sal := netsal(1001) SQL> print sal Example: 4 Code a package Step 1: Open the editor and create the package Step 2: Type the code below in a file named. end.DataBaseManagementSystems LAB MANUAL Code a function to return the net salary of a given employee.basic%type. MAHEPACK. tax out number).

04. / Step 3: Save the above file and open the editor to create the package body Program CREATE OR REPLACE PACKAGE BODY MAHEPACK AS function netsal (id in salary.basic%type. else tax := netsalary * 0. end.02. 2).emp_no%type) return number is netsal salary. elsif netsalary < 4000 then tax := netsal * 0.01. 78 WWW.cstid%type. begin netsalary := netsal(id).emp_no%type. begin select sum(basic) + sum(commission) – sum(deduction) into netsal from salary where emp_no = id.CSEROCKZ. end if. tax out number) is netsalary number(10. sal out number). END. return (netsal). procedure tax (id in salary. if netsalary < 2000 then tax := netsalary * 0.COM .DataBaseManagementSystems LAB MANUAL (cid in cstmast.

loop fetch cur_tr into id. price. if cur_tr%rowcount = 0 then raise_application_error(-20020. end.itmid. open cur_tr. end loop. ‘ERREOR!!!THERE IS NO DATA’). qty.DataBaseManagementSystems LAB MANUAL end.TRNQTY%TYPE. trnqty. exit when cur_tr%notfound. / Step 4: Save the above file and to create the package. begin sales := 0. END.ITMPRICE%TYPE.cstid%type. procedure totsales (cid in cstmast. sal := sales.CSEROCKZ.ITMID%TYPE. sal out number) is id TRN. close cur_tr. cursor cur_tr is select trn. itmprice from trn. price ITMMAST. 2) := 0. end if.COM . qty TRN. sales NUMBER(10. itmmast where trn.itmid.itmid = itmmast. at SQL prompt type SQL> start mpack SQL> start mpackb 79 WWW. sales := sales + qty * price.cstid = cid and trn.

rolls back any effects of the procedure. :tx) SQL> print tx Or SQL> variable nsal number SQL> execute :nsal := mahepack. SQL> SHOW ERRORS Raise Application Error: RAISE_APPLICATION_ERROR procedure is one of Oracles utilities which help the user to manage the error conditions in the applications by specifying user-defined error numbers and messages. WEEK 12 (PL/SQL) 34) (i) Creation of simple PL/SQL program which includes declaration section. executable section and exception handling section ( ex: Student marks can be selected from the table and printed for those who secured first class and an exception can be raised if no records were found). at SQL prompt type SQL> variable tx number SQL> execute mahepack. It terminates the procedure execution.CSEROCKZ.DataBaseManagementSystems LAB MANUAL Step 5: To execute.netsal(1001) SQL> print nsal PS: Show Errors: SHOW ERRORS is used to display the line number and error of the most recent compilation errors. ROLLBACK and SAVEPOINT in SQL block. 80 WWW. It takes 2 input parameters – the error number (which must be between -20000 and -20999) and the error message to display.tax(1001. (ii) Insert data into student table and use COMMIT. returns any user-specified error number and error message.COM .

36) Program development using WHILE LOOPS. department>) Step 1: Open the editor Step 2: Type the code below in a file named. Program CREATE TRIGGER UPDSAL BEFORE UPDATE ON SALARY FOR EACH ROW BEGIN insert intosalaryaud 81 WWW. basic. CASE and CASE expression. invoke functions in SQL statements and write complex functions. USER defined exceptions. package bodies. package variables and cursors and calling stored packages.DataBaseManagementSystems LAB MANUAL 35) Develop a program that includes the features NESTED IF. TRSAL. commission. (Salary < emp_no. 40) Develop programs using features of parameters in a CURSOR. FOR UPDATE CURSOR. department> Salaryaud < emp_no. BUILT IN exceptions. deduction.COM . passing parameters IN and OUT procedures. The program can be extended using the NULLIF and COALESCE functions. WHERE CURRENT of clause and CURSOR variables. nested loops using ERROR handling. basic. deduction. salary_date. salary_date. numeric FOR LOOPS. private objects. Example: 1 Write a row trigger to insert the existing values of the salary table into a new table when the salary table is updated.CSEROCKZ. 37) Program development using creation of procedure. commission. RAISE APPLICATION ERROR. 38) Program development using creation of stored function. 39) Program development using creation of package specification.

end.department). end if. :old. Program DECLARE total_sal number(9). Example: 2 Write a trigger to restrict the user from using the emp table on Tuesday. :old.emp_no. Then check to see that the total salary does not exceed Rs 20000. :old.salary_date. END / Step 3: Save the above file Step 4: To create the trigger. 'Cannot delete on Tuesday'). 82 WWW. If total salary is greater than Rs 20000 then undo the updates made to emp 1001 and emp 1002. at SQL prompt type SQL> start trsal Step 5: To test the trigger. :old.commission.basic.deduction. update values in salary table and see if data is inserted in salaryaud table.DataBaseManagementSystems LAB MANUAL values (:old.CSEROCKZ. / Example: 3 Write a PL/SQL block of code that first inserts a record in an Emp table. 'day')) = 'tuesday') then raise_application_error(-20121.COM . :old. Update salaries of emp 1001 and emp 1002 by Rs 2000 and Rs 1500. Program create or replace trigger tr2 before insert or update or delete on emp begin if (rtrim(to_char(sysdate.

It then marks and saves the current position in the transaction by using the SAVEPOINT. 1000). / PS: The above program first inserts a record into emp table.DataBaseManagementSystems LAB MANUAL BEGIN insert into emp values (‘1009’. to calculate the area of the circle for the values of radius varying from 1 to 10. if total_sal > 20000 then ROLLBACK TO SQVEPOINT no_update. END.CSEROCKZ. end if. Store the odd radius values and the corresponding areas in a table. update emp set sal = sal + 1500 where emp_id = 1002. Example: 4 Write a PL/SQL code of block. ‘Ram’. ie ignores the 2 updates and only commits the insert. SAVEPOINT no_update. update emp set sal = sal + 2000 where emp_id = 1001. COMMIT. 83 WWW.COM . if the salaries are exceeding 20000 it rollsback to the save point. select sum(sal) into total_sal from emp. If the salaries do not exceed 20000 then the insert and 2 updates are committed. It updates the salaries.

radius number(5). else dbms_output.DataBaseManagementSystems LAB MANUAL Program declare pi constant number(4. NOT INSERTING!!!’). areaa). while radius <= 10 loop areaa := pi*power(radius.14.2).areaa).areaa). radius:=radius+1.CSEROCKZ. end loop.COM . end case. areaa). when radius = 3 then insert into area values (radius. / 84 WWW.put_line(‘EVEN RADIUS.areaa). begin radius := 1. when radius = 9 then insert into area values(radius.2) := 3. areaa number(14. when radius = 7 then insert into area values(radius. when radius = 53 then insert into area values(radius.2). end. case when radius = 1 then insert into area values (radius.

DataBaseManagementSystems LAB MANUAL Overview of SQL DDL.gives user's access privileges to database REVOKE . Some examples: SELECT .add comments to the data dictionary GRANT .delete objects from the database TRUNCATE . Some examples: CREATE .COM .alters the structure of the database DROP .CSEROCKZ.withdraw access privileges given with the GRANT command DML is Data Manipulation Language statements.remove all records from a table. including all spaces allocated for the records ar removed COMMENT .retrieve data from the a database 85 WWW.to create objects in the database ALTER . DDL is Data Definition Language statements. DML and DCL Commands.

insert data into a table UPDATE .Change transaction options like what rollback segment to use 86 WWW.updates existing data within a table DELETE .control concurrency DCL is Data Control Language statements.identify a point in a transaction to which you can later roll back ROLLBACK . the space for the records remain CALL .restore database to original since the last COMMIT SET TRANSACTION .save work done SAVEPOINT .call a PL/SQL or Java subprogram EXPLAIN PLAN .deletes all records from a table.explain access path to data LOCK TABLE .COM .CSEROCKZ.DataBaseManagementSystems LAB MANUAL INSERT . Some examples: COMMIT .

RESULT: Table created. DROP. RESULT: Table created. Name Null? Type ---------------------------VARCHAR2(20) DATE 87 --------------------------------.CREATE TABLE Syntax: CREATE TABLE tablename (column_name data_ type constraints. prof1 varchar(20). …) Example: INPUT: SQL> CREATE TABLE Emp ( EmpNo short CONSTRAINT PKey PRIMARY KEY. EName VarChar(15).2) not null).DataBaseManagementSystems LAB MANUAL Basic SQL DDL Commands. SQL .salary number(7. doj date not null. SQL>Create table prog20 (pname varchar2(20) not null). To practice basic SQL DDL Commands such as CREATE. Mgr short CONSTRAINT FKey1 REFERENCES EMP (EmpNo). DeptNo short CONSTRAINT FKey2 REFERENCES DEPT(DeptNo)). Job Char(10) CONSTRAINT Unik1 UNIQUE.prof2 varchar(20). etc. sex varchar(1) not null. SQL>desc prog20.-------PNAME DOJ NOT NULL NOT NULL WWW.dob date not null.COM . Hiredate Date.CSEROCKZ. 1.

2) 2. RESULT: Table Dropped.INSERT INTO Syntax:  INSERT INTO tablename VALUES (value list) Single-row insert 88 WWW. Here EMP is table name NOT NULL NOT NULL DATE VARCHAR2(1) VARCHAR2(20) VARCHAR2(20) NOT NULL Basic SQL DML Commands.COM .ALTER TABLE INPUT: SQL>ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo). TRUNCATE TRUNCATE TABLE <TABLE NAME>.DataBaseManagementSystems LAB MANUAL DOB SEX PROF1 PROF2 SALARY NUMBER(7. SQL .CSEROCKZ. DELETE. 1. SQL . 3. etc. 4. To practice basic SQL DML Commands such as INSERT. SQL . ALTER TABLE EMP DROP CONSTRAINT Pkey1. Similarly.DROP TABLE – Deletes table structure – Cannot be recovered – Use with caution INPUT: SQL> DROP TABLE EMP. RESULT: Table Altered.

‘Smith’).’05-may-56’).’c’.CSEROCKZ.’SUP3’.’f’. SQL> Insert into prog values('&pname'. INPUT: SQL>Insert into prog20 values(‘Hema’.’c+ +’. Enter value for pname: ravi Enter value for doj: 15-june-81 89 WWW. INPUT: SQL>Insert into prog values(‘&pname’. SNAME) SELECT SNO.10)  Inserting one row.’&doj’). all/some columns at a time.DataBaseManagementSystems LAB MANUAL INSERT INTO S VALUES(‘S3’.’25000’).’BLORE’.’25-sept-01’28-jan-85’.’MADRAS’) Other Examples: INPUT: SQL>Insert into prog values (‘kkk’.S1’ Smith’  Inserting many rows. SNAME FROM S WHERE CITY IN (‘BLORE’. many columns at a time INSERT INTO S (SNO.'&doj'). INSERT INTO NEW_SUPPLIER (SNO.COM . RESULT: 1 row created. RESULT: 1 row created. SNAME) VALUES (‘S1’.

10 * SAL SQL> update emp set sal=20000 where empno=7369. SQL .COM . SQL .DataBaseManagementSystems LAB MANUAL RESULT: old 1: Insert into prog values('&pname'. Basic SQL DCL Commands. ROLLBACK etc. To practice basic SQL DCL Commands such as COMMIT.CSEROCKZ.UPDATE Syntax: UPDATE tablename SET column_name =value [ WHERE condition] Examples: UPDATE S SET CITY = ‘KANPUR’ WHERE SNO=‘S1’ UPDATE EMP SET SAL = 1. 3. 2. 90 WWW. RESULT: 1 row deleted.'&doj') new 1: Insert into prog values('ravi'.DELETE FROM Syntax: DELETE FROM tablename WHERE condition Examples: DELETE FROM SP WHERE PNO= ‘P1’ DELETE FROM SP INPUT: SQL>Delete from emp where empno=7369.'15-june-81') 1 row created. 1 row updated.

91 WWW. Syntax: COMMIT [WORK] [COMMENT 'comment_text'] COMMIT [WORK] [FORCE 'force_text' [.int] ] FORCE . Oracle will store any commit comment in the data dictionary along with the transaction ID. RESULT: Commit complete.will manually commit an in-doubt distributed transaction force_text .sets a specific SCN.COM .transaction identifier (see the DBA_2PC_PENDING view) int . If a network or machine failure prevents a distributed transaction from committing properly.CSEROCKZ. INPUT: SQL>commit.DataBaseManagementSystems LAB MANUAL 1. COMMIT Save changes (transactional).

SAVEPOINT Save changes to a point (transactional). SAVEPOINT everyone. ROLLBACK Undo work done (transactional).CSEROCKZ. UPDATE employees SET salary = 1000000. 92 WWW. Syntax: SAVEPOINT text_identifier Example: UPDATE employees SET salary = 95000 WHERE last_name = 'Smith'. Syntax: ROLLBACK [WORK] [TO [SAVEPOINT]'savepoint_text_identifier']. SELECT SUM(salary) FROM employees.COM . 3. ROLLBACK [WORK] [FORCE 'force_text']. RESULT:Rollback complete.will manually rollback an in-doubt distributed transaction INPUT: SQL>rollback.DataBaseManagementSystems LAB MANUAL 2. FORCE . SAVEPOINT justsmith.

DataBaseManagementSystems LAB MANUAL ROLLBACK TO SAVEPOINT justsmith.CSEROCKZ. 93 WWW.COM . COMMIT.

------------------------NOT NULL NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7. SQL>select * from emp.List all employee details.DataBaseManagementSystems LAB MANUAL Writing and Practice of Simple Queries. Get the description DEPT table. 1. SQL>desc dept. RESULT: Name --------------------------------DEPTNO DNAME LOC 3. RESULT: 94 Null? --------------------NOT NULL Type --------------------------NUMBER(2) VARCHAR2(14) VARCHAR2(13) WWW. RESULT: Name -------------------------------EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO AGE ESAL Null? Type ----------------------.2) NUMBER(7. Get the description of EMP table.COM . To write simple queries and practice them.CSEROCKZ. SQL>desc emp.2) NUMBER(3) NUMBER(3) NUMBER(10) 2.

both inclusive.---------.---------.--------.---------.List all employee names and their salaries. RESULT ENAME ---------ALLEN JONES BLAKE CLARK SCOTT TURNER FORD russel greg 9 rows selected.-------------------------7369 SMITH CLERK 7902 17-DEC-80 800 0 20 25 0 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 25 0 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 25 0 7566 JONES MANAGER 7839 02-APR-81 2975 500 20 25 0 7698 BLAKE MANAGER 7839 01-MAY-81 2850 1400 30 25 0 4.--------. whose salary lies between 1500/.DataBaseManagementSystems LAB MANUAL EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO AGE ESAL -------.COM .---------. 95 WWW.and 3500/.CSEROCKZ. INPUT SQL>select ename from emp where sal between 1500 and 3500.---------.

COM .CSEROCKZ. List all employees which starts with either J or T. List all employee names and their and their manager whose manager is 7902 or 7566 0r 7789.7789).DataBaseManagementSystems LAB MANUAL 5. RESULT: ENAME --------JONES TURNER JAMES 96 WWW. RESULT ENAME ------SCOTT FORD 6.7566. INPUT SQL>select ename from emp where mgr in(7602. INPUT SQL>select ename from emp where ename like ‘J%’ or ename like ‘T %’.

job from emp where job like ‘M%’ or job like ‘P %’. List all employee names and jobs.20). List all employees who belongs to the department 10 or 20. RESULT: ENAME JOB ---------. whose job title includes M or P. INPUT SQL>select ename from emp where deptno in (10.CSEROCKZ. INPUT SQL>select distinct job from emp. List all jobs available in employee table.DataBaseManagementSystems LAB MANUAL 7. RESULT: ENAME ---------SMITH JONES CLARK 97 WWW.COM . INPUT SQL>select ename. RESULT: JOB --------ANALYST CLERK MANAGER PRESIDENT SALESMAN assistant clerk 7 rows selected. 9.--------JONES MANAGER BLAKE MANAGER CLARK MANAGER KING PRESIDENT 8.

max(sal). INPUT SQL>select count (distinct job) from emp. Find how many job titles are available in employee table.94118 12. INPUT SQL>select ename .DataBaseManagementSystems LAB MANUAL SCOTT KING ADAMS FORD MILLER 8 rows selected.5 3277. RESULT: 98 SAL ---------800 1600 1250 2975 1250 2850 2450 SAL+0. RESULT: ENAME ---------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK 7 rows selected.15* sal from emp. 10. INPUT SQL>select min(sal). sal .5 WWW. sal+0.15*SAL -----------920 1840 1437.5 3421. List all employee names . salary and 15% rise in salary. List minimum .25 1437. maximum . average salaries of employee.5 2817.avg(sal) from emp. RESULT: MIN(SAL) MAX(SAL) AVG(SAL) --------------------------3 5000 1936.CSEROCKZ.COM . 11.

with deptno 20. RESULT 99 WWW.DataBaseManagementSystems LAB MANUAL COUNT(DISTINCTJOB) -----------------7 13. Find how much amount the company is spending towards salaries.COM .sal from emp where job like ‘M%’ and sal > (select min (sal) from emp). INPUT SQL>select ename from emp where deptno = 20. RESULT ENAME ---------JONES BLAKE CLARK SAL ---------2975 2850 2450 15. INPUT SQL>select sum (sal) from emp. Display all employee names and salary whose salary is greater than minimum salary of the company and job title starts with ‘M’.CSEROCKZ. RESULT: MAX(SAL)-MIN(SAL) ----------------4997 14. RESULT SUM(SAL) --------32928 16. What is the difference between maximum and minimum salaries of employees in the organization? INPUT SQL>select max(sal)-min(sal) from emp. INPUT SQL>select ename. Display name of the dept.

ENAME RESULT ---------CLARK SCOTT KING ADAMS JAMES FORD 6 rows selected. INPUT SQL>select ename from emp where comm is null.CSEROCKZ. List ename whose commission is NULL. 100 WWW.DataBaseManagementSystems LAB MANUAL ENAME ---------SMITH JONES SCOTT ADAMS 17.COM .

DataBaseManagementSystems LAB MANUAL 18. so aggregate function be used. INPUT SQL>select ename from emp where mgr is not null. Order by : The order by clause is used to display the results in sorted order. dept.CSEROCKZ. Find no. Group by : The attribute or attributes given in the clauses are used to form groups. programmer.of dept in employee table. To write queries using clauses such as GROUP BY. etc. Source tables: emp.COM . Display total salary spent for each job category. 101 WWW. software. 1. ORDER BY. and retrieving information by joining tables. Having: SQL applies predicates (conditions) in the having clause after groups have been formed. Tuples with the same value on all attributes in the group by clause are placed in one group. RESULT COUNT(DISTINCTENAME -------------------17 19. RESULT ENAME ---------SMITH ALLEN WARD JONES MARTIN 5 rows selected. Writing Queries using GROUP BY and other clauses.sum (sal) from emp group by job. INPUT SQL>select job. study. INPUT SQL>select count (distinct ename) from emp. List ename whose manager is not NULL.

RESULT ENAME SAL ------------------chai 3 JAMES 950 MILLER 1000 ADAMS 1100 russel 2200 5 rows selected. Display the sales cost of package developed by each programmer.DataBaseManagementSystems LAB MANUAL RESULT JOB SUM(SAL) -----------------ANALYST 6000 CLERK 23050 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 assistant 2200 clerk 2003 7 rows selected. RESULT DNAME COUNT(ENAME) ------------------------ACCOUNTING 3 RESEARCH 5 SALES 9 4. dept where emp.CSEROCKZ. 3.deptno group by dname.deptno=dept. sal from emp where sal in (select min(sal) from emp group by mgr). 102 WWW. Display lowest paid employee details under each manager. INPUT SQL>select ename. Display number of employees working in each department and their department name.COM . INPUT SQL> select dname. 2. count (ename) from emp.

RESULT PNAME -------------------john kamala raju 3 rows selected.COM .DataBaseManagementSystems LAB MANUAL INPUT SQL>select pname. SUM(SCOST) ---------12000 12000 12333 103 WWW. sum(scost) from software group by pname.CSEROCKZ.

DataBaseManagementSystems LAB MANUAL 5. count(title) from software group by pname. INPUT SQL>select devin. 6.-----------cobol 1 7. count(title) from software where dcost < 1000 group by devin. RESULT PNAME COUNT(TITLE) -------------------. 8. Display the number of packages in each language for which the development cost is less than thousand. INPUT SQL>select splace. Display each institute name with number of students.-----------BDPS 2 BITS 1 BNRILLIANI 1 COIT 1 HYD 1 5 rows selected. Display the number of packages sold by each programmer. count(pname) from study group by splace. RESULT DEVIN COUNT(TITLE) ---------. were sold? 104 WWW. RESULT SPLACE COUNT(PNAME) -------------------.CSEROCKZ.COM . INPUT SQL>select pname. How many copies of package have the least difference between development and selling cost.-----------john 1 kamala 1 raju 1 ramana 1 rani 1 5 rows selected.

INPUT SQL>select title from software where devin = ‘PASCAL’ and dcost = (select max(dcost)from software where devin = ‘PASCAL’). RESULT DEVIN COUNT(*) ---------. Display the details of software developed by the male programmers earning more than 3000/-.Who are the male programmers earning below the average salary of female programmers? INPUT SQL>select pname from programmer where sal < (select avg(sal) from programmer where sex = ‘F’) and sex = ‘M’. 105 WWW.COM . Which is the costliest package developed in Pascal. RESULT PNAME -------------------vijay 12.of packages. RESULT no rows selected 10. INPUT SQL>select devin. Which language was used to develop most no .DataBaseManagementSystems LAB MANUAL INPUT SQL>select sold from software where scost – dcost=(select min(scost – dcost) from software).CSEROCKZ.---------jsp 2 11. RESULT SOLD --------11 9. count (*) from software group by devin having count(*) = (select max(count(*) ) from software group by devin).

software where sal > 3000 and sex = ‘M’ and programmer. study where devin = ‘c’ and sex =’F’ and splace = ‘pragathi’ and programmer. RESULT no rows selected 13. sold from programmer. title. software. devin from programmer. Display the details of software developed in c language by female programmers of pragathi.DataBaseManagementSystems LAB MANUAL INPUT SQL>select programmer. devin.pname = study. 106 WWW.pname.pname.pname and software. title.COM . INPUT SQL>select software.pname.pname.pname = software.CSEROCKZ.pname = software. scost. dcost.

pname from study where pname = (select pname from software where scost = (select max (scost) from software). RESULT SPLACE PNAME -----------------------SAHBHARI MARY 2. INPUT SQL> select study. count(*) from programmer group by prof1 having count (*) = (select max (count (*) ) from programmer group by prof1). To write queries using Set operations and to write nested queries. Writing Nested Queries.CSEROCKZ.pname and study.DataBaseManagementSystems LAB MANUAL 14. Find the name of the institute in which the person studied and developed the costliest package. Find the salary and institute of a person who developed the highest selling package. INPUT SQL>select splace. Set Operations: UNION INTERSECT EXCEPT OR NOT AND NESTED QUERY:. 1.pname = (select pname from software where scost = (select max (scost) from software)).COM . splace from study. RESULT 107 WWW.A nested query makes use of another sub-query to compute or retrieve the information. programmer where study. sal.pname = programmer. Which language has been stated by the most of the programmers as proficiency one? INPUT SQL>select prof1.pname.

COM .CSEROCKZ.----------MARY 4500 SABHARI 108 WWW.-----.DataBaseManagementSystems LAB MANUAL PNAME SAL SPLACE ----------.

INPUT SQL> select title. (dcost-scost) from software where dcost > scost. INPUT SQL> select p. 6.COM . 1. Display the title.pname and p. Writing Queries using functions. Display the names and dob of all programmers who were born in january.pname and sal= t. dcost. How many packages were developed by the person who developed the cheapest package. Calculate the amount to be recovered for those packages whose development cost has not yet recovered. p.(or) INPUT SQL>select pname.sal from programmer t where pname<>t. count (title) from software where dcost = (select min(dcost) from software) group by pname. Display the details of those who draw the same salary.’MON’)=’JAN’. AIM: To write queries using single row functions and group functions.sal from programmer p. programmer t where p.pname. INPUT SQL>select pname . (scost . 5. dcost. INPUT SQL>select title .DataBaseManagementSystems LAB MANUAL 3.dcost) from software descending order by (scost-dcost). difference of scost and dcost in the descending order of difference.sal. INPUT SQL>select pname. scost.sal = t. RESULT PNAME ------------VIJAY COUNT(TITLE) ---------------------1 4. scost.CSEROCKZ.pname <> t.sal. 109 WWW. dob from programmer where to_char (dob.

INPUT SQL> select pname.COM . 3. INPUT SQL>select pname from programmer where to_char(dob. INPUT SQL>select pname from programmer where doj = (select min (doj) from programmer).’MON’) like to_char (sysdate. 9. Calculate the experience in years of each programmer and display along with programmer name in descending order. INPUT SQL>select to_char (doj. 8.’YY’) having count (*) = (select max (count(*)) from programmer group by to_char (doj. ‘MON’). 4. 6. INPUT SQL> select pname .CSEROCKZ. 2) "EXPERIENCE" from programmer order by months_between (sysdate. 5. ‘YY’) having count(*) = (select max (count(*)) from programmer group by to_char(dob. doj) desc.DataBaseManagementSystems LAB MANUAL 2.’YY’) from programmer group by to_char (doj. In which month most number of programmers are joined. What is the length of the shortest name in programmer table ? 110 WWW. Display the least experienced programmer’s details.’YY’). dob from programmer where dob = (select max (dob) from programmer where to_char (dob. INPUT SQL>select * from programmer where doj = (select max (doj) from programmer). round (months_between(sysdate. most of the programmers are born.'yy') = 65). 7. Who is the most experienced programmer knowing pascal. ‘YY’) from programmer group by to_char (dob.’YY’). doj)/12. In which year. INPUT SQL>select to_char (dob . List out the programmer names who will celebrate their birthdays during current month. Who is the youngest programmer born in 1965.

INPUT SQL>select pname from programmer where length (pname) <=5. INPUT SQL>select lower (title).CSEROCKZ. 11. upper (pname) from software. Display the names of the programmers whose name contains up to 5 characters. 111 WWW. 10.DataBaseManagementSystems LAB MANUAL INPUT SQL>select length (pname) from programmer where length (pname) = select min ( length (pname) from programmer). Display all packages names in small letters and corresponding programmer names in uppercase letters.COM .

DataBaseManagementSystems LAB MANUAL Writing Queries on views. AIM: To write queries on views.pname). 2. SQL>create view xyz as select * from programmer full natural join software. INPUT SQL>delete from view1 where pname like ‘raju’. SQL>create a view view2 as (select pname.74000). 4.’oracle’.’28-jan85’.’12-sep-03’.’dbase’. 5. RESULT 1 row deleted.sex.doj. INPUT SQL>update view1 set salary =50000 where pname like ‘raju’. devin from programmer.CSEROCKZ. RESULT 1 row updated.sal from programmer). Create a view from single table containing all columns from the base table. 1.’f’. 112 WWW.dob. RESULT 1 row created.pname = software. SQL> create view lmn as (select programmer. INPUT SQL> insert into view1 values (‘ramu’. Create a view from two tables with selected columns. title. software where sal < 3000 and programmer. Check all DML commands with above 4 views. Note: update command does not works for all queries on views. 3. SQL>create view view1 as (select * from programmer). Create a view from single table with selected columns. Create a view from two tables with all columns. pname.COM .

BEGIN ENO1:=&ENO1. DA1:=(BASIC1*20)/100.pf%type.DataBaseManagementSystems LAB MANUAL 6.COM . RESULT View dropped. DEPTNO1 empdet.netpay%type.deptno%type. BASIC1 empdet. INPUT SQL>drop view xyz. BASIC1:=&BASIC1.basic%type. DA1 empdet. ENAME1:='&ENAME1'. ENAME1 empdet. RESULT View dropped. PF1 empdet.DA%type. HRA1:=(BASIC1*50)/100. HRA1 empdet.eno%type.HRA%type. Drop views which you generated.CSEROCKZ. NETPAY1 empdet. INPUT SQL>drop view view2. To write a PL/SQL block for inserting rows into EMPDET table with the following Calculations: HRA=50% OF BASIC DA=20% OF BASIC PF=7% OF BASIC NETPAY=BASIC+DA+HRA-PF INPUT DECLARE ENO1 empdet.name%type. Writing PL/SQL block for insertion into a table. DEPTNO1:=&DEPTNO1. 113 WWW. INPUT SQL>drop view view1.

PL/SQL procedure successfully completed. Enter value for basic1: 6000 old 14: BASIC1:=&BASIC1. new 13: DEPTNO1:=10. DEPTNO1. SQL>/ Enter value for eno1: 105 old 11: ENO1:=&ENO1. new 11: ENO1:=104. Enter value for deptno1: 10 old 13: DEPTNO1:=&DEPTNO1. new 12: ENAME1:='SRINIVAS REDDY'. new 14: BASIC1:=6000. END. new 11: ENO1:=105. Enter value for ename1: SRINIVAS REDDY old 12: ENAME1:='&ENAME1'. Enter value for basic1: 6000 old 14: BASIC1:=&BASIC1. new 13: DEPTNO1:=10. 114 WWW. ENAME1.DataBaseManagementSystems LAB MANUAL PF1:=(BASIC1*7)/100. PF1. HRA1. BASIC1. Enter value for ename1: CIRAJ old 12: ENAME1:='&ENAME1'. DA1. NETPAY1).COM . NETPAY1:=BASIC1+HRA1+DA1-PF1. INSERT INTO EMPDET VALUES (ENO1. RESULT: SQL> @BASIC Enter value for eno1: 104 old 11: ENO1:=&ENO1. Enter value for deptno1: 10 old 13: DEPTNO1:=&DEPTNO1.CSEROCKZ. new 12: ENAME1:='CIRAJ'.

INPUT DECLARE num number(5).--------. num1:=num. rem number(5). while(num>0) 115 PF 350 350 385 420 420 WWW. RESULT ENO NAME DEPTNO BASIC HRA DA NETPAY --------. PL/SQL procedure successfully completed.CSEROCKZ. BEGIN num:=&num.--------. s number(5):=0.COM .DataBaseManagementSystems LAB MANUAL new 14: BASIC1:=6000. num1 number(5).-----------------------------.------------------------------101 SANTOSH 10 5000 2500 1000 8150 102 SHANKAR 20 5000 2500 1000 8150 103 SURESH 20 5500 2750 1100 8965 104 SRINIVASA REDDY 10 6000 3000 1200 9780 105 CIRAJ 10 6000 3000 1200 9780 Writing PL/SQL block for checking armstrong number To write a PL/SQL block to check whether given number is Armstrong or not.--------. SQL> SELECT * FROM EMPDET.--------.

CSEROCKZ. num:=trunc(num/10).put_line(num1||' IS NOT ARMSTRONG NUMBER '). new 7: num:=153. / RESULT: SQL>@arm Enter value for num: 153 old 7: num:=&num. End loop. if (s=num1)then dbms_RESULT. new 7: num:=123.3). s:=s+power(rem. else dbms_RESULT.COM .10). SQL> / Enter value for num: 123 old 7: num:=&num. INPUT DECLARE 116 WWW. 153 IS ARMSTRONG NUMBER PL/SQL procedure successfully completed. AIM: To write a PL/SQL block to check whether a given number is Even or Odd. 123 IS NOT ARMSTRONG NUMBER PL/SQL procedure successfully completed.put_line(num1||' IS ARMSTRONG NUMBER '). End if. END. Writing a PL/SQL block for checking a number even or odd.DataBaseManagementSystems LAB MANUAL loop rem:=mod(num.

2). BEGIN num:=&num. SQL> / Enter value for num: 3 old 5: num:=&num.CSEROCKZ. if rem=0 then dbms_RESULT. rem number. end if. Writing PL/SQL block to find sum of digits of a given number. else dbms_RESULT.put_line(' Number '||num||' is Odd'). Number 3 is Odd PL/SQL procedure successfully completed. new 5: num:=6. RESULT: SQL>start even Enter value for num: 6 old 5: num:=&num.DataBaseManagementSystems LAB MANUAL num number(5). new 5: num:=3. rem:=mod(num. END. Number 6 is Even PL/SQL procedure successfully completed. 117 WWW.put_line(' Number '||num||' is Even').COM .

num:=trunc(num/10).10). end loop.put_line('SUM OF DIGITS OF '||num1||' IS: '||sm).CSEROCKZ. SUM OF DIGITS OF 123 IS: 6 PL/SQL procedure successfully completed. new 7: num:=456. sm number(5):=0. num1:=num. while(num>0) loop rem:=mod(num. num1 number(5). / RESULT: SQL> @sum INPUT truncated to 2 characters Enter value for num: 123 old 7: num:=&num. SUM OF DIGITS OF 456 IS: 15 PL/SQL procedure successfully completed. BEGIN num:=&num. rem number(5). sm:=sm+rem. end. INPUT DECLARE num number(5). new 7: num:=123. SQL> @sum INPUT truncated to 2 characters Enter value for num: 456 old 7: num:=&num.DataBaseManagementSystems LAB MANUAL To write a PL/SQL block to find Sum of Digits of a given Number. 118 WWW. dbms_RESULT.COM .

DataBaseManagementSystems LAB MANUAL 119 WWW.COM .CSEROCKZ.

COM . f3 number(5). f2:=f3. dbms_RESULT. THE FIBONACCI SERIES IS: 0 1 1 2 3 5 8 13 120 WWW. while(i<=num) loop f3:=f1+f2. dbms_RESULT. i:=i+1. i number(5):=3. / RESULT: SQL> start fib Enter value for num: 10 old 8: num:=&num.put_line(f1). dbms_RESULT.put_line(f2). END. new 8: num:=10.put_line('THE FIBONACCI SERIES IS:'). dbms_RESULT. end loop. f2 number(5):=1.put_line(f3).CSEROCKZ. f1:=f2. To write a PL/SQL block to Generate Fibonacci Series INPUT DECLARE num number(5). BEGIN num:=&num. f1 number(5):=0.DataBaseManagementSystems LAB MANUAL Writing PL/SQL block for generating Fibonacci series.

else dbms_RESULT. end if. l:=length(name1). l:=l-1.CSEROCKZ. END.put_line(name1||' IS PALINDROME '). while l>0 loop name2:=name2||substr(name1.put_line('REVERSE OF STRING IS:'||NAME2). new 6: name1:='LIRIL'. l number(5). INPUT DECLARE name1 varchar2(20). Writing PL/SQL block for checking palendrome. end loop.DataBaseManagementSystems LAB MANUAL 21 34 PL/SQL procedure successfully completed. name2 varchar2(20). if(name1=name2) then dbms_RESULT.put_line(name1||' IS NOT PALINDROME ').COM .l. BEGIN name1:='&name1'.1). dbms_RESULT. REVERSE OF STRING IS:LIRIL 121 WWW. To write a PL/SQL block to Check the Given String is Palindrome or Not. / RESULT Enter value for name1: LIRIL old 6: name1:='&name1'.

sal. To write a Cursor to display the list of Employees and Total Salary Department wise. s emp.deptno ||' Department name is:' || i.sal%type. dbms_RESULT. cursor c2 is select * from emp.COM . dbms_RESULT.CSEROCKZ.deptno=j. 122 WWW.put_line('Department is :' || i. REVERSE OF STRING IS:MADAM MADAM IS PALINDROME PL/SQL procedure successfully completed. for j in c2 loop if ( i.put_line('----------------------------------------------'). new 6: name1:='MADAM'.dname). INPUT DECLARE cursor c1 is select * from dept. Writing PL/SQL block to demonstrate Cursors. BEGIN for i in c1 loop s:=0.put_line('-------------------------------------------'). dbms_RESULT.DataBaseManagementSystems LAB MANUAL LIRIL IS PALINDROME PL/SQL procedure successfully completed. SQL> / Enter value for name1: MADAM old 6: name1:='&name1'.deptno) then s:=s+j.

ename || ' '|| j. END.sal ). RESULT: SQL> @abc -----------------------------------------------------------------------------Department is :10 Department name is : ACCOUNTING -----------------------------------------------------------------------------7782 CLARK 2450 7839 KING 5000 7934 MILLER 1300 ----------------------------------------------------------------------------Total salary is: 8750 --------------------------------------------------------------------------------------------------------------------------------------------------------Department is :20 Department name is:RESEARCH -----------------------------------------------------------------------------7369 SMITH 800 7566 JONES 2975 7788 SCOTT 3000 7876 ADAMS 1100 7902 FORD 3000 ----------------------------------------------------------------------------Total salary is: 10875 ----------------------------------------------------------------------------------------------------------------------------------------------------------Department is :30 Department name is:SALES -----------------------------------------------------------------------------123 WWW. dbms_RESULT.DataBaseManagementSystems LAB MANUAL dbms_RESULT.put_line('Total salary is: '|| s). dbms_RESULT.empno|| ' '|| j. dbms_RESULT.put_line('----------------------------------------------'). end loop. end loop.put_line(j.COM . end if.CSEROCKZ.put_line('----------------------------------------------').

INPUT DECLARE cursor c(jb varchar2) is select ename from emp where job=jb. em emp. 124 WWW.DataBaseManagementSystems LAB MANUAL 7499 ALLEN 1600 7521 WARD 1250 7654 MARTIN 1250 7698 BLAKE 2850 7844 TURNER 1500 7900 JAMES 950 -----------------------------------------------------------------------------Total salary is: 9400 ----------------------------------------------------------------------------------------------------------------------------------------------------------Department is :40 Department name is:OPERATIONS ----------------------------------------------------------------------------------------------------------------------------------------------------------Total salary is: 0 -----------------------------------------------------------------------------PL/SQL procedure successfully completed.CSEROCKZ. Writing PL/SQL CURSOR To write a Cursor to display the list of employees who are Working as a Managers or Analyst.COM .job%type.

loop fetch c into em.put_line(em). end loop. dbms_RESULT. loop fetch c into em.COM . end loop.DataBaseManagementSystems LAB MANUAL BEGIN open c('MANAGER'). 125 WWW. dbms_RESULT. close c. RESULT: EMPLOYEES WORKING AS MANAGERS ARE: JONES BLAKE CLARK EMPLOYEES WORKING AS ANALYST ARE: SCOTT FORD PL/SQL procedure successfully completed.put_line(em). dbms_RESULT. exit when c%notfound.put_line(' EMPLOYEES WORKING AS MANAGERS ARE:'). dbms_RESULT. exit when c%notfound.CSEROCKZ. END. close c. open c('ANALYST').put_line(' EMPLOYEES WORKING AS ANALYST ARE:').

name.deptno. RESULT: SQL> @EMP Empno. END.sal%type.COM . BEGIN open c.salary of employees are:= 7369 SMITH 20 800 7499 ALLEN 30 1600 7521 WARD 30 1250 7566 JONES 20 2975 7654 MARTIN 30 1250 7698 BLAKE 30 2850 7782 CLARK 10 2450 7788 SCOTT 20 3000 7839 KING 10 5000 7844 TURNER 30 1500 126 WWW.put_line(i||' '||j||' '||k||' '||l).empno%type. l emp. salary of employees are:= ').ename%type.deptno%type. close c. ename. j emp.CSEROCKZ. exit when c%notfound. i emp. name. k. deptno. loop fetch c into i. deptno.put_line('Empno. dbms_RESULT. end loop.DataBaseManagementSystems LAB MANUAL Writing PL/SQL CURSOR To write a Cursor to display List of Employees from Emp Table in PL/SQL block INPUT DECLARE cursor c is select empno. l. j. dbms_RESULT. k emp. sal from emp .

Writing PL/SQL CURSOR To write a Cursor to find employee with given job and deptno. END. INPUT DECLARE cursor c1(j varchar2.DataBaseManagementSystems LAB MANUAL 7876 ADAMS 20 1100 7900 JAMES 30 950 7902 FORD 20 3000 7934 MILLER 10 1300 PL/SQL procedure successfully completed.deptno%type. open c1(jb. ename from emp where job=j and deptno=dn. jb emp.COM . fetch c1 into row1. BEGIN jb:='&jb'.ename. else dbms_RESULT. RESULT: SQL> @CUR Enter value for jb: MANAGER old 7: jb:='&jb'.row1.empno||' ' ||'employee name is:'||row1.ename).empno.CSEROCKZ.put_line('empno is:'||row1. d:=&d. end if.job%type. if c1%notfound then dbms_RESULT. d emp. row1 emp%rowtype. new 7: jb:='MANAGER'. dn number) is select empno.d).put_line('Employee does not exist'). Enter value for d: 20 127 WWW.

dbms_RESULT. Writing PL/SQL BLOCK using string functions.'x')). 128 WWW. l number(5). empno is:7566 employee name is:JONES PL/SQL procedure successfully completed. BEGIN a:='&a'.COM .1.put_line('Using Substring Function:' || substr(a.put_line('Using Substring Function:' || substr(a. dbms_RESULT. To write a PL/SQL block to apply String Functions on a given input String. Enter value for d: 40 old 8: d:=&d.DataBaseManagementSystems LAB MANUAL old 8: d:=&d.3)).1)).put_line('Using Ltrim function for xxxabcxxxx:' || ltrim('xxxabcxxxx'. Employee does not exist PL/SQL procedure successfully completed.put_line('Using Lower Function:' || lower(a)). INPUT DECLARE a varchar2(20). dbms_RESULT.put_line('Using Initcap Function:' || initcap(a)). new 8: d:=40. SQL> / Enter value for jb: CLERK old 7: jb:='&jb'. dbms_RESULT. new 7: jb:='CLERK'. l:=length(a).CSEROCKZ. dbms_RESULT. new 8: d:=20.l. dbms_RESULT.put_line('Using UPPER Function:' || upper(a)).

l+4. END.DataBaseManagementSystems LAB MANUAL dbms_RESULT. new 5: a:='santosh reddy'.'*')).put_line('Using Lpad function :'|| lpad(a.COM . Using Lower Function:santosh reddy Using UPPER Function:SANTOSH REDDY Using Initcap Function:Santosh Reddy Using Substring Function:y Using Substring Function:san Using Ltrim function for xxxabcxxxx:abcxxxx Using Rtrim function for xxxabcxxxx:xxxabc Using Lpad function :****santosh reddy Using Rpad function :santosh reddy**** PL/SQL procedure successfully completed. dbms_RESULT.put_line('Using Rtrim function for xxxabcxxxx:'|| rtrim('xxxabcxxxx'.'*')).'x')). new 5: a:='UMA SHANKAR'. dbms_RESULT. SQL> / Enter value for a: UMA SHANKAR old 5: a:='&a'.l+4.put_line('Using Rpad function :'|| rpad(a. RESULT: SQL>@STR Enter value for a: santosh reddy old 5: a:='&a'. Using Lower Function:uma shankar Using UPPER Function:UMA SHANKAR Using Initcap Function:Uma Shankar Using Substring Function:R Using Substring Function:UMA Using Ltrim function for xxxabcxxxx:abcxxxx Using Rtrim function for xxxabcxxxx:xxxabc Using Lpad function :****UMA SHANKAR Using Rpad function :UMA SHANKAR**** PL/SQL procedure successfully completed 129 WWW.CSEROCKZ.

DataBaseManagementSystems LAB MANUAL Writing PL/SQL triggers To write a TRIGGER to ensure that DEPT TABLE does not contain duplicate of null values in DEPTNO column.COM .CSEROCKZ. INPUT CREATE OR RELPLACE TRIGGER trig1 before insert on dept for each row DECLARE 130 WWW.

deptno.'&dname'.------------10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON SQL> insert into dept values(&deptnp.'&dname'. SQL> select * from dept. DEPTNO DNAME LOC --------.TRIG1' 131 WWW.-------------.'&loc'). end if. line 5 ORA-04088: error during execution of trigger 'SCOTT.CSEROCKZ.DataBaseManagementSystems LAB MANUAL a number.'&loc') new 1: insert into dept values(null.'hyd') insert into dept values(null.TRIG1".'marketing'. end if. BEGIN if(:new.'error:: cannot have duplicate deptno'). Enter value for deptnp: null Enter value for dname: marketing Enter value for loc: hyd old 1: insert into dept values(&deptnp. if(a=1) then raise_application_error(-20002. RESULT: SQL> @trigger Trigger created.'hyd') * ERROR at line 1: ORA-20001: error::deptno cannot be null ORA-06512: at "SCOTT. else select count(*) into a from dept where deptno=:new.COM .'error::deptno cannot be null'). END.'marketing'.deptno is Null) then raise_application_error(-20001.

'&dname'.'&loc') new 1: insert into dept values(50.'MARKETING'.DataBaseManagementSystems LAB MANUAL SQL> / Enter value for deptnp: 10 Enter value for dname: manager Enter value for loc: hyd old 1: insert into dept values(&deptnp.COM .'hyd') insert into dept values(10.'&dname'.CSEROCKZ. DEPTNO DNAME LOC --------.'hyd') * ERROR at line 1: ORA-20002: error:: cannot have duplicate deptno ORA-06512: at "SCOTT. line 9 ORA-04088: error during execution of trigger 'SCOTT. SQL> select * from dept.'manager'.'&loc') new 1: insert into dept values(10.-------------.------------10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 50 MARKETING HYDE 132 WWW.TRIG1' SQL> / Enter value for deptnp: 50 Enter value for dname: MARKETING Enter value for loc: HYDERABAD old 1: insert into dept values(&deptnp.'manager'.'HYDERABAD') 1 row created.TRIG1".

DataBaseManagementSystems LAB MANUAL Locking Table. Several tables can be locked with a single command .] table [options] IN lockmode MODE [NOWAIT] LOCK TABLE [schema. LOCK TABLE table1. AIM: To learn commands related to Table Locking LOCK TABLE Statement Manually lock one or more tables. 133 WWW.table2.] view [options] IN lockmode MODE [NOWAIT] Options: PARTITION (partition) SUBPARTITION (subpartition) @dblink lockmodes: EXCLUSIVE SHARE ROW EXCLUSIVE SHARE ROW EXCLUSIVE ROW SHARE* | SHARE UPDATE* If NOWAIT is omitted Oracle will wait until the table is available.separate with commas e. Default Locking Behaviour : A pure SELECT will not lock any rows. Syntax: LOCK TABLE [schema.CSEROCKZ.COM .g.table3 IN ROW EXCLUSIVE MODE.

ROW SHARE = Allow ROW EXCLUSIVE or ROW SHARE or SHARE locks to be granted to the locked rows. present it in a layout specified by Form 134 WWW. Multiple Locks on the same rows with LOCK TABLE Even when a row is locked you can always perform a SELECT (because SELECT does not lock any rows) in addition to this.COM .DataBaseManagementSystems LAB MANUAL INSERT.. SHARE ROW EXCLUSIVE = Allow ROW SHARE locks to be granted to the locked rows. ROW EXCLUSIVE = Allow ROW EXCLUSIVE or ROW SHARE locks to be granted to the locked rows. EXCLUSIVE = Allow SELECT queries only Although it is valid to place more than one lock on a row. also known as Forms.will place a ROW EXCLUSIVE lock.. Forms are the applications that connect to a database.will place a ROW EXCLUSIVE lock.FOR UPDATE NOWAIT . SELECT.. SHARE = Allow ROW SHARE or SHARE locks to be granted to the locked rows. UPDATE or DELETE's . UPDATES and DELETE's may still cause a wait if a conflicting row lock is held by another transaction.FROM.CSEROCKZ. Generation of Forms using ORACLE FORM BUILDER To design a form using Oracle Developer 2000 Introduction Use Form Builder to simplify for the creation of data-entry screens. retrieve information requested by the user. each type of lock will allow additional locks to be granted as follows..

Update. Manipulate table’s record. If you don’t want to get this window anymore uncheck the ‘Display at startup’ box. 135 WWW.’ If you want to build a new form manually. login in as “scott” password “tiger." then "Connect. Welcome window You will get the ‘Welcome to the Form Builder’ window. Form Builder Tool Open the "Form Builder" tool.DataBaseManagementSystems LAB MANUAL designer." In the ‘Connect’ window. click on "Cancel” or check ‘Build a new form manually’ and click ‘OK. You can start your work with any of the following options: • Use the data Block Wizard • Build a new form manually • Open an existing form • Build a form based on a template The default is ‘Use the data Block Wizard.” then click “CONNECT.CSEROCKZ. previous record. Navigate a table.” Notice that the box next to ‘Database Objects’ is not empty anymore and it has a ‘+’ sign in it.COM . Use “content” canvas. Use next. In this Hands-On. highlight "Database Objects. Enter query." Go to the Main menu and choose "File.’ Connect to database In the ‘Object Navigator’ window. That will indicate that this item is expandable and you are able to see its entire objects. you learn how to: Create a Data block for the “Customer” table. Use “execute query”. Insert. Delete and Save record. Form Builder allows you to build forms quickly and easily. Create a layout. and allow the user to modify or add information.

If you drag your cursor on the icon a tooltip will show ‘Create. Selecting Tables Click on “browse. Go to the Main menu and choose “File.” and click on the "create” icon. choose the default option “Data Block Wizard” and click "OK. The ‘Create’ icon is in the vertical tool bar in the ‘Object Navigator’ window. highlight "Data Blocks. "c:_de. Create a Module In the ‘Object Navigator’ window.” select “Save as” to store the new object in the “iself” folder and save it as customer data entry. Create a Data Block In the ‘Object Navigator’ window. highlight the "cust11” table.COM . Select the default option ‘Table or View’ and then click “NEXT” again. Type of Data Block Select the type of data block you would like to create by clicking on a radio button.DataBaseManagementSystems LAB MANUAL Click on the ‘+’ sign next to the ‘Database Objects’ to expand all database schemas.CSEROCKZ. This is a default name." In this example the ‘DE’ abbreviation stands for Data Entry.” In the ‘Tables’ window." Welcome Data Block In the ‘Welcome Data Block Wizard’ window click on the “NEXT” icon. highlight module1.’ New Data Block In the ‘New Data Block’ window." Selecting columns for the Data Block Wizard 136 WWW. then click "OK. It is a green ‘+’ sign.

You use the vertical or horizontal toolbar canvases for your push buttons. you can have multiple layers of objects and it is the same as the tab canvas. Stacked. Think of the ‘Content’ canvas as one flat place to have all your objects.” Selecting canvas In the ‘Layout Wizard’ window. In the stacked canvas." then click “Next. click ”Next. and click "Finish. click on the one arrow sign.” Selecting Columns for the Layout Wizard In the ‘Layout Wizard’ window. And then select all columns. titles. These are the columns that you want to be displayed on the canvas.COM . Horizontal Toolbar. pictures. Then click “Next. Simply select the data block in the Object Navigator and click the Data Block Wizard toolbar button. Canvas is a place that you will have your objects such as columns.DataBaseManagementSystems LAB MANUAL To choose all columns. Welcome screen In the ‘Welcome to the Layout Wizard’ window. use the default checkmark radio button (Create the data block.” Layout Wizard End of the Data Block Wizard and beginning of the Layout Wizard In the ‘Congratulations’ screen. Check the different types of canvases by clicking on the ‘down arrow’ box next to the ‘Type’ field. The following are different types of canvases: Content. select all the columns. select the "new canvas" option. Select "content. and click “next." You can also use the Data Block Wizard to modify your existing data block. Vertical Toolbar. click on the two arrow signs in the ‘Data Block Wizard’ window. and Tab. To choose selected columns. then call the Layout Wizard).” 137 WWW. If you have already had your canvas.CSEROCKZ. etc. select the canvas and then click on the next. or choose ‘Data Block wizard’ from the ‘Tools’ menu.

Select "Forms. When you change size. Congratulation Screen In the ‘Congratulations’ window. a tooltip will be displayed and you see ‘Execute Query. width.COM ." Checkmark the ‘Display Scrollbar’ box when you use multiple records or the ‘Tabular’ option. Execute Query Click on the "Execute Query" icon below the main menu. click on the ‘Run’ icon. The object module should be compiled successfully before executing the Form." You will see the output layout screen.” Selecting a layout style Select a layout style for your frame by clicking a radio button.DataBaseManagementSystems LAB MANUAL Change your objects appearances Change size or prompt if needed. To run the form. In this window. drag your cursor to view all the icon descriptions. You can change the measurement units. click “Next. If you drag the cursor on the toolbar in the ‘Forms Runtime’ window. You can change it to inch or centimeter.CSEROCKZ. and height for each item on the canvas.’ So to know all your option. The ‘Run’ icon is on the horizontal toolbar in the ‘CUSTOMER_DE’ canvas." and then click “next. Select “Tabular. Select "Form." if you want one record at a time to be displayed. As a default the default units for item width and height are points.” if you want more than one record at a time to be displayed. Make some window adjustments and then run the form. click "Finish.” Record layout Type the "Frame Title" and click "next. you can enter a prompt. 138 WWW.

139 WWW. Remember in this stage.DataBaseManagementSystems LAB MANUAL Next Record Click on the "Next Record" icon to navigate to the next record. Apply the changes. Enter Query Click on the "Enter Query" icon to query selected records. A drop down menu will be displayed. All items on the forms will be blanked. your record was inserted but not committed yet. You can either type all the customer information or duplicate it from pervious record. Next and Previous Record Click "next record" and "previous record" to navigate through the records and the one was added. Duplicate Record To duplicate the previous record. This is an easy way to navigate through the “Customer” table. Insert Record Click "Insert Record" to add new customer. go to the main menu and select the ‘Record’ sub-menu. Previous Record Click on the "Previous Record" icon to navigate to the previous record. Save transactions Click "Save" to commit the insert statement. Select the ‘Duplicate’ option in the sub-menu.CSEROCKZ.COM .

If you have not committed any transaction. Click “YES” to save changes.COM . Lock a Record You can also lock the record. you will be prompted to save changes. Exit from Form Runtime Exit the FORM Runtime. Don’t forget to save the Form. RABAD 140 WWW.CSEROCKZ.DataBaseManagementSystems LAB MANUAL Delete Record Click "Remove Record" to delete the record. Click “OK” for acknowledgement.

CSEROCKZ.DataBaseManagementSystems LAB MANUAL Selecting the type of form to create 141 WWW.COM .

DataBaseManagementSystems LAB MANUAL Object wizard 142 WWW.CSEROCKZ.COM .

DataBaseManagementSystems LAB MANUAL Selecting the canvas on which data block can be displayed 143 WWW.CSEROCKZ.COM .

COM .CSEROCKZ.DataBaseManagementSystems LAB MANUAL Form showing the Employee details 144 WWW.

CSEROCKZ. 4. 2. You have been assigned to write the reports based on their reports layout requirements. Connect to database In the Object Navigator. numeric and date items." then select the "Connect" option. Open Report Builder tool Open the "Report Builder" tool. change the format mask for dollar. login as “iself” password schooling. You will learn how to: use report wizard. your client is a stock broker that keeps track of its customer stock transactions.Write a tabular report. It is similar in concept to the idea of an Oracle table. then click “CONNECT. report builder. Hands-on In this Hands-On.” Save a report 145 WWW.Apply user layout Format mask.DataBaseManagementSystems LAB MANUAL EXPT#28. “date model”. property palette. 3. work on query and group box.” choose "File. highlight "Database Objects. In the ‘Connect’ window. see report style. Oracle. returns output from your select statement in tabular format.Run the report. Generating REPORTS using Oracle Developer 2000 AIM: To design reports using Oracle Developer 2000 Introduction Tabular report shows data in a table format.Test the repot. use tabular style. object navigator. navigating through report’s record. Your client wants you to create a simple listing report to show list of the stock trades by using stocks table for their brokerage company Your tasks are: 1.COM . by default.

make sure to save the report in the ISELF folder and name it "rpt01_stock_history. 146 WWW. highlight the "untitled" report. change the name to Q_STOCKS. In the Group property palette.” and select the “Save as” option.DataBaseManagementSystems LAB MANUAL In the Object Navigator. double click on the "Data Model" icon. write a query to read all the stocks record sorted by their symbol.” Change SQL box’s name In the Data Model window. right click on the ‘Q_1’ and open its property palette. type ‘Stock History’ in the Title box and choose the report style as ‘Tabular.” report number 1 stock history. (SQL Query Statement) SELECT * FROM stocks ORDER BY symbol Click “OK. Open Report Wizard In the Data Model. choose “File. click on the "SQL Query" icon. Data Model In the Object Navigator. In its property palette. Then close the window. Create SQL box In the Data Model window. In the ‘Save as’ window.’ Notice that when you change the report style a layout of that report will be displayed on the screen. Change GROUP box’s name In the Data Model. change the name to ‘G_STOCKS. In the ‘SQL Query Statement’ window.COM . right click on the group box (G_SYMBOL) and open its property palette. In the Style tab. in the “SQL” box. Then drag the plus sign cursor and click it anywhere in the “Data Model” screen where you wish your object to be. click on the ‘Report Wizard’ icon on the horizontal tool bar.CSEROCKZ.’ and close the window. on the Report Wizard window.

Totals. Labels and Template tabs Click “NEXT” to go to the Data tab. select and drag it while the cursor is on the object. Click “NEXT” to open the Labels tab. select the fields for which you would like to calculate totals. We have none in this hands-on exercise. Data. This is a simple report. and structure. Know report’s functions To know each icon functionalities. drag your cursor on it and a tooltip will display its function. Click “NEXT” again to go to the Template tab. Click “NEXT” to navigate to the Fields tab. Select all the columns to be display. click on the "next page" or "previous page" icon on the horizontal toolbar.DataBaseManagementSystems LAB MANUAL Choose a different style to display its layout of its report style. line widths. 147 WWW. Click “NEXT” to navigate to Totals tab. you should have your output report on the screen. Use the default template and click “finish.” Running a report Now. Navigate through the output To navigate through the output report in the Report Editor .COM . Do the same with the "first page" or "last page" icon. Move an object To move an object. To resize an object . fonts.CSEROCKZ. and choose a template for your report. select it and drag its handler to the preferred size. Fields. Your report will inherit the template’s colors. Resize an object Maximize the output report and format the report layout. select the fields that you would like to be display in your report.Live Pre-viewer. Use the “zoom in” and “zoom out” icon to preview the report. In the ‘SQL Query Statement’ verify your query. modify the labels and widths for your fields and totals as desired.

"add decimal place. Then go to the toolbar and click on the “$” icon.DataBaseManagementSystems LAB MANUAL Change Format Mask To change the "format mask" of a column. and click on the ‘. Right click on the "trade date" column and open its "property palette." and the “right justify” format to the all currency columns (Todays Low.0’ icon (apply commas). To open an object’s property palette.CSEROCKZ. Also." Change the date "Format Mask" property and make it “year 2000 complaint (MM-DD-RR). Todays High. right click on it and select the Property Palette option. and make it right justify. you can change any attributes of field by opening its property palette.” 148 WWW. and current price) Select the “traded today” column. the column should be selected.COM .

CSEROCKZ.DataBaseManagementSystems LAB MANUAL Selecting type of report Creating reports Selecting the format of reports 149 WWW.COM .

DataBaseManagementSystems LAB MANUAL Selecting the Table in database 150 WWW.COM .CSEROCKZ.

DataBaseManagementSystems LAB MANUAL Selecting the columns in the report 151 WWW.COM .CSEROCKZ.

DataBaseManagementSystems LAB MANUAL Modify the labels in a table 152 WWW.CSEROCKZ.COM .

CSEROCKZ.DataBaseManagementSystems LAB MANUAL Choose a template to represent the report 153 WWW.COM .

COM .DataBaseManagementSystems LAB MANUAL To specify the completion of report generation 154 WWW.CSEROCKZ.

CSEROCKZ.DataBaseManagementSystems LAB MANUAL 155 WWW.COM .

]object TO grantee [WITH GRANT OPTION] [WITH HIERARCHY OPTION] GRANT object_priv [(column. column.]object TO grantee [WITH GRANT OPTION] [WITH HIERARCHY OPTION] GRANT ALL PRIVILEGES [(column.COM .....DataBaseManagementSystems LAB MANUAL EXPT#29. column..)] ON DIRECTORY directory_name TO grantee [WITH GRANT OPTION] [WITH HIERARCHY OPTION] 156 WWW... AIM: To learn GRANT and REVOKE commands to restrict privileges.. column.)] ON [schema..)] ON [schema. (1) GRANT Statement Grant privileges to a user (or to a user role) Syntax: Grant System-wide Privs: GRANT system_priv(s) TO grantee [IDENTIFIED BY password] [WITH ADMIN OPTION] GRANT role TO grantee [IDENTIFIED BY password] [WITH ADMIN OPTION] GRANT ALL PRIVILEGES TO grantee [IDENTIFIED BY password] [WITH ADMIN OPTION] Grant privs on specific objects: GRANT object_priv [(column. Providing Security using GRANT and REVOKE.CSEROCKZ.

]object TO grantee [WITH GRANT OPTION] [WITH HIERARCHY OPTION] grantee: user role PUBLIC system_privs: CREATE SESSION . trigger. session.. synonym. views. operator. ALTER. rollback segment. profile. tablespace. SELECT ANY TABLE . ALTER or DROP: cluster.Use an unlimited amount of any tablespace. sequence. UPDATE. procedure.. user.Update rows in tables and views in any schema INSERT ANY TABLE .Insert rows into tables and views in any schema Also System Admin rights to CREATE. INSERT.COM . DELETE. index.. INDEX. materialized view.DataBaseManagementSystems LAB MANUAL GRANT object_priv [(column. dimension. (full list of system privs) object_privs: SELECT. context. REFERENCES roles: 157 WWW. or mviews in any schema UPDATE ANY TABLE . outline.CSEROCKZ.Query tables. view. DEBUG. role. EXECUTE. type.Allows user to connect to the database UNLIMITED TABLESPACE . table. column. link. database. directory.)] ON JAVA [RE]SOURCE [schema.

OSOPER. DELETE_CATALOG_ROLE AQ_USER_ROLE. | role.COM ." may also be written as "GRANT ALL. EXECUTE_CATALOG_ROLE. RECOVERY_CATALOG_OWNER .g.advanced queuing SNMPAGENT . |PUBLIC} 158 WWW. UPDATE (sal) ON scott.. Syntax: Roles: REVOKE role FROM {user. | role.emp TO emma WITH HIERARCHY OPTION will grant the object privilege on all subobjects. AQ_ADMINISTRATOR_ROLE ... IMP_FULL_DATABASE SELECT_CATALOG_ROLE. "GRANT ALL PRIVILEGES.CSEROCKZ. OSDBA. |PUBLIC} System Privs: REVOKE system_priv(s) FROM {user. including any created after the GRANT statement is issued. EXP_FULL_DATABASE.. GRANT SELECT (empno).Enterprise Manager/Intelligent Agent.heterogeneous services plus any user defined roles you have available Notes: Several Object_Privs can be assigned in a single GRANT statement e." (ii) REVOKE Statement Revoke privileges from users or roles. SYSOPER. WITH GRANT OPTION will enable the grantee to grant those object privileges to other users and roles.rman HS_ADMIN_ROLE .DataBaseManagementSystems LAB MANUAL SYSDBA.

| role. INSERT.CSEROCKZ. |PUBLIC} [CASCADE CONSTRAINTS] [FORCE] REVOKE object_priv [(column1. UPDATE. column2. DELETE.]object FROM {user.)] ON [schema. | role. UPDATE ANY TABLE plus too many others to list here 159 WWW. | role.]object FROM {user.)] ON DIRECTORY directory_name FROM {user. DROP ANY VIEW RESTRICTED SESSION. |PUBLIC} [CASCADE CONSTRAINTS] [FORCE] REVOKE object_priv [(column1. | role.COM .. | role. SELECT. ALL PRIVILEGES system_privs ALTER ANY INDEX.DataBaseManagementSystems LAB MANUAL REVOKE ALL FROM {user. column2.)] ON [schema..]object FROM {user... CREATE TABLE. |PUBLIC} [CASCADE CONSTRAINTS] [FORCE] key: object_privs ALTER. |PUBLIC} Object Privs: REVOKE object_priv [(column1. column2.)] ON JAVA [RE]SOURCE [schema. BECOME USER. REFERENCES. UNLIMITED TABLESPACE. |PUBLIC} [CASCADE CONSTRAINTS] [FORCE] REVOKE object_priv [(column1. EXECUTE. column2. INDEX.

OSDBA.Table1 from USER1 Owners of objects ALWAYS have full permissions on those objects.0.2) http://www.ncl. 4. Oracle 9i Release 2 (9. EXP_FULL_DATABASE.ac. REFERENCES: 1.DataBaseManagementSystems LAB MANUAL roles Standard Oracle roles SYSDBA.920/a96540/t oc.901/a90125/toc.uk/teaching/facilities/swdoc/oracle9i/server.ss64.1) SQL Reference. Oracle 9i Release 1 (9. WWW. This is one reason it makes sense to place tables in one schema and the packaged prodecures used to access those tables in a separate schema.mit.CSEROCKZ.htm. e. www. RESOURCE and DBA are now deprecated (supported only for backwards compatibility) unless you are still running Oracle 6. IMP_FULL_DATABASE plus any user defined roles you have available FORCE. Database Systems Instructor: Prof. The roles CONNECT. 3.COM .This usually means you tried revoking permission from the table owner. OSOPER. 160 2. will revoke all privileges from a user-defined-type and mark it's dependent objects INVALID. http://downloadeast.g.edu). An A-Z Index of Oracle SQL Commands (version 9.htm.2) SQL Reference. Oracle will not allow REVOKE select on USER1. SYSOPER.0 Error ORA-01927 "cannot REVOKE privileges you did not grant" .com/ora/.com/docs/cd/A91202_01/901_doc/server. Samuel Madden Source: MIT Open Courseware (http://ocw.oracle.cs.

lc.org.com userid:demo@infosys and passwork:infosys.leidenuniv.ua/orelly/oracle/langpkt/index. RDBMS Lab Guide.htm PL/SQL User's Guide and Reference.2) http://www. 161 WWW. 7.920/a96624/to c.COM . http://www.campusconnect.unix. 6.htm. Release 2 (9.DataBaseManagementSystems LAB MANUAL 5.nl/awcourse/oracle/appdev.infosys. www.CSEROCKZ. Orelly PL/SQL Pocket Reference.

What is a Database system? The database and DBMS software together is called as Database system. Ø Providing multiple user interfaces. 6. Ø Providing backup and recovery. What is DBMS? It is a collection of programs that enables user to create and maintain a database. Ø Unauthorised access is restricted. Ø Security Problems. describes what data are stored in database and what relationship among those data. 162 WWW. 3. Ø Logical level: The next higher level of abstraction. 2. 5. 4. built and populated with data for a specific purpose.CSEROCKZ. Describe the three levels of data abstraction? The are three levels of abstraction: Ø Physical level: The lowest level of abstraction describes how data are stored. What is database? A database is a logically coherent collection of data with some inherent meaning. Ø Data integrity. Advantages of DBMS? Ø Redundancy is controlled.DataBaseManagementSystems LAB MANUAL VIVA VOICE QUESTIONS AND ANSWERS 1. Ø View level: The highest level of abstraction describes only part of entire database. Ø Difficult in accessing data. In other words it is general-purpose software that provides the users with the processes of defining. representing some aspect of real world and which is designed.COM . Ø Data isolation. Ø Enforcing integrity constraints. Disadvantage in File Processing System? Ø Data redundancy & inconsistency. Ø Concurrent access is not possible. constructing and manipulating the database for various applications.

COM . with performance at least comparable to that of existing system.DataBaseManagementSystems LAB MANUAL 7. What is Data Independence? Data independence means that “the application is independent of the storage structure and access strategy of data”. In other words. Two types of Data Independence: 163 WWW. It is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems. Intension It is a constant value that gives the name.CSEROCKZ. 8. How is the data structure of System R different from the relational structure? Unlike Relational systems in System R Ø Domains are not supported Ø Enforcement of candidate key uniqueness is optional Ø Enforcement of entity integrity is optional Ø Referential integrity is not enforced 11. Define the "integrity rules" There are two Integrity rules. This is time dependent. 10. structure of table and the constraints laid on it. What is extension and intension? Extension It is the number of tuples present in a table at any instance. What is System R? What are its two major subsystems? System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. 9. The ability to modify the schema definition in one level should not affect the schema definition in the next higher level. Ø Entity Integrity: States that “Primary key cannot have NULL value” Ø Referential Integrity: States that “Foreign Key can be either a NULL value or should be Primary Key value of other relation. Its two subsystems are Ø Research Storage Ø System Relational Data System.

that is. What is an Entity type? It is a collection (set) of entities that have same attributes. Entities are described in a database by a set of attributes. What is an Entity? It is a 'thing' in the real world with an independent existence. What is Object Oriented model? This model is based on collection of objects.CSEROCKZ. An object contains values stored in instance variables with in the object. data relationships data semantics and constraints. Hence accounts for logical data independence. These bodies of code are called methods. 15. What is a view? How it is related to data independence? A view may be thought of as a virtual table. Thus the view can insulate users from the effects of restructuring and growth in the database. In other words. a table that does not really exist in its own right but is instead derived from one or more underlying base table. 16. 14. 18. What is E-R model? This data model is based on real world that consists of basic objects called entities and of relationship among these objects. What is an Entity set? It is a collection of all entities of particular entity type in the database. 17. Ø Logical Data Independence: Modification in logical level should affect the view level.COM . Objects that contain same types of values and the same methods are grouped together into classes. 164 WWW. An object also contains bodies of code that operate on the object. What is Data Model? A collection of conceptual tools for describing data. 13. there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Growth and restructuring of base tables is not reflected in views. NOTE: Logical Data Independence is more difficult to achieve 12.DataBaseManagementSystems LAB MANUAL Ø Physical Data Independence: Modification in physical level should not affect the logical level.

21. What is Relationship set? The collection (or set) of similar relationships. What is Weak Entity set? An entity set may not have sufficient attributes to form a primary key.. Each tuple is an ordered list of n-values t=(v1. What is a Relation Schema and a Relation? A relation Schema denoted by R(A1. A relation is defined as a set of tuples. What is Relationship? It is an association among two or more entities. What is an attribute? It is a particular property. 23.. vn). t2. which describes the entity. What is an Extension of entity type? The collections of entities of a particular entity type are grouped together into an entity set.DataBaseManagementSystems LAB MANUAL 19.COM . 27. 26. Let r be the relation which contains set tuples (t1.v2. tn). What is degree of a Relation? It is the number of attribute of its relation schema. An) is made up of the relation name R and the list of attributes Ai that it contains. . 165 WWW. 22. then it is said to be Weak Entity set. 24. 28.. What is Relationship type? Relationship type defines a set of associations or a relationship set among a given set of entity types. A2. ….. What is DDL (Data Definition Language)? A data base schema is specifies by a set of definitions expressed by a special language called DDL. t3. What is degree of Relationship type? It is the number of entity type participating. .. 25.. and its primary key compromises of its partial key and primary key of its parent entity.CSEROCKZ. 20.

34.DataBaseManagementSystems LAB MANUAL 29. 166 WWW. 30. What is DDL Interpreter? It interprets DDL statements and record them in tables containing metadata. What is DML Compiler? It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand.Definition Language? The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called data storagedefinition language. What is DML (Data Manipulation Language)? This language that enable user to access or manipulate data as organised by appropriate data model. Ø Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data. 36. What is Query evaluation engine? It executes low-level instruction generated by compiler. What is Record-at-a-time? The Low level or Procedural DML can specify and retrieve each record from a set of records. What is VDL (View Definition Language)? It specifies user views and their mappings to the conceptual schema. This retrieve of a record is said to be Record-at-a-time. 33. 35. This retrieve of a record is said to be Set-at-a-time or Set-oriented. What is SDL (Storage Definition Language)? This language is to specify the internal schema.CSEROCKZ. 31.COM . Ø Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data. What is Set-at-a-time or Set-oriented? The High level or Non-procedural DML can specify and retrieve many records in a single DML statement. 32. This language may specify the mapping between two schemas. 37. What is Data Storage .

g. QUEL. 42. E. where 167 WWW. E.CSEROCKZ. 41. Ø We cannot remove any dependency from F and still have set of dependency that is equivalent to F. Codd. 44. Ø We cannot replace any dependency X A in F with a dependency Y A where Y is a proper subset of X and still have a set of dependency that is equivalent to F. What is Multivalued dependency? Multivalued dependency denoted by X Y specified on relation schema R. What is Relational Calculus? It is an applied predicate calculus specifically tailored for relational databases proposed by E. ILL.g. What is Functional Dependency? A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets of R specifies a constraint on the possible tuple that can form a relation state r of R. QUEL The domain-oriented calculus has domain variables i. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. 40. variables that range over the underlying domains instead of over relation. variable whose only permitted values are tuples of that relation. How does Tuple-oriented relational calculus differ from domainoriented relational calculus The tuple-oriented calculus uses a tuple variables i.DataBaseManagementSystems LAB MANUAL 38. When is a functional dependency F said to be minimal? Ø Every dependency in F has a single attribute for its right hand side.e.F. It consists of a set of operations that take one or two relations as input and produce a new relation.g.COM . 43.e. DEDUCE. of languages based on it are DSL ALPHA. What is normalization? It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs) and primary key to achieve the properties Ø Minimizing redundancy Ø Minimizing insertion. What is Relational Algebra? It is procedural query language. This means the value of X component of a tuple uniquely determines the value of component Y. 39. E.. deletion and update anomalies..

47. 49. if every non prime attribute is non-transitively dependent on primary key. What is Lossless join property? It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition. What is 1 NF (Normal Form)? The domain of attribute must include only atomic (simple. indivisible) values. What is 4NF? A relation schema R is said to be in 4NF if for every Multivalued dependency X 168 WWW.DataBaseManagementSystems LAB MANUAL X and Y are both subsets of R. X must be a candidate key. Ø A is a prime attribute of R. 51. What is 2NF? A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key. In other words. What is Fully Functional dependency? It is based on concept of full functional dependency. What is BCNF (Boyce-Codd Normal Form)? A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every FD X A. A functional dependency X Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more. What is 3NF? A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is true Ø X is a Super-key of R. 46. 50.CSEROCKZ.COM . specifies the following constraint on any relation r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the following properties Ø t3[x] = t4[X] = t1[X] = t2[X] Ø t3[Y] = t1[Y] and t4[Y] = t2[Y] Ø t3[Z] = t2[Z] and t4[Z] = t1[Z] where [Z = (R-(X U Y)) ] 45. 48.

Ø X is a super key. Artificial Key: If no obvious key. R2. then the last resort is to simply create a key.. Rn} that holds R.. Ø The join dependency is implied by the set of FD.. compound and natural key? Partial Key: It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity.. then combining multiple elements to create a unique identifier for the construct is known as creating a compound key. one the following is true Ø Ri = R for some i. 52.DataBaseManagementSystems LAB MANUAL Y that holds over R. What are partial. Then this is known as developing an artificial key. What is 5NF? A Relation schema R is said to be 5NF if for every join dependency {R1.COM . Natural Key: When one of the data elements stored within a construct is utilized as the primary key. Compound Key: If no single data element uniquely identifies occurrences within a construct. alternate. What is indexing and what are the different kinds of indexing? Indexing is a technique for determining how quickly specific data can be found. by assigning a unique number to each record or occurrence. 55. over R in which the left side is key of R. What is Domain-Key Normal Form? A relation is said to be in DKNF if all constraints and dependencies that should hold on the the constraint can be enforced by simply enforcing the domain constraint and key constraint on the relation. . 54. then it is called the natural key. one of following is true Ø X is subset or equal to (or) XY = R.CSEROCKZ. artificial. either stand alone or compound is available. Types: Ø Binary search style indexing 169 WWW. Alternate Key: All Candidate Keys excluding the Primary Key are known as Alternate Keys. It is sometime called as Discriminator. 53.

What is durability in DBMS? Once the DBMS informs the user that a transaction has successfully completed. It is also called data dictionary. This information is stored in a collection of relations maintained by the system called metadata. R3. . Rn is a lossless-join decomposition of R . R2. Inclusion Dependency: An Inclusion Dependency is a statement of the form that some columns of a relation are contained in other columns. A foreign key constraint is an example of inclusion dependency.CSEROCKZ. This property is called durability. 58. Rn} is said to hold over a relation R if R1. Aggregation: A concept which is used to model a relationship between a collection of entities 170 WWW. .. What is meant by query optimization? The phase that identifies an efficient execution plan for evaluating a query that has the least estimated cost is referred to as query optimization.. 59. There is no set of sound and complete inference rules for JD.. What is join dependency and inclusion dependency? Join Dependency: A Join dependency is generalization of Multivalued dependency. information about every relation and index that it contains. DBMS ensures this by undoing the actions of incomplete transactions. What is system catalog or catalog relation? How is better known as? A RDBMS maintains a description of all the data that it contains. R2.COM . What do you mean by atomicity and aggregation? Atomicity: Either all actions are carried out or none are. 60. 57. Users should not have to worry about the effect of incomplete transactions.A JD {R1... its effects should persist even if the system crashes before all its changes are reflected on disk.DataBaseManagementSystems LAB MANUAL Ø B-Tree indexing Ø Inverted list indexing Ø Memory resident table Ø Table indexing 56..

66. 61. The query language can be classified into data definition language and data manipulation language. Such situations are called phantom deadlocks and they lead to unnecessary aborts. the DBMS can reduce the amount of work to be done during restart in the event of subsequent crashes. It is used when we need to express a relationship among relationships. What do you mean by flat file database? It is a database in which there are no programs or user access languages. What is a query? A query with respect to DBMS relates to user commands that are used to interact with a data base. By taking checkpoints.DataBaseManagementSystems LAB MANUAL and relationships. Brief theory of Network.COM . or nested queries. 63. which keeps its Physical Structure hidden from user. are used to bring back a set of rows to be used by 171 WWW. What is a Phantom Deadlock? In distributed deadlock detection. It has no cross-file capabilities but is user-friendly and provides user-interface management. What is a checkpoint and When does it occur? A Checkpoint is like a snapshot of the DBMS state.CSEROCKZ. What are the different phases of transaction? Different phases are Ø Analysis phase Ø Redo Phase Ø Undo phase 64. 65. What do you mean by Correlated subquery? Subqueries. Hierarchical schemas and their properties Network schema uses a graph data structure to organize records example for such a database management system is CTCG while a hierarchical schema uses a tree data structure example for such a system is IMS. 62. 67. the delay in propagating local information might cause the deadlock detection algorithms to identify deadlocks that do not really exist. 68. What is "transparent DBMS"? It is one.

The following example demonstrates a non-correlated subquery. dispatches and 172 WWW.CNUM) 69. this is called a correlated subquery. If the subquery is executed for each row of the parent. designed specifically for controlling data access. which is the software. What is RDBMS KERNEL? Two important pieces of RDBMS architecture are the kernel.g. What are the unary operations in Relational Algebra? PROJECTION and SELECTION.CNUM = ORDER. 70. What are the primitive operations common to all record management systems? Addition.CSEROCKZ. and securing data. 72. its primary functions are storing. Name the buffer in which all the commands that are typed in are stored ‘Edit’ Buffer 71. 73. it can be executed once for the parent query or it can be executed once for each row returned by the parent query. An RDBMS maintains its own list of authorized users and their associated privileges. PRODUCT: Concatenation of every row in one relation with every row in another. Are the resulting relations of PRODUCT and JOIN operation the same? No. manages memory caches and paging. deletion and modification. JOIN: Concatenation of rows from one relation and related rows from another.DataBaseManagementSystems LAB MANUAL the parent query. Columns from the subquery cannot be referenced anywhere else in the parent query. which consists of the system-level data structures used by the kernel to manage the database You might think of an RDBMS as an operating system (or set of subsystems). controls locking for concurrent resource usage. E. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where CUST. A correlated subquery can be easily identified if it contains any references to the parent subquery columns in its WHERE clause. and the data dictionary. retrieving. Depending on how the subquery is written.COM .

DataBaseManagementSystems LAB MANUAL schedules user requests. 77. Distribution Control. All the files are binary. and maps the actual physical storage location. Lock Management 75. Not only RDBMS takes care of locating data it also determines an optimal access path to store or retrieve the data 76. The control files and the redo logs support the functioning of the architecture 173 WWW. provides access to them. and manages space usage within its table-space structures. What is the job of the information stored in data-dictionary? The information in the data dictionary validates the existence of the objects.COM . Name the sub-systems of a RDBMS I/O. Language Processing. Which part of the RDBMS takes care of the data dictionary? How Data dictionary is a set of tables and database objects that is stored in a special area of the database and maintained exclusively by the kernel. 79. Security. Define SQL and state the differences between SQL and other conventional programming Languages SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational database structures. Storage Management. Name the three major set of files on disk that compose a database in Oracle There are three major sets of files on disk that compose a database. 76. Process Control.CSEROCKZ. Memory Management. Logging and Recovery. How do you communicate with an RDBMS? You communicate with an RDBMS using Structured Query Language (SQL) 78. Transaction Control. These are Ø Database files Ø Control files Ø Redo logs The most important of these are the database files where the actual data resides. The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them. 74.

control files and log files. also known as Oracle background processes. the system global area or shared global area.DataBaseManagementSystems LAB MANUAL itself. All three sets of files must be present. putting the database on different disk drives. What are the four Oracle system processes that must always be up and running for the database to be useable The four Oracle system processes that must always be up and running for the database to be useable include DBWR (Database Writer). The combination of the SGA and the Oracle background processes is known as an Oracle instance 81. if there is one. provide functions for the user processes—functions that would otherwise be done by the user processes themselves Oracle database-wide system memory is known as the SGA. and the database administrator might have to recover some or all of the database using a backup. LGWR (Log Writer). Without these files. 80. and all the Oracle background processes and user processes can use them. the number (or location) of the files is immaterial. The data and control structures in the SGA are shareable. and PMON (Process Monitor). Any database must have at least one control file. more than one files are used. How many of these files should a database have at least? Why? Database Files The database files hold the actual data and are typically the largest in size.CSEROCKZ. Depending on their sizes. What are database files. or backing up and restoring just part of the database. SMON (System Monitor). What is an Oracle Instance? The Oracle system processes. In terms of accessing and using the data in the tables and other objects. 82. The database files are fixed in size and never grow bigger than the size at which they were created Control Files The control files and redo logs support the rest of the architecture. you cannot access the database.COM . although you typically have more than one to 174 WWW. and available to Oracle for any data on the database to be useable. open. You must have at least one database file but usually. the tables (and other objects) for all the user accounts can go in one database file—but that's not an ideal situation because it does not make the database structure very flexible for controlling access to storage for different users.

it never changes until the row is deleted or the table is dropped. If any type of failure occurs. Redo Logs Any database must have at least two redo logs.CSEROCKZ. 83. the combination of which uniquely identifies the physical storage location of the row. and the synchronization information to ensure that all three sets of files are always in step. Oracle can apply the information in the redo logs automatically without intervention from the DBA. the redo logs record all changes to the user objects or system objects. the information is recorded in the control files. Application developers also use it in SQL statements as a quick way to access a row once they know the ROWID 84. Regardless of the block size. What is ROWID? The ROWID is a unique database-wide physical address for every row on every table. which contains the row Ø The row within the block (because each block can hold many rows) The ROWID is used internally in indexes as a quick means of retrieving rows with a particular key value. The ROWID consists of the following three components. the entire block is not available for holding data. the changes recorded in the redo logs can be used to bring the database to a consistent state without losing any committed transactions. These Oracle blocks are the smallest unit of storage. which contains the block with the rows Ø Oracle block address. The redo log files are fixed in size and never grow dynamically from the size at which they were created. This block header has a minimum size. 175 WWW. Every time you add a new database or redo log file to the database. the date and time it was created.COM . The block size should be a multiple of the operating system block size. but it can grow. These are the journals for the database. What is Oracle Block? Can two Oracle Blocks have the same address? Oracle "formats" the database files into a number of Oracle blocks when they are first created—making it easier for the RDBMS software to manage the files and easier to read data into the memory areas. Increasing the Oracle block size can improve performance. Once assigned (when the row is first inserted into the database). In the case of non-data loss failure. Oracle takes up some space to manage the contents of the block. Ø Oracle database file number. The control file records the name of the database. the location of the database and redo logs. but it should be done only when the database is first created.DataBaseManagementSystems LAB MANUAL guard against loss.

The trigger can e defined to execute once for the entire statement or once for every row that is inserted. 88. Along with the RDBMS software. What is database Trigger? A database trigger is a PL/SQL block that can defined to automatically execute for insert. The Import utility reads the file produced by an export. A stored procedure executes the SQL commands and returns the result to the client. and inserts the data If Export and Import are used as a means of backing up and recovering the database. Stored procedures are used to reduce network traffic.CSEROCKZ. Name two utilities that Oracle provides. The best you can do is recover the database to the time when the export was last performed. Two blocks can have the same block address if they are in different database files. A stored procedure can have a set of compound SQL statements. all the changes made to the database cannot be recovered since the export was performed. there are twelve events for which you can define database triggers. What are stored-procedures? And what are the advantages of using them. 87.DataBaseManagementSystems LAB MANUAL Each Oracle block is numbered sequentially for each database file starting at 1. 85. update. recreates the definitions of objects. Oracle provides two utilities that you can use to back up and restore the database. A database trigger can call database procedures that are also written in PL/SQL. 86. or deleted. How are exceptions handled in PL/SQL? Give some of the internal exceptions' name PL/SQL exception handling is a mechanism for dealing with run-time errors 176 WWW. For any one table. and delete statements against a table. Stored procedures are database objects that perform a user defined operation. These utilities are Export and Import. which are use for backup and recovery. updated.COM . The Export utility dumps the definitions and data for the specified part of the database to an operating system binary file.

System-Defined Exceptions Exceptions internal to PL/SQL are raised automatically upon error. control returns to the block in which the handler was defined. User-Defined Exceptions PL/SQL enables the user to define exception handlers in the declarations area of subprogram specifications. the exception name is ot_failure. After the exception handler executes.DataBaseManagementSystems LAB MANUAL encountered during procedure execution. The following is an example of a subprogram exception: EXCEPTION when NO_DATA_FOUND then g_out_status_code := 'FAIL'. Errors cause the program to raise an exception with a transfer of control to the exception-handler block. Within this exception is the RAISE statement that transfers control back to the ot_failure exception handler.CSEROCKZ. The exception handler must be defined within a subprogram specification. User accomplishes this by naming an exception as in the following example: ot_failure EXCEPTION. out_msg := g_out_msg. Use of this mechanism enables execution to continue if the error is not severe enough to cause procedure termination. PL/SQL internal exceptions. Exception Name Oracle Error CURSOR_ALREADY_OPEN ORA-06511 DUP_VAL_ON_INDEX ORA-00001 177 WWW. In this case. Code associated with this handler is written in the EXCEPTION specification area as follows: EXCEPTION when OT_FAILURE then out_status_code := g_out_status_code. If there are no more executable statements in the block. RAISE ot_failure. Table below gives a complete list of internal exceptions.COM . control returns to the caller. This technique of raising the exception is used to invoke all user-defined exceptions. PL/SQL internal exceptions. NO_DATA_FOUND is a system-defined exception.

DataBaseManagementSystems LAB MANUAL
INVALID_CURSOR ORA-01001 INVALID_NUMBER ORA-01722 LOGIN_DENIED ORA-01017 NO_DATA_FOUND ORA-01403 NOT_LOGGED_ON ORA-01012 PROGRAM_ERROR ORA-06501 STORAGE_ERROR ORA-06500 TIMEOUT_ON_RESOURCE ORA-00051 TOO_MANY_ROWS ORA-01422 TRANSACTION_BACKED_OUT ORA-00061 VALUE_ERROR ORA-06502 ZERO_DIVIDE ORA-01476 In addition to this list of exceptions, there is a catch-all exception named OTHERS that traps all errors for which specific error handling has not been established. 89. Does PL/SQL support "overloading"? Explain The concept of overloading in PL/SQL relates to the idea that you can define procedures and functions with the same name. PL/SQL does not look only at the referenced name, however, to resolve a procedure or function call. The count and data types of formal parameters are also considered. PL/SQL also attempts to resolve any procedure or function calls in locally defined packages before looking at globally defined packages or internal functions. To further ensure calling the proper procedure, you can use the dot notation. Prefacing a procedure or function name with the package name fully qualifies any procedure or function reference. 90. Tables derived from the ERD a) Are totally unnormalised b) Are always in 1NF c) Can be further denormalised d) May have multi-valued attributes (b) Are always in 1NF

178

WWW.CSEROCKZ.COM

DataBaseManagementSystems LAB MANUAL
91. Spurious tuples may occur due to i. Bad normalization ii. Theta joins iii. Updating tables from join a) i & ii b) ii & iii c) i & iii d) ii & iii (a) i & iii because theta joins are joins made on keys that are not primary keys. 92. A B C is a set of attributes. The functional dependency is as follows AB -> B AC -> C C -> B a) is in 1NF b) is in 2NF c) is in 3NF d) is in BCNF (a) is in 1NF since (AC)+ = { A, B, C} hence AC is the primary key. Since C B is a FD given, where neither C is a Key nor B is a prime attribute, this it is not in 3NF. Further B is not functionally dependent on key AC thus it is not in 2NF. Thus the given FDs is in 1NF. 93. In mapping of ERD to DFD a) entities in ERD should correspond to an existing entity/store in DFD b) entity in DFD is converted to attributes of an entity in ERD c) relations in ERD has 1 to 1 correspondence to processes in DFD d) relationships in ERD has 1 to 1 correspondence to flows in DFD (a) entities in ERD should correspond to an existing entity/store in DFD 94. A dominant entity is the entity a) on the N side in a 1 : N relationship b) on the 1 side in a 1 : N relationship c) on either side in a 1 : 1 relationship d) nothing to do with 1 : 1 or 1 : N relationship (b) on the 1 side in a 1 : N relationship
179

WWW.CSEROCKZ.COM

DataBaseManagementSystems LAB MANUAL
95. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By CUSTOMER Union Select 'EAST', CUSTOMER From CUST_DTLS Where REGION = 'E' Order By CUSTOMER The above is a) Not an error b) Error - the string in single quotes 'NORTH' and 'SOUTH' c) Error - the string should be in double quotes d) Error - ORDER BY clause (d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS 96. What is Storage Manager? It is a program module that provides the interface between the low-level data stored in database, application programs and queries submitted to the system. 97. What is Buffer Manager? It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory. 98. What is Transaction Manager? It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflicting. 99. What is File Manager? It is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a disk. 100. What is Authorization and Integrity manager? It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data. 101. What are stand-alone procedures? Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not
180

WWW.CSEROCKZ.COM

What are cursors give different types of cursors. on a tablespace-by-tablespace basis. 102. The users can continue to make full use of the files. the only option available in the event of data file loss is restoring all the files from the latest backup. The database is restored to the most consistent state without any loss of committed transactions. The language supports the use two types of cursors Ø Implicit Ø Explicit 103. 104. redo logs. All work performed on the database since the last backup is lost.COM . that the files of the tablespace are to backed up. The database must be running in ARCHIVELOG mode for the hot backup option. The cold backup is not an available option. What are Armstrong rules? How do we say that they are complete and/or sound The well-known inference rules for FDs Ø Reflexive rule : 181 WWW. he/she can use the operating system to copy those files to the desired backup destination.CSEROCKZ. You must shut down the instance to guarantee a consistent copy. This is a straight file copy.DataBaseManagementSystems LAB MANUAL available for reference from other Oracle tools. Once the user has indicated that he/she wants to back up the tablespace files. If a data loss failure does occur. the lost database files can be restored using the hot backup and the online and offline redo logs created since the backup was done. which slows execution. PL/SQL uses cursors for all database information accesses statements. What is cold backup and hot backup (in case of Oracle)? Ø Cold Backup: It is copying the three sets of files (database files. Another limitation of standalone procedures is that they are compiled at run time. and control file) when the instance is shut down. If a cold backup is performed. usually from the disk directly to tape. So different means of backing up database must be used — the hot backup. Issue a SQL command to indicate to Oracle. Ø Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. including making changes to the data.

For finding the minimal key it is required to find the closure that is the set of all attributes that are dependent on any given set of attributes under the given set of functional dependency. For each attribute A in K a. For each FD Y Z in F and if Y belongs to X+ then add Z to X+ 4. Repeat steps 2 and 3 until Old X+ = X+ Algo. Ø Augmentation rule: If X Y then XZ YZ. 105. closure for X. Set Old X+ = X+ 3. Ø Decomposition rule : If X YZ then X Y.. What do you understand by dependency preservation? Given a relation R and a set of FDs F. dependency preservation states that the closure of the union of the projection of F on each decomposed relation Ri is equal to the closure of F. i. They are sound because it is enough if a set of FDs satisfy these three. WY Z} then WX Z.DataBaseManagementSystems LAB MANUAL If Y is subset or equal to X then X Y. Compute (K – A)+ with respect to F b. Set X+ = X 2.e. I Determining X+. They are called complete because using these three rules we can generate the rest all inference rules. ((PR1(F)) U … U (PRn(F)))+ = F+ 182 WWW. X Z} then X YZ. given set of FDs F 1. How can you find the minimal key of relational schema? Minimal key is one which can identify each tuple of the given relation schema uniquely. given set of FDs F 1. Ø Pseudo Transitive rule : If {X Y.CSEROCKZ. Of these the first three are known as Amstrong Rules.COM .II Determining minimal K for relation schema R. Algo. Ø Transitive rule: If {X Y. Y Z} then X Z. Ø Union or Additive rule: If {X Y. If (K – A)+ = R then set K = (K – A)+ 106. Set K to R that is make K a set of all attributes in R 2.

108. What are the different types of JOIN operations? Equi Join: This is the most common type of join which involves only equality comparisions. The disadvantage in this type of join is that there 183 WWW. Retroactive Update: The updates that are applied to database after it becomes effective in real world . What is meant by Proactive. Proactive Update: The updates that are applied to database before it becomes effective in real world . Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world . then some dependency is lost in the decomposition.COM . 107.CSEROCKZ. Retroactive and Simultaneous Update.DataBaseManagementSystems LAB MANUAL if decomposition is not dependency preserving.

COM .com Keep Watching for Regular Updates….!! 184 WWW.cserockz.CSEROCKZ.com www.DataBaseManagementSystems LAB MANUAL EMAIL: cserockz08@gmail.

You're Reading a Free Preview

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