18
PES Institute Of Technology ( Bangalore South Campus) 1Km beforeElectronic City,HosurRoad,Bangalore-560100. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING V SEMESTER LAB MANUAL SUBJECT: DATABASE APPLICATIONS LAB SUBJECT CODE: 10CSL57 SESSION: JULY 2013 – DECEMBER 2013 PESIT(SOUTH CAMPUS),CSE, Surbhi Agrawal 1

PES Institute Of Technology ( Bangalore South Campus)pesitsouth.pes.edu/pdf/CE/RS/fifthsem/DBMS-Labman… ·  · 2016-05-30PES Institute Of Technology ( Bangalore South Campus)

  • Upload
    haphuc

  • View
    221

  • Download
    0

Embed Size (px)

Citation preview

PES Institute Of Technology ( Bangalore South Campus)

1Km beforeElectronic City,HosurRoad,Bangalore-560100.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

V SEMESTER

LAB MANUAL

SUBJECT: DATABASE APPLICATIONS LAB

SUBJECT CODE: 10CSL57

SESSION: JULY 2013 – DECEMBER 2013

PESIT(SOUTH CAMPUS),CSE, Surbhi Agrawal 1

Data Definition Language (DDL) statements are used to define the database structure or schema.

CREATE - to create objects in the database ALTER - alters the structure ofthe database DROP - delete objects from the database TRUNCATE - remove all records from a table, including all spaces allocatedforthe records are removed COMMENT - add comments to the data dictionary RENAME - rename an object

Data Manipulation Language (DML) statements are used for managing data

withinschema objects.

� SELECT - retrieve data from the a database � INSERT - insert dataintoa table

� UPDATE - updates existingdatawithin a table

� DELETE - deletes all records from a table, the space for the records remain

� MERGE - UPSERT operation (insert orupdate)

� CALL - call a PL/SQLorJava subprogram � EXPLAINPLAN - explain access path to data � LOCK TABLE - controlconcurrency

Creating Tables

To create table we use the CREATE TABLE statement. The usual form of this statementis: CREATE TABLE [IF NOT EXISTS]table_name(column_list)

MySQL supports IF NOT EXISTS after CREATE TABLE statement to prevent you

from error to create table which already exists on the database server, table_name is the

name of table you would like to create, define a set of columns which is usually in

thisform: column_name data_type(size)[NOT NULL].

To create employees table

CREATE TABLE employees (employeeNumber into(11) NOT NULL,

lastName varchar(50) NOT NULL, firstName varchar(50) NOT NULL,

extension varchar(10) NOT NULL, email varchar(100) NOT NULL,

officeCode varchar(10) NOT NULL, reportsTo int(11) default NULL,

jobTitle varchar(50) NOT NULL, PRIMARY KEY(employeeNumber));

PESIT(SOUTH CAMPUS),CSE, Surbhi Agrawal 2

The primary key of the table employeeNumber can be specified. If the table has more

than one primarykey, you can separatethem bya comma.

CREATE TABLE payments ( customerNumber int(11) NOT NULL, checkNumber varchar(50) NOT NULL, paymentDate datetime NOT

NULL, amount double NOT NULL,PRIMARY KEY (customerNumber,checkNumber));

. Showing and DescribingTablesin aDatabase

In order to show all tables in a database use SHOW TABLES statement,the server

will returns all tables name of the current selected database. SHOW TABLES

Table characteristicsortable metadata,can be viewed usingDESCRIBE statement

DESCRIBE employees;

Altering Table Structures

MySQL allows to alterexistingtable structureswith a lot ofoptions.

ALTER [IGNORE] TABLE table_name options[, options...] options:

ADD [COLUMN] create_definition [FIRST | AFTER col_name ]

or ADD [COLUMN] (create_definition,create_definition,...) or ADD INDEX [index_name] (index_col_name,...) or ADD PRIMARY KEY (index_col_name,...)

or ADD UNIQUE [index_name] (index_col_name,...) or ADD FULLTEXT[index_name] (index_col_name,...)

or ADD [CONSTRAINT symbol] FOREIGN KEY [index_name]

(index_col_name,...)[reference_definition]

or ALTER [COLUMN] col_name {SET DEFAULT literal | DROPDEFAULT} or CHANGE [COLUMN] old_col_name create_definition [FIRST | AFTER column_name]

or MODIFY [COLUMN] create_definition [FIRST |AFTER col_name] or DROP [COLUMN] col_name

