Вы находитесь на странице: 1из 31

INFORMATION SCIENCE & ENGENEERING.

vi SEMESTER

DATABASE LABORATORY
ISE

Name:

Reg. No.

Batch
CONTENTS

SL. Experiment Page No. Max.


No. Marks
MARKS DETAILS

1. Internal Assessment Marks : 50


2. Minimum Internal Assessment Marks : 25
3. Maximum Marks in the University Examination : 100
4. VTU Lab Exam marks split up
Procedure : 15 % of Total
Viva : 15 % of Total
Execution : 70 % of Total

Do’s and Don’t in the Laboratory

DO …..
• Come prepared to the Lab.
• Submit your Records to the Lecturer and sign in the Log Book on entering
the Lab.
• Follow the Lab exercise cycles as instructed by the Department. Violating
the same will result in deduction of marks.
• Use the same login(if any) assigned to you.
• Put the chairs back to its position before you leave.
• Backlog exercises to be executed after completing regular exercises.

DON’T …..
• Move around in the lab during the lab session.
• Tamper System Files or Try to access the Server.
• Write Data Sheets or Records in the Lab.
• Change the system assigned to you without the notice of the Lab Staff.
• Teaching your friends.

Director, Dept. of MCA


INTRODUCTION TO SQL

 SQL is the language used in most RDBMSs to enable users to access data.
 Developed by a prototype RDBMS called SYSTEM R by IBM in mid seventies.
 ORACLE introduced the first commercially viable SQL implementation in 1979.
 SQL *PLUS does not care whether SQL commands are given in lowercase or
uppercase.
 Case matters only when SQL *PLUS or ORACLE is checking a value for equality
in the database.

THE SQL COMMAND SET

An SQL statement is a specific instance of a valid SQL command.

A statement partially consists of SQL reserved words, whoch cannot be used for any
other purpose.

SQL statements are divided into the following categories :

 Data Definition Language (DDL) Statements


 Data Manipulation Language (DML) Statements
 Transaction Control Statements.

Data Definition Statements are : Create, Alter, Drop, Rename, Grant, Revoke.

Data Manipulation Statements are : Delete, Insert, Select, Update

Transaction Control Statements are : Commit, Rollback

ELEMENTARY DATATYPES IN ORACLE

In order to create any table using DDL, datatypes are essentially required to define the
various data entities of the table definition.

Just as people can be classified into different types, based on characteristics (shy,
outgoing, smart, talkative), different kinds of data can be classified according to the
characteristics.

Elementary datatypes in ORACLE include :


 Number
 Char – fixed length, printable chars – 255ch
 Varchar2 – variable char 4000 bytes
 Date – century, yy, mm, dd, hh, mm, ss
 Long - printable chars up to 2 GB
 RAW - 2000 bytes of Information. Raw data. Cannot be edited or Updated, ex.
Scanned image.

ORACLE 8.0 Data types


 Internal LOB
o BLOB – Binary Large Object
o CLOB – Character Large Object
o NCLOB –NonCharacter Large Object
 External LOB
o BFILE – Binary File
o BFILENAME( ) – Function to invoke Bfile
CONSTRAINTS :
 Unique :
o Specifies that all values in a column must be unique. Values in field
cannot be duplicated.
o More than one Null value can be inserted in the column.
o Unique constraint can be placed on multiple columns.

 Null/Not Null :
o Null specifies that the column may contain value or may not contain any.
o By default all column in a table allow Null values.
o Not Null specifies that all rows in a table must have value for specified
column. All NOT NULL columns are mandatory.
o NULL should be however specified for numeric fields, as any arithmetic
with NULL results in a NULL value.

 Check :
o Specifies a condition which must be true for the data being inserted into the
table. A single column can have multiple checks.
o Check involving multiple columns is given as table level check constraint.

 Primary Key :
o Refers to one or more column values in a table that can uniquely identify
each row in a table.
o A table can have only ONE Primary key.
o Primary Key can be made up of one column or more than one column.
When a primary key is made up of more than one column, then the Key is
called Composite Primary key. ‘
o A primary key column cannot contain nulls and is unique by default.

 Foreign Key :
o A Foreign Key is one or more columns with values based on the Primary
key values from another table.
o A foreign key constraint specifies that the values stored in foreign key
column correspond to values of the primary key in other table.
o Foreign key constraint is also known as referential Integrity constraint.
o The table containing foreign key is known as Dependent table (Master
Table) and the table that is referenced by foreign key is called Referenced
table (Detail Table)

 Default :
o Specifies a value to be assigned to the column if a subsequent INSERT
statement omits a value for the column. The datatypes of the expression
must match the datatype of the column.

