sql tutorial - pesit southpesitsouth.pes.edu/pdf/2017/ise/dbms lab manual.pdf · faculties handling...

13
SEMESTER V DBMS LABORATORY WITH MINI PROJECT Subject Code 15CSL58 IA Marks 20 Number of Lecture Hours/Week 01 + 02P Exam Marks 80 Total Number of Lecture Hours 40 Exam Hours 03 Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming (Max. Exam Mks. 50) • Design, develop, and implement the specified queries for the following problems using Oracle, MySQL, MS SQL Server, or any other DBMS under LINUX/Windows environment. • Create Schema and insert at least 5 records for each table. Add appropriate database constraints. PART-B: Mini Project (Max. Exam Mks. 30) • Use Java, C#, PHP, Python, or any other similar front -end tool. All applications must be demonstrated on desktop/laptop as a stand-alone or web based application (Mobile apps on Android/IOS are not permitted.) SQL Tutorial IBM developed the original version of SQL, originally called Sequel, as part of the System R project in the early 1970s. The Sequel language has evolved since then, and its name has changed to SQL (Structured Query Language). Many products now support the SQL language. SQL has clearly established itself as the standard relational database language. The SQL language has several parts: Data-definition language (DDL). The SQL DDL provides commands for defining relation schemas, deleting relations, and modifying relation schemas. Data-manipulation language (DML). The SQL DML provides the ability to query information from the database and to insert tuples into, delete tuples from, and modify tuples in the database. Integrity. The SQL DDL includes commands for specifying integrity constraints that the data stored in the database must satisfy. Updates that violate integrity constraints are disallowed. View definition. The SQL DDL includes commands for defining views. Transaction control. SQL includes commands for specifying the beginning and ending of transactions. Embedded SQL and dynamic SQL. Embedded and dynamic SQL define how SQL statements can be embedded within general-purpose programming languages, such as C, C++, and Java. Authorization. The SQL DDL includes commands for specifying access rights to relations and views.

Upload: vanquynh

Post on 13-May-2018

231 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

SEMESTER – V

DBMS LABORATORY WITH MINI PROJECT

Subject Code 15CSL58 IA Marks 20 Number of Lecture

Hours/Week 01 + 02P Exam Marks 80

Total Number of Lecture Hours 40 Exam Hours 03

Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu

PART-A: SQL Programming (Max. Exam Mks. 50)

• Design, develop, and implement the specified queries for the following problems using Oracle, MySQL,

MS SQL Server, or any other DBMS under LINUX/Windows environment.

• Create Schema and insert at least 5 records for each table. Add appropriate database constraints.

PART-B: Mini Project (Max. Exam Mks. 30)

• Use Java, C#, PHP, Python, or any other similar front-end tool. All applications must be demonstrated on

desktop/laptop as a stand-alone or web based application (Mobile apps on Android/IOS are not permitted.)

SQL Tutorial

IBM developed the original version of SQL, originally called Sequel, as part of the System R project in the

early 1970s. The Sequel language has evolved since then, and its name has changed to SQL (Structured

Query Language). Many products now support the SQL language. SQL has clearly established itself as the

standard relational database language.

The SQL language has several parts:

Data-definition language (DDL). The SQL DDL provides commands for defining relation schemas,

deleting relations, and modifying relation schemas.

Data-manipulation language (DML). The SQL DML provides the ability to query information from the

database and to insert tuples into, delete tuples from, and modify tuples in the database.

Integrity. The SQL DDL includes commands for specifying integrity constraints that the data stored in the

database must satisfy. Updates that violate integrity constraints are disallowed.

View definition. The SQL DDL includes commands for defining views.

Transaction control. SQL includes commands for specifying the beginning and ending of transactions.

Embedded SQL and dynamic SQL. Embedded and dynamic SQL define how SQL statements can be

embedded within general-purpose programming languages, such as C, C++, and Java.

Authorization. The SQL DDL includes commands for specifying access rights to relations and views.

Page 2: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

Create databases:

Create database <database name>;

Use <database name>

Create table:

The general form of the create table command is:

create table r

