Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Subject/Unit Name/Module Name file:///E:/DBMS/M_1.10/index.

html

DBMS / Module 10 / Structured Query Language (Part 2)

Structured Query Language

In the earlier lecture, I introduced the Basics of SQL. We will continue the discussion
on how to write queries when you have two or more relations, Types of various join
operations and additional basic operations of SQL with examples.

Natural Join: Natural join operation considers two relations as operands and
produces a new relation as output by evaluating a condition called join condition on the
common attribute(s). That means Natural Join operation considers only those pairs of
tuples with same value on those attributes that are common in both schemas. Natural
join matches tuples with the same values for all common attributes, and retains only
one copy of each common column.

Question: For all instructors who have taught some course, find their names and the
course ID of the courses they taught.
The schema used to answer the question is

Instructor (Id, name, dept_name, Salary)

Teaches (Id, Course_Id, Sec_Id, Semester, Year)

There are many ways of writing this Query in SQL. We discuss two ways one with
using natural join and the other without using natural join.

SQL Query: select name, course_id,


from instructor, teaches

where instructor.Id = teaches.Id

By using natural join, the same query in SQL using natural join is expressed as

select name, course_Id

from instructor natural join teaches;


Both will generate and return same result.

Question: Find the course ID, semester, year and title of each course offered by the
CSE department

1 of 7 2/16/2012 5:14 PM
Subject/Unit Name/Module Name file:///E:/DBMS/M_1.10/index.html

The relational Schema used for this Query is:

section (course_id, sec_id, , semester, year, building, room_no,


time_slot_id)

course ( course_id, title, dept_name, credits)

SQL Query: select Course_Id, Semester, year, title

from instructor, teaches

where instructor.Id = teaches.Id

By using natural join, the same query in SQL using natural join is expressed as

select section,course_Id, semester, year, title

from section, course

where section natural join instructor and dept_name = ‘CSE‘


In the query shown below we have m relations and m-1 natural join operations and P is
the predicate in where clause You can consider in fact each operation given in the from
clause:

Select A1, A2, … , An

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


where P;
We can as well use relational expressions such as E1, E2, … En. Each Ei is a single
relation or an expression involving natural joins.

Question: List the names of instructors along with the titles of courses that they teach

Select name, title

From instructor natural join teaches, course

Where teaches.course_id = course.course-id.

How is it computed? The following are the steps followed for outputting the answer to
this query.

i) Computes natural join of instructor with teaches.

ii) Cartesian product of result obtained with course is performed next

2 of 7 2/16/2012 5:14 PM
Subject/Unit Name/Module Name file:///E:/DBMS/M_1.10/index.html

iii) Where clause is applied on the result of ii)

But you cannot write SQL query in the form:

Select name, title from instructor natural join teaches natural join course;

This query would then discard all (instructor name, course title) pairs where the
instructor teaches a course in department other than the instructor's own department.

To take the advantage of using natural join operation and avoiding the danger of
equating attributes erroneously, SQL provides a form of the natural join construct that
allow you to specify exactly which columns should be take into account while
equating. The operator joins … using requires a list of attribute names to be specified.
The operation r1 join 2 using (A1. A2) is similar to r1 natural join r2 except that a pair
of tuples t1 from r1 and tuple t2 from r2 match is t1.A1 = t2.A1 and t1.A1 = t2.A2;
even if r1 and r2 both have attribute named A3 is is not required that t1.A3 = t2.A3.

Additional Operations in SQL:


Rename operator: The SQL allows renaming relations and attributes using the as
clause: old-name as new-name. For example, to list the ID, name and average salary
of each instructor, we can write SQL query as

select Id, name, salary/12 as Month_salary

from instructor

Here Month_salary is uses as clause to rename the expression salary/12. As is


optional. Keyword as is optional. Instead of writing instructor as T , we can as well
write instructor T .

Query: Find the names of all instructors who have a higher salary than some instructor
in ‘CSE’.

select distinct T. name


from instructor as T, instructor as S
where T.salary > S.salary and S.dept_name = ‘CSE’

In this query T and S can be thought of as copies of the relations instructor and teaches
and we consider them as aliases. In SQL standard, we call T and S as correlation name,
tuple variable, table alias or correlation variable. This query indicates that all attributes
of instructor are to be selected. Select * indicates that all attributes of the result relation
of the from clause are selected.

Order by Clause: SQL offers Order by clause for the user to display tuples in a
relation in some desired order. This clause causes the tuples in the result of query to
appear in sorted order. For example, to display all instructors in the CSE department in

3 of 7 2/16/2012 5:14 PM
Subject/Unit Name/Module Name file:///E:/DBMS/M_1.10/index.html

alphabetical order, we can use the order by clause. By default, order by clause lists
items in ascending order. Desc for descending order. Ordering can also be performed
on multiple attributes.
Ans: select * from instructor order by salary desc, name asc;

Between is a comparison operator to simplify where clauses that specify that a value <=
some value and greater than or equal to some other value. SQL allows to use the
notation (v1, v2, … , vn) to denote tuple of arity n combining values v1, v2, … , vn .
Comparison operators can be used on tuples, and the ordering is defined
lexicographically. Here condition is defined in where clause. Twu tuples are equal if all
the attributes are equal.

Question: Find the names of instructors whose salary lies between 10000 and 20000.
That is >= 10000 and <= 20000.