CREATING A TABLE
Tables are fundamental storage object of the Oracle database.

Tables consist of rows and columns. A single table can have maximum of 1000 columns.

Syntax :
Create Table [Schema] table_name (
Column datatype [column constraint],
……………..,
[table constraint]);

Key words used in the above syntax are :

Schema : Is the schema(workspace) to contain the table. If it is omitted, Oracle creates


the table in creator’s own schema.

Table_name : Is the name of the table to be created. Table name and column name can
be 1 to 30 characters long.
The character must be alphabetic, but name may include letters, numbers and
underscores.
The table name cannot be the name of another object owned by same user and cannot be
reserved word.

Column : Specifies the name of a column of the table. The number of column in a table
can range from 1 to 1000. This was limited to 254 columns in the last version of Oracle.

datatype : Is the datatype of a column. Specifies the type and width of data to be stored
in the column.

column_constraint : Defines an integrity constraint as part of the column definition

Table_constraint : defines an integrity constraint as part of table definition.


Example : Master table

CREATE TABLE dept1(


Dno VARCHAR2(10) constraint pk PRIMARY KEY, /* column
constraint */
Dname VARCHAR2(15),
CONSTRAINT dno_ck
CHECK (dno like ‘D%’)); /* table constraint */

Example : Detail table

CREATE TABLE employee1(


Ename VARCHAR2(15),
Eno NUMBER(4) PRIMARY KEY,
Sal NUMBER(7,2) CHECK (sal between 2000 and 10000),
doj DATE,
comm NUMBER(4,2) DEFAULT 10.5,
dno VARCHAR2(10) REFERENCES dept1(dno) /* foreign key */
ON DELETE CASCADE);

If more than one constraint is to be specified to a single column, then it can be declared
as a table constraint.
REFERENCES Keyword specifies a foreign key in the detail table.

ON DELETE CASCADE deletes the corresponding records in the detail table


(employee1) whenever a delete operation is performed on the master table (dept1). If this
clause is not set when creating the table, Oracle does not permit, the deletion of records in
the master table.
INSERTING ROWS IN A TABLE

Insert command is used to add a row of data to the table.

Syntax :
INSERT INTO tablename ([field1, field2 ,….]) VALUES (value1, value2…)

Examples :
 Character and Date values must be enclosed in single quotes and date must be in
default format.

INSERT INTO employee1


VALUES(‘Blake’,1001,5000, ’11-may-1988’,12,10);

 To leave a column empty NULL can be inserted in a column.

INSERT INTO dept1 VALUES(‘D10’,NULL);

 Data need not be inserted in all columns.

INSERT INTO employee1(eno,dno) VALUES(1002,10);

 Columns can be inserted out of order they appear in the table. This does not change
the fundamental order of columns in the table. It simply allows listing of the data
fields in a different order.

INSERT INTO employee1(eno,dno) VALUES(1002,10);

 To insert date in different format, to_date function can be used. TO_date can also be
used to format a time into a date column.

INSERT INTO employee1(doj)


VALUES (to_date(’02/12/1989’),’dd/mm/yyyy’)

INSERT INTO sale(timefld) VALUES (to_date(’13:50’,’HH24:MI’));

ALTERING TABLE :

Oracle allows modification of existing table. Table might be changed in following


ways :
 One of more columns can be added to a table.
 Constraints can be added to a column or dropped from a column.
 Existing table definition, suchas datatype or length may be modified.
 Table may be renamed.
 Table may be deleted.

Adding and Dropping Columns/Constraints


 ALTER TABLE dept
ADD addr varchar2(15);

 ALTER TABLE dept


MODIFY addr varchar2(40);

 ALTER TABLE employee1 ADD CONSTRAINT emp_chk CHECK (eno >100);

 ALTER TABLE emp DROP PRIMARY KEY;

 ALTER TABLE employee1 ADD primary key(num);

 ALTER TABLE dept1 DROP CONSTRAINT dno_ck;

 ALTER TABLE employee1 ADD CONSTRAINT for_key FOREIGN KEY(dno)


REFERENCES dept1(dno);

 ALTER TABLE employee1 ADD CONSTRAINT com_chk CHECK (comm. <


2000)

 ALTER TABLE employee1 DROP COLUMN doj

DELETING FROM A TABLE :

Used to remove rows from a table.


Syntax :
DELETE FROM tablename WHERE condition.

Examples :

 Delete all rows from a table


DELETE FROM employee1;

 Delete rows based on some condition.


DELETE FROM EMPLOYE E1 where sal <2000;

In Oracle every row has a unique ROWID column. Even duplicate records are unique on
Oracle because of ROWID. The ROWID column exists in every row in a database and
no two ROWIDs are same. Duplicate roes can be deleted using the ROWID.