(A1 D1,

A2 D2,

. . . ,

An Dn,

integrity-constraint1,

. . . ,

integrity-constraintk

);

Example :The following command creates a relation department in the database.

create table department

(dept name varchar (20),

building varchar (15),

budget numeric (12,2),

primary key (dept name));

The form of the alter table command is

Alter table

alter table r add AD;

where r is the name of an existing relation, A is the name of the attribute to be added, and D is the type of

the added attribute.

We can drop attributes from a relation by the command

alter table r drop A;

where r is the name of an existing relation, and A is the name of an attribute of the relation. Many database

systems do not support dropping of attributes, although they will allow an entire table to be dropped.

Populate tables

A newly created relation is empty initially. We can use the insert command to load data into the relation.

For example, if we wish to insert the fact that thereis an instructor named Smith in the Biology department

with instructor id 10211

and a salary of $66,000, we write:

insert into instructor

values (10211, ’Smith’, ’Biology’, 66000);

The values are specified in the order in which the corresponding attributes are listed in the relation schema.

Delete

Page 3: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

We can use the delete command to delete tuples from a relation. The command

delete from student;

SQL queries Explained using part of university database.

Note:This whole tutorial is based on the following database

SQL data definition for part of the university database.

create table department

(dept name varchar (20),

building varchar (15),

budget numeric (12,2),

primary key (dept name));

>create table course

(course id varchar (7),

title varchar (50),

dept name varchar (20),

credits numeric (2,0),

primary key (course id),

foreign key (dept name) references department);

>create table instructor

(ID varchar (5),

name varchar (20) not null,

dept name varchar (20),

salary numeric (8,2),

primary key (ID),

foreign key (dept name) references department);

>create table section

(course id varchar (8),

sec id varchar (8),

semester varchar (6),

year numeric (4,0),

building varchar (15),

room number varchar (7),

time slot id varchar (4),

primary key (course id, sec id, semester, year),

foreign key (course id) references course);

>create table teaches

(ID varchar (5),

course id varchar (8),

sec id varchar (8),

semester varchar (6),

year numeric (4,0),

primary key (ID, course id, sec id, semester, year),

foreign key (course id, sec id, semester, year) references section,

foreign key (ID) references instructor);

Page 4: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

To remove a relation from an SQL database, we use the drop table command. The drop table command

deletes all information about the dropped relation from the database. The command

drop table r;

deletes all tuples in r

delete from r;

Basic Structure of SQL Queries:

The basic structure of an SQL query consists of three clauses: select, from, and where. The query takes as

its input the relations listed in the from clause, operates on them as specified in the where and select

clauses, and then produces a relation as the result.

Queries on a Single Relation

Example 1 : “Find the names of all instructors.”

select name

from instructor;

Example 2 : “Find the department names of all instructors,”

select dept name

from instructor;

Example 3 :In cases where we want to force the elimination of duplicates, we insert the keyword distinct

after select.

select distinct dept name

from instructor;

Example 4 :Use of the keyword all to specify explicitly that duplicates are not removed:

select all dept name

from instructor;

select clause containing arithmetic expressions involving the operators +, −, ∗ , and /

Example 5: select ID, name, dept name, salary * 1.1

from instructor;

Example 6 :“Find the names of all instructors in the Computer Science department who have salary greater

than $70,000.”

select name

from instructor where dept name = ’Comp. Sci.’ and salary > 70000;

Queries on Multiple Relations

Page 5: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

Example 7 : “Retrieve the names of all instructors, along with their department names and department

building name.”

select name, instructor.dept name, building

from instructor, department

where instructor.dept name= department.dept name;

A typical SQL query has the form

select A1, A2, . . . , An

from r1, r2, . . . , rm

where P;

Example 8: “For all instructors in the university who have taught some course, find their names and the

course ID of all courses they taught”:

select name, course id

from instructor, teaches

where instructor.ID= teaches.ID;

This query can be written more concisely using the natural-join operation in SQL as:

select name, course id

from instructor natural join teaches;

A from clause in an SQL query can have multiple relations combined using natural join, as shown here:

select A1, A2, . . . , An

from r1 natural join r2 natural join . . . natural join rm

where P;