or DROPPRIMARY KEY or DROPINDEX index_name or DISABLE KEYS

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 3

or ENABLE KEYS

or RENAME [TO] new_table_name

or ORDER BY col_name

or table_options � The CHANGE and MODIFY are the same, they allow you to change the definition of the column or its position in the table. � The DROP COLUMN will drop the column of the table permanently, if the table contain data all the data of the column will be lost. � The DROP PRIMARY KEY and DROP INDEX only remove the primary key or index of the column. � The DISABLE and ENABLE KEYS turn off and on updating indexes for MyISAM table only. � The RENAME Clause allows you the change the table name to the new one.

Dropping Tables

To delete table from the database, use DROP TABLE statement: DROP [TEMPORARY] TABLE [IF EXISTS] table_name [, table_name,...] TEMPORARY keyword is used for dropping temporary tables. MySQL allows you to drop multiple table at once by listing them and separated each by a comma. IF EXISTS is used to prevent you from deleting table which does not exist in the database.

Empty Table's Data In some cases, to delete all table data in a fast way and reset all auto increment columns. MySQL provide you TRUNCATE table statement to do so. The statement is in this form:

TRUNCATE TABLE table_name TRUNCATE TABLE statement drop table and recreate it so it is much faster than DELETE TABLE statement but it is not transaction-safe. The number of deleted rows is not return like DELETE TABLE statement.On DELETE triggers are not invoked because TRUNCATE does not use DELETE statement.