UPDATING A TABLE
Values stored in a table can be updated using the UPDATE statement.
Syntax :
UPDATE tablename SET (field1=value, field2=value ……)
WHERE condition;

Example :
 To Update all rows in a table

UPDATE employee1 SET comm.=11.5;

 TO Update rows based on a condition :

UPDATE employee SET eno=1005 WHERE name=‘Blake’;

CREATING A TABLE FROM ANOTHER TABLE:

A new table can be created from a table using CREATE … SELECT statement.

Example :
CREATE TABLE backup AS
SELECT * FROM dept1;

The new table created can have selected columns from the table from, which it is created.
CREATE TABLE emp_grade AS
SELECT eno, ename Employee_Name, dname
FROM employee1, dept1 where sal>2000;

The new table can have different column names. The above examples shows column
ename in employee1 table is named as Employee_name in the new table emp_grade.

Another way of creating a table with selected columns and column names is
CREATE TABLE emp_grade AS
SELECT eno EMPLOYEE_NO, dept1.dno, dname DEPT_NAME
FROM employee1,dept1

RENAMING A TABLE :

RENAME employee1 TO emp1;

DROPPING A TABLE :

DROP TABLE EMP1;


If some dependent table object exists while dropping table, the Drop command will
generate an error. To over come this CASCADE CONSTRAINT should succeed the
DROP command.

DROP TABLE emp1 CASCADE CONSTRAINT;

CONTROLLING TRANSACTIONS:
When inserting toed in a table, the transactions can be controlled so that user has
option to return the table back to the original status, or to make the changes in the table
permanent so that the changes are available to all.

COMMIT :
Committing a transaction permanently saves the transaction changes to the
database.
Until the commit command is not given, the work done till then can be undone.
Committing transactions makes changes available to other users who otherwise will
continue to get old information.

Until the user performs a commit, transaction is in the following state :


 Data Manipulation Language operations affect only the database buffer, so that they
can be backed out.
 A rollback segment buffer is created in the server.
 The owner can view the changes of the transaction, but the other users of the database
cannot see the effects of the transaction.

Data Definition commands force a commit to occur, without user instructing it to.
Ex. Quit, create table, create view, alter table, drop table, drop view commands perform
implicit commit.

Data Manipulation commands needs to be committed explicitly.

AUTOCOMMIT :
The SQL *Plus autocommit feature can cause changes to be committed after each
SQL command, without user explicitly giving commit command.
The autocommit feature is set OFF by default and can be set ON with the SET
command :

SET autocommit OFF/ON

To check and display the current status of autocommit, SHOW command is used :
SHOW autocommit;
ROLLBACK:
This command undoes all changes since the beginning of the current transaction
using the corresponding rollback segment.
This command can be used to manually undo the work done by an in-doubt distributed
transaction.

In case of server failure with host computer or application program, Oracle performs an
implicit rollback.

SELECT ….

Syntax
SELECT column(s) FROM tablename
WHERE condition;
Examples
To display all the columns of a table :

SELECT * FROM dept1;

 To display selected columns of a table :

SELECT eno, ename, sal FROM employee1;

 To display records based on a condition :

SELECT * FROM employee1 WHERE eno=1001;

 To Eliminate display duplicate values in a table

SELECT DISTINCT(dno) FROM employee1;

Querying based on a Character column

SELECT * FROM employee1 WHERE ename LIKE ‘B%’;

SELECT * FROM employee1 WHERE ename LIKE ‘_l%’;

 Displaying query result in sentence format, Using Concatenation Operator ( ||)

SELECT ename ||’is earning Rs. ‘ || sal from empoyee1;

 Column Alias – Rename a column in display.

SELECT dno Department_No, eno FROM employee1;


ARRANGING DATA :
Data displayed in the select clause is normally nor arranged in any sequence. To sort the
data in a table the following statement is used

SELECT * FROM employee1 ORDER BY eno;

By default data is stored in ascending order. To Change the order

SELECT * FROM employee1 ORDER BY sal DESC

To order on multiple columns :

SELECT * FROM EMPLOYEE ORDER BY sal ASC, comm, DESC

Using & - the substitution variable : Used to fetch data or value at the time of execution

SELECT * FROM employee1 WHERE dno=-‘&dno’;

SELECT * FROM employee WHERR sal>=&sal;

Concatenation Operator (||) : Allows columns to be linked to other column, constant


values or arithmetic expressiona to result in a single character column.

Example :

SELECT ename || ‘s SALARY IS ‘ || sal FROM employee1;

SELECT ename || ’ ‘ || dname FROM employee1, dept1 WHERE