Example 9: “List the names of instructors along with the the titles of courses that they teach.”:

select name, title

from instructor natural join teaches, course

where teaches.course id= course.course id;

Additional Basic Operations

Example 10 :“For all instructors in the university who have taught some course, find their names and the

course ID of all courses they taught.”

select T.name, S.course id

from instructor as T, teaches as S

where T.ID= S.ID;

Example 11:“Find the names of all instructors whose salary is greater than at least one instructor in the

Biology department.”

select distinct T.name

from instructor as T, instructor as S

where T.salary > S.salary and S.dept name = ’Biology’;

Page 6: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

String Operations:

Pattern matching can be performed on strings, using the operator like. We describe patterns by using two

special characters:

Percent (%): The % character matches any substring.

Underscore ( ): The character matches any character.

To illustrate pattern matching,we consider the following examples:

’Intro%’ matches any string beginning with “Intro”.

’%Comp%’ matches any string containing “Comp” as a substring, for example,

’Intro. to Computer Science’, and ’Computational Biology’.

’_ _ _’ matches any string of exactly three characters.

’ _ _ _%’ matches any string of at least three characters.

Example 12 :“Find the names of all departments whose building name includes the substring ‘Watson’.” :

select dept name

from department

where building like ’%Watson%’;

Ordering the Display of Tuples

Example 13:To list in alphabetic order all instructors in the Physics department:

select name

from instructor

where dept name = ’Physics’

order by name;

Example 14: if several instructors have the same salary, we order them in ascending order by name.We

express this query in SQL as follows:

select *

from instructor

order by salary desc, name asc;

Where Clause Predicates

Example 15:find the names of instructors with salary amounts between $90,000 and $100,000.

select name

from instructor

where salary between 90000 and 100000;

Example 16: “Find the instructor names and the courses they taught for all instructors in the Biology

department who have taught some course.”

select name, course id

from instructor, teaches

where (instructor.ID, dept name) = (teaches.ID, ’Biology’);

Page 7: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

Set Operations

Example 17:The set of all courses taught in the Fall 2009 semester:

select course id

from section

where semester = ’Fall’ and year= 2009;

Example 18: The set of all courses taught in the Spring 2010 semester:

select course id

from section

where semester = ’Spring’ and year= 2010;

The Intersect Operation

Example 19:To find the set of all courses taught in the Fall 2009 as well as in Spring 2010:

(select course id

from section

where semester = ’Fall’ and year= 2009)

intersect

(select course id

from section

where semester = ’Spring’ and year= 2010);

The Except Operation

Example 20:To find all courses taught in the Fall 2009 semester but not in the Spring 2010 semester:

(select course id

from section

where semester = ’Fall’ and year= 2009)

except

(select course id

from section

where semester = ’Spring’ and year= 2010);

Aggregate Functions

Aggregate functions are functions that take a collection (a set or multiset) of values as input and return a

single value. SQL offers five built-in aggregate functions:

• Average: avg

• Minimum: min

• Maximum: max

• Total: sum

• Count: count

Basic Aggregation

Example 21: “Find the average salary of instructors in the Computer Science department.”

select avg (salary)

from instructor

Page 8: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

where dept name= ’Comp. Sci.’;

Example 22:“Find the total number of instructors who teach a course in the Spring 2010 semester.”

select count (distinct ID)

from teaches

where semester = ’Spring’ and year = 2010;

Aggregation with Grouping

Example 23: “Find the average salary in each department.”

select dept name, avg (salary) as avg salary

from instructor

group by dept name;

Example 24: “Find the number of instructors in each department who teach a course in the Spring 2010

semester.”

select dept name, count (distinct ID) as instr count

from instructor natural join teaches

where semester = ’Spring’ and year = 2010

group by dept name;

The Having Clause

Example 25:departments where the average salary of the instructors is more than $42,000.

select dept name, avg (salary) as avg salary

from instructor

group by dept name

having avg (salary) > 42000;

Example 26: “For each course section offered in 2009, find the average total credits (tot cred) of all

students enrolled in the section, if the section had at least 2 students.”

select course id, semester, year, sec id, avg (tot cred)

from takes natural join student

where year = 2009