SELECTION OF DATA In order to retrieve data from MySQL database server use SELECT statement. SELECT column_name1, column_name2... FROM tables [WHERE conditions] [GROUP BY group [HAVING group_conditions]] [ORDER BY sort_columns PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 4

[LIMIT limits]; The SELECT statement has many option clauses which may or may not be used, the order has to be appear as mentioned above.

To select all columns in a table you can use (*) notation instead of listing all column name

SELECT * FROM employees Example if only first name, last name and job title of all employee has to viewed then the query is, SELECT lastname,firstname,jobtitle FROM employees

WHERE Clause WHERE clause enables to select a particular rows which match its conditions or search criteria. SELECT firstname,lastname,email FROM employees WHERE jobtitle="president"

DISTINCT With DISTINCT keyword, you can eliminate the duplicated result from SELECT statement. For example, to find how many job title of all employee in employees table,use DISTINCT keyword in SELECT statement. SELECT DISTINCT jobTitle FROM employees;

GROUP BY To find number of employee who hold each job, you use GROUP BY clause. GROUP BY clause allows to retrieve rows in group. SELECT count(*), jobTitle FROM employees GROUP BY jobTitle;

HAVING Clause HAVING clause usually use with GROUP BY clause to select a particular of group. For example: SELECT count(*), jobTitle FROM employees GROUP BY jobTitle HAVING count(*) = 1 This query select the job in the company for which we have one employee in each job title. HAVING clause select all group which have count(*) equal 1.

Sorting with ORDER BY The ORDER BY clause allows to sort the result set on one or more column in ascending or descending order. To sort the result set in ascending order use ASC and PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 5

in descending order use DESC keywords. By default, the ORDER BY will sort the result set in ascending order. For example, to sort the name of employee on the first name and job title execute the following query: SELECT firstname,lastname, jobtitle FROM employees ORDER BY firstname

ASC;

Selection using constraints and a list of values SQL IN allows you to select values which match any one of a list of values. The usage of SQL IN is as follows: SELECT column_list FROM table_name WHERE column IN

("list_item1","list_item2"…) The column in WHERE clause does not need to be in column_list you selected, but it has to be a column in the table table_name. If the list has more than one value, each item has to be separated by a comma. In addition, use NOT operator with SQL IN to get values which does not match any value in a list of value. To find out all offices which are located in US and France perform the following query: SELECT officeCode, city, phone FROM offices WHERE country = 'USA' OR country = 'France' In this case, we can use SQL IN instead of the above query: SELECT officeCode, city, phone FROM offices WHERE country IN ('USA','France') To get all countries which does are not located in USA and France, use NOT IN in the where clause as follows: SELECT officeCode, city, phone FROM offices WHERE country NOT IN ('USA','France')

Between clause SQL BETWEEN allows to retrieve values within a specific range. SELECT column_list FROM table_name WHERE column_1 BETWEEN lower_range AND upper_range

MySQL returns all records in which the column_1 value is in the range of lower_range and upper_range as well as the values lower_range and upper_range. The query which is equivalent to SQL BETWEEN to get the same result is SELECT column_list FROM table_name WHERE column_1 >= lower_range AND column_1 <= upper_range In order to find all records which are not in a range use NOT BETWEEN. To find all products that buy price outside the range of 20 and 100 SELECT productCode,ProductName,buyPrice FROM products WHERE buyPrice

NOT BETWEEN 20 AND 100 ORDER BY buyPrice DESC

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 6

Like clause SQL LIKE allows to perform pattern matching in your characters column in a database table. SQL LIKE is often used with SELECT statement in WHERE clause. MySQL provides two wildcard characters for use with LIKE, the percentage % and underscore _. Percentage (%) wildcard allows to match any string of zero or more characters Underscore (_) allows you to match any single character. . To search all employees in employees table who have first name starting with character ‘a’ SELECT employeeNumber, lastName, firstName FROM employees WHERE firstName LIKE 'a%' To search all employees which have last name ended with ‘on’ SELECT employeeNumber, lastName, firstName FROM employees WHERE lastName LIKE '%on' To find all employees whose last name containing ‘on’ SELECT employeeNumber, lastName, firstName FROM employees WHERE lastName LIKE '%on%' To search all employees whose name are such as Tom, Tim… use underscore wildcard SELECT employeeNumber, lastName, firstName FROM employees WHERE firstName LIKE 'T_m' To find all strings which are unmatched with a specific pattern. To search all employees whose last name are not starting with ‘B’ SELECT employeeNumber, lastName, firstName FROM employees WHERE lastName NOT LIKE 'B%'

The information that user needs is not actually stored in the database but we can retrieve it by computing in some ways from stored data. Aggregate functions allow us to perform a calculation on a set of records and return a single returned value. Aggregate functions ignore null value when performing calculation except COUNT function. Aggregate functions are often used with GROUP BY clause of SELECT statement.

SUM Function SUM function returns the sum of all values in an expression. Example to get the total money for each selling product we just use the SUM function and group by product. SELECT productCode,sum(priceEach * quantityOrdered) total FROM orderdetails GROUP by productCode AVG Function

AVG is used to calculate average value of an expression. It ignores NULL values. AVG(expression) We can use AVG function to calculate the average price of all products by executing the following query.SELECT AVG(buyPrice) average_buy_price FROM Products PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 7

MAX and MIN Function MAX function returns the maximum and MIN function returns the minimum value of the set of values in expression. MAX(expression) MIN(expression) MIN and MAX function can be used to retrieve the highest and lowest price product. SELECT MAX(buyPrice) highest_price, MIN(buyPrice) lowest_price FROM Products

COUNT Function Count Function returns the count of the items in expression. COUNT functioncan be used to count the number of products.: SELECT COUNT(*) AS Total FROM products

UPDATE Statement SQL UPDATE statement is used to update existing data in a data table. It can be used to change values of single row, group of rows or even all rows in a table. UPDATE[LOW_PRIORITY][IGNORE]table_name[,table_name...] SETcolumn_name1= expr1[, column_name2=expr2 ...] [WHERE condition]

In MySQL, the data of many tables can be changed at a time. If an UPDATE statement violates an integrity constraint, MySQL does not perform the update and it will return an error message. The SET clause determines the column(s) and the changed values. The changed values could be a constant value expression or even a subquery. WHERE clause determines which rows of the tables will be updated. It is an optional part of SQL UPDATE statement. If WHERE clause is ignored, all rows in the tables will be updated. LOW_ PRIORITY keyword is used to delay the execution until no other client applications reading data from the table. IGNORE keyword is used to execute the update even error(s) can be occurred during execution. Errors could be duplicated value on unique column, or new data does not match with the column data type. In the first situation data are not updated and in the second one MySQL try to convert the data into closest valid values. UPDATE employees SET email = '[email protected]' WHERE employeeNumber = 1 PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 8

1. Consider the following relations: Student (snum: integer, sname: string, major: string, level: string, age: integer) Class (name: string, meets at: string, room: string, fid: integer) Enrolled (snum: integer, cname: string) Faculty (fid: integer, fname: string, deptid: integer) The meaning of these relations is straightforward; for example, Enrolled has one record per student-class pair such that the student is enrolled in the class. Level is a two character code with 4 different values (example: Junior: JR etc).Write the following queries in SQL. No duplicates should be printed in any of the answers. i. Find the names of all Juniors (level = JR) who are enrolled in a class taught by Prof. Harshith ii. Find the names of all classes that either meet in room R128 or have five or more Students enrolled. iii. Find the names of all students who are enrolled in two classes that meet at the same time. iv. Find the names of faculty members who teach in every room in which some class is taught. v. Find the names of faculty members for whom the combined enrollment of the courses that they teach is less than five.

Schema Diagram

Student snum sname major level age

Class

name Meets at room fid

Enrolled

cname

Snum

Faculty

fid fname deptid

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 9

ER Diagram

major level

sname

age Student

snum

Enrolled

Faculty

deptid teaches

Class fid fname

cname fid

room

meetsat

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 10

2. The following relations keep track of airline flight information: Flights (no: integer, from: string, to: string, distance: integer, Departs: time, arrives: time, price: real) Aircraft (aid: integer, aname: string, cruisingrange: integer) Certified (eid: integer, aid: integer) Employees (eid: integer, ename: string, salary: integer) Note that the Employees relation describes pilots and other kinds of employees as well; Every pilot is certified for some aircraft, and only pilots are certified to fly. Write each of the following queries in SQL. i. Find the names of aircraft such that all pilots certified to operate them have salaries more than Rs.80, 000. ii. For each pilot who is certified for more than three aircrafts, find the eid and the maximum cruisingrange of the aircraft for which she or he is certified. iii. Find the names of pilots whose salary is less than the price of the cheapest route from Bengaluru to Frankfurt. iv. For all aircraft with cruisingrange over 1000 Kms, .find the name of the aircraft and the average salary of all pilots certified for this aircraft. v. Find the names of pilots certified for some Boeing aircraft. vi. Find the aids of all aircraft that can be used on routes from Bengaluru to New Delhi.

Schema Diagram

Flights

From To Distance Departs Arrives Price

No

Aircraft

Aid Aname cruisingrange

Certified

Eid Aid

Employees

Eid Ename Salary

Certified Pilot

Eid No

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 11

ER Diagram

aname

Aid cruisingr

ange price

Aircraft no

from

to

Flights

Certified distance

certifi ed depart

pilot

arrives

Employees

salary eid ename

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 12

3. Consider the following database of student enrollment in courses & 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) BOOK _ ADOPTION (course# :int, sem:int, book-ISBN:int) TEXT (book-ISBN:int, book-title:string, publisher:string, author:string) 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. 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 end for querying and displaying the results.

Schema Diagram

Student

Regno Name Major bdate

Course

Course# Cname dept

Enroll

Regno Course# Sem Marks

Book Adoption

Course# Sem BookISBN Text

BookISBN Booktitle Publisher Author

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 13

ER Diagram

major bdate marks

course# cname

name

Student

dept Course

Enroll

regno

sem Book Adoption

sem

Text

bookISBN

publisher booktitle author

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 14

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) CATALOG (book-id:int, title:string, author-id:int, publisher-id:int, category-id:int, year:int, price:int) CATEGORY (category-id:int, description:string) 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 at least five tuples for each relation. iii. 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. 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 end for querying and displaying the results.

Author author-id Name City country

Publisher Publisher-id Name City country

Catalog

Bookid Title Authorid Publisherid Categoryid Year price

Category

Category-id description

Order Details

Order-no Book-id quantity

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 15

ER Diagram

categoryid descripti

on

category

publish name

erid city

country

city publisher

Author

nam

e catalog

authorid country

title price

orderdetails

orderid bookid quantity

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 16

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 at least five tuples for each relation iii. Find all the customers who have at least two accounts at the Main branch. iv. Find all the customers who have an account at all the branches 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 end for querying and displaying the results

Schema Diagram

Branch Branch-name Branch-city assests

Account

Accno Branch-name balance

Depositor

Customer-name accno

Customer

Customer-name Customer-street Customer-city

Loan

Loan-number Branch-name amount

Borrower

Customer-name Loan-number

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 17

ER Diagram

branchname branchcity assets

balance branchname

M Account-

1

Account branch

branch

accountno

N 1

depositor Loan-

Branch

M M

cname

customer M borrower N Loan

amount

cstreet

ccity branchname

loanno

PESIT(SOUTH CAMPUS),CSE,Surbhi Agrawal 18