employee1.dno=dept1.dno
LAB EXERCISES.

Exercise 1:
1. Consider the Insurance database given below. The primary keys are
underlined and the data types are specified.
PERSON (driver-id#:String, name : string, address:string)
CAR (Regno:String, model:string, year:int)
ACCIDENT (Report-Number:int, date: date, location:string)
OWNS (driver-id#:string, Regno:String)
PARTICIPATED (driver-id#:string, regno:string,report-number:int,
damageamount:int)

1. Create the above tables by properly specifying the primary keys and the foreign
keys.
2. Enter atleast five tuples for each relation.
3. Demonstrate how you
a. Update the damage amount for the car with a specific Regno in the accident
with report number 12 to 25000.
b. Add a new accident to the database
4. Find the total number of people who owned cars that were involved in accidents in
2008.
5. Find the number of accidents in which cars belonging to a specific model were
involved.
6. Generate suitable reports.
7. Create suitable front ends for querying and displaying the results.

Solution :

1. To create the tables for the above database we have the statements –

create table person(driver_id varchar2(5) primary key,


name varchar2(8), address varchar2(10));
create table car(regno varchar2(5) primary key, model varchar2(6), year date);
create table accident(report_no number(4) primary key, date1 date,
location varchar2(25));
create table owns(driver_id varchar2(5) references person(driver_id),
regno varchar2(5) references car(regno),
primary key(driver_id, regno));
create table participated(driver_id varchar2(5) references person,
regno varchar2(5) references car,
report_no number(4) references accident,
damageamount number(10)
primary key(driver_id, regno, report_no));

2. To insert the tuples into the relations –


To insert direct values into the table we have –
insert into person values(‘D101’,’Aishwarya’,’Bollywood’);
To do multiple insertions -
insert into person values(‘&driver_id’,’&name’,’&address’);
Output :
Enter value for driver_id: D101
Enter value for name: Aishwarya
Enter value for address: Bollywood

For the next entry just press /


insert into car values(‘&regno’,’&model’,’&year’);
insert into accident values(&report_no,’&date1’,’&location’);
insert into owns values(‘&driver_id’,’&regno’);
insert into participated values
(‘&driver_id’,’&regno’,&report_no,damageamount);

Note:-
 The values entered into the owns and participated relations should already
be present in their respective referenced tables.

 The values entered should be appropriate to reflect the outputs produced


by the subsequent queries

Ex:

Values of PERSON table:

DRIVERID NAME ADDRESS

10 AVINASH BANGALORE
20 BOBBY BOMBAY
30 CLEO DELHI
40 DARYL CALCUTTA
50 ETON PUNE

Values of CAR table:

REGNO MODEL YEAR

100 ILO 2004


200 ZEN 2004
300 COROLLA 2004
400 M800 2005
500 ELANTRA 2005
900 M800 2007
Values of ACCIDENT table:

REPORT NO ACC DATE LOCATION

1 01-FEB-04 BANGALORE
2 02-FEB-02 BANGALORE
3 03-FEB-04 BOMBAY
12 01-FEB-04 BANGALORE
4 02-FEB-02 DELHI

Values of OWNS table:

DRIVERID REGNO

10 200
20 100
30 300
40 400
50 500
20 600

Values of PARTICIPATED table:

DRIVERID REGNO REPORTNO DAMAGE_AMT

40 400 1 1000
20 100 2 2000
40 400 3 5000
50 500 12 15000
40 400 4 15000

3 a) update participated set damageamount = 25000 where report_no = 12;

OUTPUT: One row updated


DRIVERID REGNO REPORTNO DAMAGE_AMT

50 500 12 25000

b) insert into accident values(15,’12-jan-2004’,’mysore road’);

OUTPUT: One row created


REPORT NO ACC DATE LOCATION

15 12-jan-2004 mysore road


4 select count(o.driver_id) from participated p, owns o, accident a, where
p.report_no = a.report_no and o.regno =p.regno and to_char(a.date1,’yyyy’)=
2002.

OUTPUT: ACCIDENTS IN 2002: 2

5. select count(report_no) from participated p car c where p.regno = c.regno


and c.model = ‘M800’;.

OUTPUT: TOTAL_CARS_M800: 3

6. ttitle center “Insurance” skip 3


btitle ‘created by rvce’
enter the required query.
Ex: select count(o.driver_id) from participated p, owns o, accident a, where
p.report_no = a.report_no and o.regno =p.regno and to_char(a.date1,’yyyy’)=
2002.

7. Procedure for connecting front end and back end:

1. Go to control panel , select administrative tools and in that select