group by course id, semester, year, sec id

having count (ID) >= 2;

Nested Subqueries

Example 27: “Find all the courses taught in the both the Fall 2009 and Spring 2010 semesters.”

select distinct course id

from section

where semester = ’Fall’ and year= 2009 and

course id in (select course id

from section

where semester = ’Spring’ and year= 2010);

Example 28:find all the courses taught in the Fall 2009 semester but not in the Spring 2010

semester:

Page 9: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

select distinct course id

from section

where semester = ’Fall’ and year= 2009 and

course id not in (select course id

from section

where semester = ’Spring’ and year= 2010);

Example 29: “find the total number of (distinct) students who have taken course sections taught by the

instructor with ID 110011” :

select count (distinct ID)

from takes

where (course id, sec id, semester, year) in (select course id, sec id, semester, year

from teaches

where teaches.ID= 10101);

Set Comparison

Example 30:find the names of all instructors that have a salary value greater than that of each instructor in

the Biology department.

select name

from instructor

where salary > all (select salary

from instructor

where dept name = ’Biology’);

Example 31: “Find the departments that have the highest average salary.”

select dept name

from instructor

group by dept name

having avg (salary) >= all (select avg (salary)

from instructor

group by dept name);

Example 32: “Find all studentswho have taken all courses offered in the Biology department.” Using the

except construct:

select distinct S.ID, S.name

from student as S

where not exists ((select course id

from course

where dept name = ’Biology’)

except

(select T.course id

from takes as T

where S.ID = T.ID));

Updates

Example 33:salaries of all instructors are to be increased by 5 percent:

update instructor

set salary= salary * 1.05;

Page 10: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

Example 34:If a salary increase is to be paid only to instructors with salary of less than $70,000:

update instructor

set salary = salary * 1.05

where salary < 70000;

Views

We define a view in SQL by using the create view command. To define a view, we must give the view a

name and must state the query that computes the view. The form of the create view command is:

create view v as <query expression>;

Consider the clerk who needs to access all data in the instructor relation, except salary. The clerk should not

be authorized to access the instructor relation. Instead, a view relation faculty can be made available to the

clerk ,with the view defined as

follows:

Example 35:

create view faculty as

select ID, name, dept name

from instructor;

Create Table Extensions

Applications often require creation of tables that have the same schema as an existing table. SQL provides a

create table like extension to support this task:

create table temp instructor like instructor;

Example 36: creates a table t1 containing the results of a query.

create table t1 as

(select *

from instructor

where dept name= ’Music’)

with data;

Page 11: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

LAB Queries to be executed during the course of semester

Part A: SQL Programming 1

Consider the following schema for a Library Database:

BOOK(Book_id, Title, Publisher_Name, Pub_Year)

BOOK_AUTHORS(Book_id, Author_Name)

PUBLISHER(Name, Address, Phone)

BOOK_COPIES(Book_id, Branch_id, No-of_Copies)

BOOK_LENDING(Book_id, Branch_id, Card_No, Date_Out, Due_Date)

LIBRARY_BRANCH(Branch_id, Branch_Name, Address)

Key constraints :

Write SQL queries to

1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of copies in each

branch, etc.

2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017 to Jun 2017.

3. Delete a book in BOOK table. Update the contents of other tables to reflect this data manipulation

operation.

4. Partition the BOOK table based on year of publication. Demonstrate its working with a simple query.

5. Create a view of all books and its number of copies that are currently available in the Library.

Part A: SQL Programming 2

Consider the following schema for Order Database:

SALESMAN(Salesman_id, Name, City, Commission)

CUSTOMER(Customer_id, Cust_Name, City, Grade, Salesman_id)

ORDERS(Ord_No, Purchase_Amt, Ord_Date, Customer_id, Salesman_id)

Write SQL queries to

1. Count the customers with grades above Bangalore’s average.

2. Find the name and numbers of all salesman who had more than one customer.

3. List all the salesman and indicate those who have and don’t have customers in their cities (Use UNION

operation.)

4. Create a view that finds the salesman who has the customer with the highest order of a day.

5. Demonstrate the DELETE operation by removing salesman with id 1000. All his orders must also be