SELECT name

FROM Instructor

WHERE salary between 10000 and 20000

Similarly we can use not between operator to answer find all instructors whose salary is
not between (10000, 20000).

SELECT name

FROM Instructor

WHERE not (salary between 10000 and 20000)


There are three set manipulation constructs are provided in SQL to extend the basic
query form. Since the answer to a query is a multi set of rows, it is natural to consider
the use of operations such as union, intersection and difference. SQL supports these
operations under the names UNION, INTERSECT and EXCEPT. Many systems
recognize the keyword MINUS for EXCEPT.
UNION: Can be used to compute the union of any two union-compatible sets of tuples
(which are themselves the result of SQL queries).

Question: Find all courses (course ids) taught in the Fall 2010.

The scheme section ( Course_id, sec_id, semester, year, building, room_number,


time_slot_id). Courseid is foreign key references course scheme.

Question: Find all courses ( courseid) taught in the spring 2011 semester.

SELECT course_id

4 of 7 2/16/2012 5:14 PM
Subject/Unit Name/Module Name file:///E:/DBMS/M_1.10/index.html

FROM Section
WHERE Semester = ‘Spring’’ and year = 2011;
There are three set manipulation constructs are provided in SQL to extend the basic
query form. Since the answer to a query is a multi set of rows, it is natural to consider
the use of operations such as union, intersection and difference. SQL supports these
operations under the names UNION, INTERSECT and EXCEPT. Many systems
recognize the keyword MINUS for EXCEPT.
UNION: Can be used to compute the union of any two union-compatible sets of tuples
(which are themselves the result of SQL queries).

Question: Find all courses (course ids) taught in the Fall 2010.

The scheme section Course_id, sec_id, semester, year, building, room_number,


time_slot_id). Courseid is foreign key references course scheme.

Question: Find all courses (courseid) taught in the spring 2011 semester.

SELECT course_id

FROM Section
WHERE Semester = ‘Spring’’ and year = 2011;
Both the queries Q1 and Q2 return one column results. Now the question is can we
determine the set of all courses taught either in Fall 2010 or spring 2011 or both? The
solution is yes. Already we wrote Q1 and Q2. To determine the combined answer, we
Q1 union Q2. This query says that we want the union of the set of all courses taught
either in fall 2010 or spring 2011 or both. The union operator eliminates automatically
duplicates. This is not so in the case of select clause. If you want retain duplicates, we
must use union all instead of union.

Intersect: Can be used to compute the intersection of any two union-compatible sets
of tuples (which are themselves the result of SQL queries. The solution is yes. Already
we wrote Q1 and Q2. To determine the combined answer, we Q1 Intersect Q2. Intersect
automatically eliminates duplicates. To retain duplicates, use intersect all instead of
intersect.

Except: Can be used to compute the set of tuples from its first input that do not occur
in the second input. That is it performs set difference operation. Here the input
operands are relations. of any two union-compatible sets of tuples (which are
themselves the result of SQL queries.

Problem Set:
Consider the following database:

5 of 7 2/16/2012 5:14 PM
Subject/Unit Name/Module Name file:///E:/DBMS/M_1.10/index.html

Student:
Stuid Stuname Major Credits

S1001 Smith,Tom History 90

S1010 burns,Ed Art 63

S1015 Jones,M Maths 42

S1002 Chin, A Maths 36

S1020 Rivera, J CSC 15

S1013 Mary Maths 9

Faculty:
Facid FacName Dept Rank

F101 Adams Art Professor

F202 Smith History Associate

F105 Tanaka CSC Instructor

F110 Byrne Maths Assistant

F221 Smith CSC Professor

Class:
CourseNo FacId Sched Room

Art103A F101 MWF9 H221

CSC201A F105 TUTHF10 M110

MTH101B F110 MTUTH9 H225

HST205A F202 MWF11 H221

MTH103C F110 MWF11 H225

CSC203A F105 MTHF12 M110

Enroll:
CourseNo StuId Grade

Art103A S1001 A

CSC201A S1020 B

CSC201A S1002 F

Art103A S1010

6 of 7 2/16/2012 5:14 PM
Subject/Unit Name/Module Name file:///E:/DBMS/M_1.10/index.html

Art103A S1002

Art103A S1020 D

MTH101B S1020 A

HST205A S1001 C

MTH103C S1010

MTH103C S1002 B

1. Write SQL queries based on the database given above and also show the output for each
query:

a) Find Ids and names of all students who take ART103A.

b) Get names and Ids of all faculty members, arranged in alphabetical order by
name

c) Get names of all Math majors who have more than 30 credits

d) Find Ids and names of all students taking ART103A

e) Find Studied and Grade of all students taking any course taught by the faculty
member whose FacId is F110. Arrange in order by Stuid.

f) Find course numbers and the names and majors of all students enrolled in the
courses taught by faculty member F110

g) Get a list of all courses that meet in the same room, with their schedules and
room numbers.

h) Find all combinations of students and faculty where the student’s major is
different from the faculty member’s department.

2. Identify appropriate SQL clauses that are needed to express the five basic relational operators
( Selection, projection, union, cross product, and Set Difference) of Relational algebra in
SQL? Discuss each one with an example.

DBMS_13 @ RGUKT 2011

7 of 7 2/16/2012 5:14 PM

You might also like