data source(ODBC).
2. click on user DSN, then click on Add, then select a driver Microsoft ODBC
for oracle and then finish
A window will appear asking for the:
Data Source Name: eg: Ram
User name : eg: mca01
Server : ora9i
Click on OK, this completes the creation of User DSN.
3. Now open Microsoft Visual Basic. A window will appear asking for the type
of New Project. Click on standard EXE and then Open button.
4. A form appears on the screen and a list of tool box option on the left side of
Screen appears.
5. For any database , select label from toolbox (A) . Drag it on the form to
Appropriate dimensions; now list of operations that can be performed
on the form are:

a) Labels: used for heading eg: Insurance database or in PERSON table


eg: Name , driverid etc
From the properties , change the caption as appropriate.

b) Text bar: used to display the contents of the tables in the database.
Enter the data source as adodc that appears automatically when you click
On data source. Enter the data field.
c) Before changing textbox properties , click on Project option of menu bar
and then select components.
Select controls – Microsoft ADO Data control 6.0 & click on ok. Now select
Adodc option from toolbox. Drag it to form. Right click to go properties.

General – Enter ODBC data source name.


Authentication – User name & password.
Record set – set command type to 2-ad cmd to table, set table.

d) Command – select command button from toolbox and drag it to form.


Various commands:
Code:
i) Insert – Adodc1.Recordset.Addnew
ii) Delete- Adodc1.Recordset .Delete
iii) Update- Adodc1.Recordset. Update.
iv) Move Next – Adodc1. Recordset. Movenext
v) Move Previous – Adodc1. Recordset.Mooveprevious.

Press F5 to execute(run) the database.

PROCEDURE FOR REPORT GENERATION IN VISUAL BASIC:

1. Go to Project option on menu bar and select components click on Designers.


Select Data Environment & Data Report. Click on ok.
2. Again go to Project option and select Add Data Environment click on connection1
(right click) & then Properties. Select Microsoft OLEDB provider for ODBC
drivers and then click next.
3. Enter Data Source Name. Enter username and password click on Test Connections
Connection succeeds .press ok.
4. Again right click on connection1, select Add command right click on command
and then properties. Add sql statement and click on ok.
5. click on Project, add Data report. A report window will appear.
6. change the report properties
Data Source: Data Environment1
Data Member: command1.
7. Then add report labels from toolbox to the report header as many as desired.
Then add report textbox from toolbox to the detail section of report. Change
their properties . data member to command1 & Data field to label.
8. Finally add a command button with code as Data Report1.
Show . Execute f5 and press this command to view report.

Ex: 1) in the main menu , for the command button ‘TABLE’ corresponding
to the person table, the sql statement will be SELECT * from PERSON.

The report generated will be entire table as shown


2) For the various queries , click on the particular query and the report
Will be generated. For each query the corresponding SQL statement
needs to be set.

Exercise 2:

2. Consider the following relations for an order processing database application in a