deleted.

Part A: SQL Programming 3

Consider the schema for Movie Database:

ACTOR(Act_id, Act_Name, Act_Gender)

DIRECTOR(Dir_id, Dir_Name, Dir_Phone)

MOVIES(Mov_id, Mov_Title, Mov_Year, Mov_Lang, Dir_id)

MOVIE_CAST(Act_id, Mov_id, Role)

Page 12: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

RATING(Mov_id, Rev_Stars)

Write SQL queries to

1. List the titles of all movies directed by ‘Hitchcock’.

2. Find the movie names where one or more actors acted in two or more movies.

3. List all actors who acted in a movie before 2000 and also in a movie after 2015 (use JOIN operation).

4. Find the title of movies and number of stars for each movie that has at least one rating and find the

highest number of stars that movie received. Sort the result by movie title.

5. Update rating of all movies directed by ‘Steven Spielberg’ to 5.

Part A: SQL Programming 4

Consider the schema for College Database:

STUDENT(USN, SName, Address, Phone, Gender)

SEMSEC(SSID, Sem, Sec)

CLASS(USN, SSID)

SUBJECT(Subcode, Title, Sem, Credits)

IAMARKS(USN, Subcode, SSID, Test1, Test2, Test3, FinalIA)

Write SQL queries to

1. List all the student details studying in fourth semester ‘C’ section.

2. Compute the total number of male and female students in each semester and in each section.

3. Create a view of Test1 marks of student USN ‘1BI15CS101’ in all subjects.

4. Calculate the FinalIA (average of best two test marks) and update the corresponding table for all students.

5. Categorize students based on the following criterion:

If FinalIA = 17 to 20 then CAT = ‘Outstanding’

If FinalIA = 12 to 16 then CAT = ‘Average’

If FinalIA< 12 then CAT = ‘Weak’

Give these details only for 8th semester A, B, and C section students.

Part A: SQL Programming 5

Consider the schema for Company Database:

EMPLOYEE(SSN, Name, Address, Sex, Salary, SuperSSN, DNo)

DEPARTMENT(DNo, DName, MgrSSN, MgrStartDate)

DLOCATION(DNo,DLoc)

PROJECT(PNo, PName, PLocation, DNo)

WORKS_ON(SSN, PNo, Hours)

Write SQL queries to

1. Make a list of all project numbers for projects that involve an employee whose last name is ‘Scott’, either

as a worker or as a manager of the department that controls the project.

2. Show the resulting salaries if every employee working on the ‘IoT’ project is given a 10 percent raise.

3. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well as the maximum

salary, the minimum salary, and the average salary in this department

4. Retrieve the name of each employee who works on all the projects controlledby department number 5

(use NOT EXISTS operator).

Page 13: SQL Tutorial - PESIT Southpesitsouth.pes.edu/pdf/2017/ISE/DBMS Lab Manual.pdf · Faculties handling Lab: Mr.Kartik.S/ Ms.Rashma.B.M/ Ms.Sharmila Banu PART-A: SQL Programming ... MS

5. For each department that has more than five employees, retrieve the department number and the number

of its employees who are making more than Rs. 6,00,000.

Part B: Mini project

• For any problem selected, write the ER Diagram, apply ER-mapping rules, normalize the relations, and

follow the application development process.

• Make sure that the application should have five or more tables, at least one trigger and one stored

procedure, using suitable frontend tool.

• Indicative areas include; health care, education, industry, transport, supply chain, etc.

• Implement, analyze and evaluate the project developed for an application.

Conduction of Practical Examination:

1. All laboratory experiments from part A are included for practical examination.

2. Mini project is evaluated for 30 Marks as per 6(b).

3. Report should be prepared in a standard format prescribed for project work.

4. Students are allowed to pick one experiment from the lot.

5. Strictly follow the instructions as printed on the cover page of answer script.

6. Marks distribution:

a) Part A: Procedure + Conduction + Viva:10 + 35 +5 =50 Marks

b) Part B: Demonstration + Report + Viva voce = 15+10+05 = 30 Marks

7. Change of experiment is allowed only once and marks allotted to the procedure

part to be made zero.