SQL Lab Manual
SQL Lab Manual
PROBLEM 1
PROBLEM STATEMENT:
SCHEMA DESCRIPTION:
PERSON CAR
DRIVER_ID NAME ADDRESS
REGNO MODEL YEAR
PARTICIPATION
DRIVER_ID REGNO REPORTNO DAMAGEAMT
ACCIDENT
REPORTNO DATE LOCATION
OWNS
DRIVER_ID REGNO
2
The table PERSON contains the attributes namely driver_id, name & address where
the primary key is driver_id.
The table CAR contains the attributes such as model, year & register number where
the primary key is register number.
The table ACCIDENT contains the attributes such as report number, date &location
where the primary key is report number.
The table OWNS contains the attributes driver id & regno, both the attributes are
foreign key &they together constitute the composite key.
The table PARTICIPATED contains the attributes driver id, regno, report number &
damage amount. Here driver id , regno , report number are foreign keys and they
constitute the composite key
3
TABLE CREATION:
VALUE INSERTION:
Query to update the damage amount for the car with a specific register
number in the accident with report number between 1 & 200.
Query to find the total number of people who owned the cars that were
involved in accidents in 2002.
REPORT:
Query to check if a person with a specific driver_id has met with an accident
in 2003.
SELECT NAME
FROM PERSON P, PARTICIPATED PA, ACCIDENT A
WHERE P.DRIVERID = PA.DRIVERID AND
PA.REPORTNO = A.REPORTNO AND
A.DDATE LIKE'%02';
RESULT:
Output for the query to update the damage amount for the car with a
specific register number in the accident with report number between 1 &
200.
1 row updated
Output for the query to find the total number of people who owned the cars
that were involved in accidents in 2002.
COUNT(P.DRIVERID)
-----------------
2
Output for the query to find the number of accidents in which cars belonging
to a specific model were involved.
COUNT(P.REPORTNO)
-----------------
9
Output for the query to check if a person with a specific driver_id has met
with an accident in 2003.
NAME
----------
ADARSH
1 row selected.
Output for the query to display name of a person & the car he/she owns.
NAME MODEL
---------- ----------
ADARSH SKODA
ANOOP BMW
KIRAN HYUNDAI
ABHISHEK MARUTI
4 rows selected.
10
PROBLEM-2
Consider the following relations for an order processing database application in a company.
i) Create the above tables by properly specifying the primary keys and the foreign keys.
ii) Enter at least five tuples for each relation.
iii) Produce a listing: CUSTNAME, NO_OF_ORDERS, AVG_ORDER_AMT, where
the middle column is the total number of orders by the customer and the last column
is the average order amount for that customer.
iv) List the Order# for the orders that were shipped from 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) Generation of suitable reports.
vii) Create a suitable front end for querying and displaying the results.
11
SCHEMA DESCRIPTION
The following schema describes an Order Processing database of a company. It describes the
following relations: Customer, Order, Order-Item, Item, Shipment and Warehouse.
Customer :
This relation contains necessary information about the customers of the company. It keeps
track of each customer’s I.D.(CID), his/her name (Cname) and the city (City) in which
he/she lives.
ATTRIBUTE TYPE
CID INTEGER
CNAME VARCHAR (10) {String}
CITY VARCHAR (10) {String}
Ordertab :
This relation maintains all the orders that have been placed by the customers of company. It
keeps track of the Order No. (ONO), the date on which the order was placed (Odate), the
I.D. of the customer who placed the order (CID) and the order amount (Ord_Amt).
ATTRIBUTE TYPE
ONO INTEGER
ODATE DATE
CID INTEGER
ORDER_AMT INTEGER
Itemtab:
This relation contains information about each item. It keeps track of the Item No. (INO) and
the unit price (Price).
12
ATTRIBUTE TYPE
INO INTEGER
PRICE INTEGER
Order_item :
This relation contains information about each order that has been placed. It keeps track of the
Order No. (ONO), the Item No. (INO) and the quantity (QTY) of each item.
ATTRIBUTE TYPE
ONO INTEGER
INO INTEGER
QTY INTEGER
Warehouse :
This relation contains information about the warehouses of the company. It keeps track of the
Warehouse No. (WareNo) and the location (City) of each warehouse.
ATTRIBUTE TYPE
WARENO INTEGER
CITY VARCHAR (10) {String}
Shipment :
This relation lists all the bulk consignments of each ordered item. It keeps track of the Order
No. (ONO), the Warehouse No. (WareNo), the date (Ship_Date) on which the consignment
was shipped.
ATTRIBUTE TYPE
ONO INTEGER
WARENO INTEGER
13
SHIP_DATE DATE
I) TABLE CREATION
CUSTOMER:
ORDERTAB:
ITEMTAB:
ORDER_ITEM:
WAREHOUSE:
SHIPMENT:
QUERIES
III)
Algorithm
SQL Query:
IV)
List the Order# for the orders that were shipped from all the warehouses that the company
has in a specific city.
Algorithm:
The warehouse numbers of a specific city can be obtained from the WAREHOUSE
relation. This can then be joined with the SHIPMENT relation on the warehouse
attribute.
SQL Query:
SELECT S.ONO
FROM SHIPMENT S,WAREHOUSE W
WHERE S.WARENO=W.WARENO AND W.CITY='SYD';
17
i) We would like to know the order numbers of all orders placed by customers who belong
to a particular city.
Algorithm:
This can be obtained by first considering the CID’s of all customers in the specified
city from the CUSTOMER relation.
This can then be combined with the ORDERTAB relation on the CID attribute.
SQL QUERY:
SELECT O.ONO
FROM CUSTOMER C,ORDERTAB O
WHERE C.CID=O.CID AND C.CITY='SYD';
ii) We would like to know the details of all orders that the company has
received.
Algorithm:
SQL Query:
SELECT *
FROM ORDERTAB;
18
RESULT
INO PRICE
----- ----------
10 2000
20 3000
30 2500
40 3500
50 1500
4000 40 10
5000 50 5
WARENO CITY
-------------- -------
15 SYD
25 SYD
35 BOM
45 BOM
55 DEL
QUERY RESULTS:
iii)
iv)
SELECT S.ONO
FROM SHIPMENT S,WAREHOUSE W
WHERE S.WARENO=W.WARENO AND W.CITY='SYD';
ONO
-------
1000
2000
REPORT RESULTS:
i) We would like to know the order numbers of all orders placed by customers who
belong to a particular city.
SELECT O.ONO
FROM CUSTOMER C,ORDERTAB O
WHERE C.CID=O.CID AND C.CITY='BAN';
ONO
-------
1000
3000
ii) We would like to know the details of all orders that the company has received.
SELECT *
FROM ORDERTAB;
PROBLEM 3
CONSIDER THE FOLLOWING DATABASE OF STUDENT ENROLLEMENT
IN COURSES AND BOOKS ADOPTED FOR EACH COURSE .
TABLE STUDENT
BDATE is of datatype date .It is a SECONDARY KEY which can be NULL. It gives the
BIRTH DATE of the specified student .
TABLE COURSE
COURSE is of datatype int .It is the PRIMARY KEY which is NOT NULL.It is the
COURSE NUMBER of each subject.
TABLE ENROLL
REG_NO is of datatype CHAR of length 10.It is a FOREIGN KEY that references the
table STUDENT which on delete cascades.
SEM is of datatype INT. It is a SECONDARY KEY which can be NULL.It gives the
SEMISTER of that student.
TABLE TEXT
TABLE BOOK_ADOPTION
SEM is of datatype INT. It is a SECONDARY KEY which can be NULL.It gives the
SEMISTER of the student who has borrowed the book.
BOOK_ISBN is of datatype INT.It is a FOREIGN KEY that references the table TEXT
which on delete cascades.
TABLE CREATION:
QUERIES
(i)
Demonstrate how you add a new text book to the database and make this book
be adopted by some department
Query
Explanation
INSERT can be used to add a single tuple to a relation. Thus a information about
a new text book can be added to the TEXT entity using INSERT command. The new text
book can be made to be adopted by some department using INSERT. The values which
are added to the BOOK_ADOPTION contains COURSENO and SEM of the department
and semester which has uses the textbook, along with the BOOK_ISBN of the textbook
through which other information of the textbook can be obtained.
(ii) Produce a list of textbooks in the alphabetic order for courses offered by the
‘CS’ department that use more than two books
Query
GROUP BY COURSENO
HAVING COUNT(COURSENO)>2)
ORDER BY BOOK_TITLE
Explanation
The first nested query selects the Departments which use more than two books.
To select the departments EXIST function is used to check whether there are any
department which use more than two books. In the outer query, we select the courseno,
book_isbn and book_title of the textbooks for courses offered by the ‘CS’ department.
In the outer query, the join condition C.COURSENO= BA.COURSENO relates the
COURSE and BOOK_ADOPTION and the condition DEPT= ‘CS’ is a selection
condition. ORDER-BY clause is used to order the tuples in the result of query according
to the BOOK_TITLE
(iii) List any department that has all its adopted books published by a specific
Publisher.
Query
Explanation
of the nested query. The department name and the publisher whose books have been
adopted by the department are projected from the entities mentioned in the FROM clause
which are joined using the join conditions given in the WHERE clause.
RESULT
GENERATION OF REPORTS
SELECT COUNT(REGNO),C.COURSENO
FROM COURSE C,STUDENT S,ENROLL E
WHERE E.REGNO=S.REGNO AND C.COURSENO=E.COURSENO
GROUP BY COURSENO
Explanation
In the above query entities COURSE,STUDENT, ENROLL are joined using the
join condition E.REGNO=S.REGNO which relates ENROLL and STUDENT and the
join condition C.COURSENO=E.COURSENO which relates ENROLL and COURSE.
The number of students are calculated using COUNT operation.
SELECT S.REGNO,S.NAME
FROM STUDENT S,ENROLL E,COURSE C
WHERE S.REGNO=E.REGNO AND
E.COURSENO=C.COURSENO
In the above query entities COURSE,STUDENT, ENROLL are joined using the join
condition E.REGNO=S.REGNO which relates ENROLL and STUDENT and the join
condition C.COURSENO=E.COURSENO which relates ENROLL and COURSE. The
REGNO and NAME is selected to see name and usn of the students of the specific
course .
31
PROGRAM -4
Consider the following relations for the details maintained by a book dealer.
viii) Create the above tables by properly specifying the primary keys and the foreign keys.
ix) Enter at least five tuples for each relation.
x) Give the details of the authors who have 2 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.
xi) Find the author of the book which has maximum sales.
xii) Demonstrate how you increase the price of books published by a specific publisher by
10%.
xiii) Generation of suitable reports.
xiv) Create a suitable front end for querying and displaying the results.
32
SCHEMA DESCRIPTION
The following schema describes a database maintained by a Book-Dealer. It describes the
following relations: Author, Publisher, Catalog, Category, Order-Details.
Author:
This relation contains necessary information about the authors. It keeps track of each author’s
I.D.(AID), his/her name (ANAME) , the city (ACITY) in which
he/she lives, and the country (ACOUNTRY) to which he/she belongs.
ATTRIBUTE TYPE
AUTHOR_ID INTEGER
ANAME VARCHAR (10) {String}
ACITY VARCHAR (10) {String}
ACOUNTRY VARCHAR(10) {String}
Publisher:
This relation maintains all the details of the publisher. It contains the publisher-id (PID),
name of the publisher (PNAME), the city in which the publisher lives (PCITY) and the
country in which the publisher lives (PCOUNTRY).
ATTRIBUTE TYPE
PID INTEGER
PNAME VARCHAR (10) {String}
PCITY VARCHAR (10) {String}
PCOUNTRY VARCHAR (10) {String}
Category:
This relation category contains the category-i.d (CID) along with the description for all the
books (DESCR).
ATTRIBUTE TYPE
CID INTEGER
DESCR VARCHAR (10) {String}
Catalog :
This relation contains information about all the books i.e. book-id (BID), title (BTITLE),
along with the details of the author of the respective books i.e. author-Id (AID), publisher
(PID) and other details of the books such as category-id (CID), ,price (PRICE), and year
(YEAR).
ATTRIBUTE TYPE
BID INTEGER
BTITLE VARCHAR (10) {String}
AID INTEGER
PID INTEGER
CID INTEGER
PRICE INTEGER
YEAR INTEGER
Order-Details :
This relation contains information about all the orders that have been placed i.e. Order-No
(ONO), book-id (BID) and the quantity (QTY).
ATTRIBUTE TYPE
ONO INTEGER
BID INTEGER
QTY INTEGER
34
TABLE CREATION:
1.
create table author(
2 author_id int primary key,
3 author_name varchar(15)
4 ,city varchar(15),
5 country varchar(15));
Table created.
2.
create table publisher(
2 publisher_id int primary key,
3 publisher_name varchar(15),
4 city varchar(15),
5 country varchar(15));
Table created.
3.
create table category(
2 category_id int primary key,
3 description varchar(15));
Table created.
4.
create table catalog(
2 book_id int primary key,
3 tittle varchar(15),author_id int,p_id int,c_id int,
4 year int,price int,
5 foreign key(author_id) references author(author_id),
6 foreign key(p_id) references publisher(publisher_id),
7 foreign key(c_id) references category(category_id));
Table created.
5.
create table order_details(
2 order_no int primary key,
3 book_id int,
35
4 quantity int,
5 foreign key(book_id) references catalog(book_id));
Table created.
This query gives details of the authors who have 2 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.
SQL COMMAND
ALGORITHM
Step2: select author id from catalog whose book(s) price is greater than the
price retrieved from step1.
Step3: select author id,author name,city and count of books from author,
catalog and rename them as AI,NAM,city,CNT respectively where author id
in author relation is equal to author id in catalog relation and the year of
publication is after 2000 and that author id exists in the set retrieved from
step2 and group the result based on author id ,author name and city having
the count of books greater than or equal to 2.
QUERY IV
SQL COMMAND
having sum(od.quantity)>=all(
select sum(quantity)
from order_details
group by b_id ) );
ALGORITHM
Step 1: Select sum of quantity of sales of each book based on book id (i.e. group
based on book id) from order_details relation.
Step 2: In turn select the book id and the quantity of sale of the book from the
order_details relation, which exists in the result of step1 and is the greatest among
them.
QUERY V
This query demonstrates how to increase the price of the books published by a specific
publisher by 10%.
SQL COMMAND
ALGORITHM
Step 1: select the books whose publisher name is ‘aaa’ from publisher.
Step 2: select the tuples from catalog whose publisher id is same as that of in the step1
result.
Step 3: Increase the price of all the books in the result of step 2 by 10%.
Step 4: Retrieve the publisher’s id, name and new price of the books from the result of
step3.
(Note: In the above nested queries the inner one gets evaluated first).
REPORT
In this project we are mainly dealing with maintenance of books by a book dealer. This
schema mainly includes relations like author, publisher,
Demonstration on how to retrieve the details of the authors who have 2 or more
books in the catalog and their price is greater than the average price of all books
in the catalog and the year of publication is after 2000.
The SQL reports generation code for these queries are as follows,
QUERY III
QUERY IV
QUERY V
select a.author_id,a.name,
c.title,cat.description,c.book_id,c.year,c.price
from author a,catlog c,category cat
where a.author_id=c.a_id and cat.category_id=c.c_id
ORDER BY c.a_id;
clear computes
clear columns
clear breaks
ttitle off
btitle off
btitle off
RESULT
5 rows selected.
5 rows selected.
888 50 8
666 60 1
6 rows selected.
6 rows selected.
CAT_ID DSCR
---------- --------------------
100 aaa
200 bbb
300 ccc
400 eee
500 ddd
5 rows selected.
43
This is the result of query iii executed using the procedure as shown in the
report. It gives the details of the author who has 2 books in the catalog and
their price is greater than all the books in the catalog and the year of
publication is after 2000.
QUERY III
This is the result of query iv executed using the procedure as shown in the
report. It gives the author name who has maximum sales.
QUERY IV
NAME
--------------------
o-broien
This is the result of query v executed using the procedure as shown in the
report. it gives the publisher id ,name and the new price of the books which is increased
by 10% published by ‘aaa’;
QUERY V
PUBLISHER REPORT
PUBLISHER REPORT
PUBLISHER REPORT
PROJECT – V
Consider the following database for a banking enterprise
(i) Create the above tables by properly specifying the primary keys
and the foreign keys.
(iii) Find all the customers who atleast two accounts at the MAIN
branch.
(iv) Find all the customers who have an account at all branches
located in a specific city.
(v) Demonstrate how you delete all account tuples at every branch
located in a specific city.
(vii) Create suitable front end for querying and displaying the results.
46
SCHEMA DESCRIPTION
This database is created for a banking enterprise. This database keeps an account of
all the branches in a particular city, information about the customer like details of the
customer, in which branch his account exists and details of loan taken from the
customer(if any).
Since a customer can have more than one account and accno can be same in
different branches we consider both the attributes as the primary key.
Table name: LOAN
This table gives the details of the loan sanctioned in the branches.
loan_number: This gives the loan number. No two loan numbers can be same,
therefore it is considered as the primary key.
branch_name: It gives the name of the branch in which the account is existing.
This attribute refers the BRANCH table to get the name of the branch, hence
it is considered to be the foreign key.
amount: This attribute gives the amount for which the loan is sanctioned.
QUERIES
STATEMENT: Find all the customers who have at least two accounts at the Main
branch.
EXPLANATION:
The above query is similar to a SELECT-JOIN-PROJECT sequence of
relational algebra operations and such queries are called select-join queries. In the where
clause, b_name = ‘MAIN’ specifies the selection condition and accno = actno is a join
condition for the join operation on the two relations account and depositor. Then the
group by clause is used to sub-group the tuples based on the grouping attributes b_name
and cust_name. The having clause provides a condition count (*) >= 2 on the groups of
tuples. Only the groups that satisfy the condition are retrieved in the result of the query.
RESULT:
b_name cust_name count (*)
MAIN TOM 2
The result of the query is as shown above. It selects only the customers who have two or
more accounts in the MAIN branch.
STATEMENT: Find all the customers who have an account at all the branches located
in a specific city.
from branch
where branch_city = ‘Bangalore’)
group by accno, cust_name
EXPLANATION:
The nested query selects the tuples that satisfy the selection condition
branch_city = ‘Bangalore’ from the relation branch. In the outer query, a join operation is
performed on the relations account and depositor with the join condition as accno=actno.
Further the IN operator compares the tuples selected from account and depositor with the
set of union-compatible tuples produced from the nested query for the value b_name. The
outer query also uses a group by clause to group the tuples based on the grouping
attributes accno, cust_name.
RESULT:
accno cust_name
456 Eliza
As demonstrated by the result, the above query selects the customers who have account at
all the branches located in the city ‘Bangalore’.
STATEMENT: Demonstrate how you delete all account tuples at every branch located
in a specific city.
QUERY: delete
from account
where b_name in ( select branch_name
from branch
where branch_city = ‘Sydney’)
EXPLANATION:
The nested query selects the tuples that satisfy the selection condition
branch_city = ‘Sydney’ from the relation branch .The IN operator compares the subtuple
of value b_name for each tuple in account relation with the tuples produced by the nested
query. Finally, the selected tuples are deleted from the account relation.
RESULT:
The above query deletes all the account tuples for every branch located
in the city ‘Sydney’.
52
GENERATION OF REPORT
1.Display the names of all the customer who have taken loan , count of the number of loans
taken and the total amount taken up each customer.
The above query is used to obtain the names of all the customerswho have taken loan,the
number of they have taken and the total amount of money they have taken. This is done by
using two tables namely BORROWER and LOAN. The names of all the customer is grouped
and the number of loans they have taken is obtained using the count keyword and the total
amount of money taken is obtained by using the sum keyword .
OUTPUT:
2. Find the names of all the customers who have taken the loan in a particular branch.
select b.customer_name
from borrower b, loan l
where l.loan_number=b.loan_number and l.branch=’gandhi bazar’;
EXPLANATION:
The above query selects the names of all the customer who have taken loans in a particular
branch. It performs the action using the two tables LOAN and BORROWER. It compares the
loan_number in both the tables and selects all the common loan_numbers . From this set it
53
selects those for which the corresponding branch value is BANGALORE. The corresponding
customer_names of the loan_numbers selected is the required answer.
OUTPUT:
CUST_NAME
------------------
Aaa
Bbb
Ccc
3. Update the balance for the customer with a given customer name to 10000
update account
set amount=10000
where accno in (select accno from depositor where d.customer_name=’xyz’);
OUTPUT:
2 rows updated
EXPLANATION:
The above query can be performed by using the two tables namely ACCOUNT, and
DEPOSITOR . The accno of the depositors whose names are xyz are selected from depositor
.For all the selected accno the corresponding amount in the account table is updated to 10000.