company.
CUSTOMER (cust: int, cname: String, City: String)
ORDER (order: int, odate: date, cust#: int, ord-Amt:int)
ITEM (item: int, unitprice: int)
ORDER-ITEM (order#: int, Item#: Int, Qty: int)
WAREHOUSE (warehouse: int, city: String)
SHIPMENT (order# int, warehouse#: int, ship-date: date)

i. Create the above tables by properly specifying the primary keys and the
foreign keys.
ii. Enter atleast five tuples for each relation.
iii. Produce a listing : CUSTNAME, #oforders, AVG_ORDER_AMT, where the
middle column is the total numbers of orders by the customer and the last
column is the average order amount for that customer.
iv. List order# for orders that were shipped for all the warehouses that the
company has in a specific city.
v. Demonstrate how you delete item# 10 from the ITEM table and make that field
null in the ORDER_ITEM table.
vi. Generate suitable reports.
vii. Create suitable front ends for querying and displaying the results.

Note:-
 ORDER is a reserve word – while creating the table create it in other name like
ordertab and the field in name orderno instead.
 To implement the last part of the question while creating the item field in the
order_item table give the constraint ON DELETE SET NULL.

Ex:

VALUES OF CUSTOMER TABLE:

CUST CNAME CITY

1 ASHOK DELHI
2 KARAN BANGALORE
3 ROHIT DELHI
4 ROHAN MUMBAI
5 GURU GOA
6 AVIK DELHI
7 BHARAT DELHI
8 ANUJ DELHI
9 LAKSHMI BANGALORE
10 PRASAD BANGALORE

VALUES OF ORDER TABLE:

ORDER ODATE CUST ORDER_AMT

20 25-FEB-05 1 2000
30 15-DEC-06 3 30000
40 13-APR-05 3 25000
50 11-NOV-04 4 23000
10 6-MAY-08 1 10899
60 25-FEB-04 6 2000
70 15-DEC-03 8 30000
80 13-APR-04 8 25000
90 11-NOV-03 9 23000
100 6-MAY-07 6 19899

VALUES OF ITEM TABLE:

ITEM UNIT PRICE

5 1000
10 1500
20 2300
25 500
30 876
40 1300

VALUES OF ORDER_ITEM TABLE:

ORDER ITEM QTY

20 5 5
20 10 3
30 20 2
40 30 7
50 30 9

VALUES OF WAREHOUSE TABLE:


WAREHOUSE CITY

1 BANGALORE
2 GOA
3 UP
4 BIHAR
5 GOA
6 DELHI
7 DELHI
8 DELHI

VALUES OF SHIPMENT TABLE:

ORDER WAREHOUSE SHIPDATE

20 1 28-FEB-05
30 4 25-DEC-06
50 4 28-FEB-05
30 3 27-FEB-05
10 1 16-MAY-08
50 5 11-NOV-04

Queries :

iii. select cname cust_name, count(*) tot_ord, avg(order_amt) avg_ord_amt from


customer c, c order o where c.cust_no=o.cust_no group by cname;

OUTPUT: EX:

CUSTNAME NO_OF_ORDERS AVG_ORDER_AMT

ANUJ 2 27500
ASHOK 2 10949.5
AVIK 2 10949.5
LAKSHMI 1 23000
…………

iv. select o.order_no from order_item o, shipment s, warehouse w where


o.order_no=s.order_no and s.warehouse_no=w.warehouse_no and w.city=’&city’;

OUTPUT: EX:

CITY=GOA

ORDER

50
v. /*If the constraint ON DELETE SET NULL is NOT given while creating the item
field in the order_item table - then we require to alter table order_item, insert
values and then have to delete constraint.

Create table order_item(order_no number(5) references order(order_no),


item_no number(5) references item(item_no) on delete set Null, qty number(3),
constraint pk primary key(order_no,item_no))

insert values

alter table order_item drop constraint pk;.

vi. ttitle center “ “ skip3


btitle ‘ ‘.
enter the required query.

Exercise 3:

3. Consider the following database of student enrollment in courses and books


adopted for each course.
STUDENT (regno: string, name: string, major: string, bdate: date)
COURSE (course: int, cname: string, dept: String)
ENROLL (regno#: string, course#: int, sem: int, marks: int)
TEXT (book_ISBN: int, book_title: string, publisher: string, author: string)
BOOK_ADOPTION (course#: int, sem: int, book_ISBN#: int)

i. Create the above tables by properly specifying the primary keys and the
foreign keys
ii. Enter atleast five tuples for each relation.
iii. Demonstrate how you add a new text book to the database and make this book
be adopted by some department
iv. Produce a list of text books (include course#, book-ISBN, book_title) in the
alphabetical order for courses offered by the ‘CS’ department that use more
than two books.
v. List any department that has all its adopted books published by a specific
publisher.
vi. Generate suitable reports.
vii. Create suitable front ends for querying and displaying the results.

Create the database and populate with the data as shown below or with similar
data to ensure the proper output for the last queries instead of getting null values:-
select * from course;

COURSE CNAME DEP


1001 3rdsem cse
1002 5thsem cse
1003 3rdsem mca
1004 dca mca
1005 4thsem cse

select * from text;

BOOKISBN BOOKTITLE PUBLISHER AUTHOR


11 dbms harcourt Korth
12 sp mcgraw navathe
13 dbms mcgraw donovon
14 ssm harcourt john

select * from bookadoption;

COURSE SEM BOOKISBN


1001 4 12
1002 3 13
1004 5 14
1001 4 13
1002 3 12

select * from enroll;

REGNO COURSE SEM MARKS


s1001 1001 4 34
s1001 1002 3 56
s1002 1003 5 56

Solution for 3.3


insert into text values(15,'dbms','mcgraw','raghuram');
insert into bookadoption values(1002,5,15);

Solution for 3.4


select distinct(c.course), t.bookisbn,t.booktitle from course c, bookadoption b,
text t where t.bookisbn = b.bookisbn and c.course = b.course and c.dept =
'cse' and
(select count(t.bookisbn) from course c, bookadoption b, text t
where t.bookisbn = b.bookisbn and c.course = b.course and c.dept = 'cse') >= 2
order by t.bookisbn desc;
Solution for 3.5:
select distinct(c.dept) from course c, bookadoption b
where c.course = b.course and
not exists ((select t.bookisbn from text t
where b.bookisbn = t.bookisbn and c.course = b.course) minus
(select bookisbn from text t where publisher like '&publisher'));

Output:-
Enter value for publisher: mcgraw
old 5: (select bookisbn from text t where publisher like '&publisher'))
new 5: (select bookisbn from text t where publisher like 'mcgraw'))

DEP
---
cse

SQL> /
Enter value for publisher: harcourt
old 5: (select bookisbn from text t where publisher like '&publisher'))
new 5: (select bookisbn from text t where publisher like 'harcourt'))

DEP
---
mca

Exercise 4 :

4. The following tables are maintained by a book dealer.


AUTHOR (author-id: int, name: string, city: string, country: string)
PUBLISHER (publisher-id: int, name: string, city: string, country: string)
CATEGORY (category-id: int, description: string)
CATALOG (book-id: int, title: string, author-id#: int, publisher-id#: int,
category-id#: int, Year: int, price: int)
ORDER –DETAILS (order-no: int, book-id#: int, quantity: int)
i. Create the above tables by properly specifying the primary keys and the
foreign keys.
ii. Enter atleast five tuples for each relation.
iii. Give the details of the authors who have two or more books in the catalog and
the price of the books is greater than the average price of the books in the
catalog and the year of publication is after 2000.
iv. Find the author of the book which has maximum sales
v. Demonstrate how you increase the price of books published by a specific
publisher by 10%.
vi. Generate suitable reports.
vii. Create suitable front ends for querying and displaying the results.

Solutions for 4.1 and 4.2

create table author(authorid number(5) primary key,


name varchar2(20), city varchar2(10), country varchar2(10));

create table publisher(publisherid number(5) primary key,


pname varchar2(20),city varchar2(10), country varchar2(10));

create table category(catid number(5) primary key, description varchar2(25))

create table catalog(bookid number(5) primary key, title varchar2(10),


authorid number(5) references author, publisherid number(5) references publisher,
catid number(5) references category, year number(4), price number(7,2));

create table orderdetails(orderno number(5) primary key, bookid number(5)


references catalog,
quantity number(3));

select * from author;

AUTHORID NAME CITY COUNTRY


1 beck newyork usa
2 donovon chicago usa
3 korth kansas usa
1001 dharani bangalore india
1002 korth kansas usa
1003 elmasri florida usa
1004 navathe califonia usa
1005 raghuram pune india

select * from publisher

PUBLISHERID PNAME CITY COUNTRY

11 mcgraw kansas usa


12 tata chicago usa

select * from catalog;


BOOKID TITLE AUTHORID PUBLISHERID CATID YEAR PRICE
--------- ---------- --------- ----------- --------- --------- ---------
1111 sp 1 11 111 2001 200
1112 ssm 2 12 112 2001 150
1113 sp 1 12 112 2001 175
1114 ssm 2 12 111 2002 233

select * from category;

CATID DESCRIPTION
--------- -------------------------
111 Text book
112 nice book
113 thing of value

select * from orderdetails;

ORDERNO BOOKID QUANTITY


11111 1111 32
11113 1112 32
11114 1114 43
11115 1113 34

Solution for 4.3


SQL> select * from author where
authorid in (select c.authorid from catalog c
where (select count(authorid) from catalog) >=2
and c.price>(select avg(price) from catalog)
and c.year>=2000
group by c.authorid);

or

select name from author where authorid in


(select authorid from catalog c, orderdetails o where c.bookid=o.bookid
where o.qty = (select max(qty from orderdetails)));

Solution for 4.4


SQL> select name from author where authorid in
(select authorid from catalog c, orderdetails o where c.bookid=o.bookid
and o.quantity = (select max(quantity) from orderdetails));
NAME
--------------------
donovon

Solution for 4.5

1. select * from publisher;

2. select * from catalog;

3. update catalog set price = price*1.1 where publisherid=12;

4. select * from catalog;

BOOKID TITLE AUTHORID PUBLISHERID CATID YEAR PRICE


--------- ---------- --------- ----------- --------- --------- ---------
1111 sp 1 11 111 2001 220
1112 ssm 2 12 112 2001 150
1113 sp 1 12 112 2001 175
1114 ssm 2 12 111 2002 233

Exercise 5 :

Consider the following database for a banking enterprise


BRANCH (branch-name: string, branch-city: string, assets: real)
ACCOUNT (accno: int, branch-name: string, balance: real)
DEPOSITOR(customer-name:string, accno:int)
CUSTOMER(customer-name: string, customer-street: string,
customer-city: string)
LOAN (loan-number: int, branch-name: string, amount: real)
BORROWER (customer-name: string, loan-number: int)

i. Create the above tables by properly specifying the primary keys and the
foreign keys.
ii. Enter atleast five tuples for each relation.
iii. Find all the customers who have atleast two accounts at the Main branch
iv. Find all the customers who have an account all the braches located in a specific
city.
v. Demonstrate how you delete all account tuples at every branch located in a
specific city.
vi. Generate suitable reports.
vii. Create suitable front ends for querying and displaying the results.
Solution for 5.1 and 5.2

create table branch(bname varchar2(10) primary key,


bcity varchar2(15),
assets number(12,2);

create table account(accno number(5) primary key,


bname varchar2(10) references branch.
balance number(12,2));

create table customer5(cname varchar2(10) primary key,


cstreet varchar2(15),
ccity varchar2(15));

create table depositor(cname varchar2(10) references customer5,


accno number(5) references account on delete cascade);

create table l(lnumber number(5) primary key,


bname varchar2(10) references branch,
amt number(9,2));

create table borrower(cname varchar2(10) references customer5,


lnumber number(5) references l);

insert into branch values('&bname','&bcity',&assets);


/* do the insert statements for the above created tables */

Solution for 5.3

select cname from depositor d, account a where d.accno = a.accno and bname = 'gstreet'
group by cname having count(d.accno)>=2;

Solution for 5.4


select distinct cname from depositor where not exists
(select bname from branch where bcity = 'delhi')
minus (select a.bname from account a,depositor d where a.accno = d.accno);

Solution for 5.5


delete account where bname in (select bname from branch where bcity='bangalore');
DESIGN FRONT-END USING VISUAL BASIC/VISUAL AGE FOR JAVA:

o Create Suitable front-end to enter data, query the required information for the
exercise in Lab Session-2. The given exercise should be shown as a small
application by including as many queries as possible.

o Create Suitable front-end to enter data, query the required information for the
exercise in Lab Session-3. The given exercise should be shown as a small
application by including as many queries as possible.

o Create Suitable front-end to enter data, query the required information for the
exercise in Lab Session-4. The given exercise should be shown as a small
application by including as many queries as possible.

o Create Suitable front-end to enter data, query the required information for the
exercise in Lab Session-5. The given exercise should be shown as a small
application by including as many queries as possible.

o Create Suitable front-end to enter data, query the required information for the
exercise in Lab Session-6. The given exercise should be shown as a small
application by including as many queries as possible.
VIVA QUESTIONS : DBMS LAB

1. What are the components of Physical database structure of


Oracle Database?
2. What are the components of Logical database structure of
ORACLE database?
3. What is a Table space?
4. What is SYSTEM tables pace and When is it Created?
5. Explain the relationship among Database, Tablespace and Data file?
6. What are Schema Objects ?
7. What is Table ?
8. What is a View ?
9. Do View contain Data ?
10. What are the advantages of Views ?
11. What are the type of Synonyms?
12. What are synonyms used for ?
13. What is an Index ?
1. How are Indexes Update ?
2. What are Clusters ?
3. What is cluster Key ?
4. When can Hash Cluster used ?
5. What is Database Link ?
6. What are the types of Database Links ?
7. What is Data Block ?
8. What is a Data File ?
9. What are the Characteristics of Data Files ?
10. What is the function of Redo Log ?
11. What is a Data Dictionary ?
12. Describe the different type of Integrity Constraints supported by ORACLE ?
13. What is difference between UNIQUE constraint and PRIMARY KEY constraint?
14. Describe Referential Integrity ?
15. What constitute an ORACLE Instance ?
16. What is SGA (system global area)?
17. What are the components of SGA ?
18. What is Cursor ?
19. What is PGA (Program Global Area)?
20. What are the two types of Server Configurations ?
21. What is a Parallel Server option in ORACLE ?
22. Name the ORACLE Background Process ?
36.When Does DBWR write to the database ?
23. What is the function of checkpoint(CKPT)?
24. Define Transaction ?
25. What does COMMIT do ?
26. What does ROLLBACK do ?
27. What is SAVE POINT ?
28. What is the function of Optimizer ?
29. What is COST-based approach to optimization ?
30. What are the different types of PL/SQL program units that can be defined and stored
in ORACLE database ?W
31. hat is a Procedure ?
32. What is difference between Procedures and Functions ?
33. What is a Package ?
34. What are the advantages of having a Package ?
35. What is Database Trigger ?
36. What are the uses of Database Trigger ?
37. What are the differences between Database Trigger and Integrity constraints ?
52. What is an Index ? How it is implemented in Oracle Database ?
53. What is a deadlock ? Explain ?
54. What is dictionary cache ?
55. What is meant by redo log buffer ?
56. What is user Account in Oracle database ?
57. How will you enforce security using stored procedures ?
58. What are the roles and user accounts created automatically with the database ?
59. What are roles ? How can we implement roles ?
o What is snapshots ? Differentiate

Вам также может понравиться