Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

SQL Queries

The document describes SQL queries for interactive querying of relational databases. It covers basic SELECT statements with projections, joins, and filters. It also discusses nested queries, aggregate functions, integrity constraints, and other SQL features. Sample queries are provided on university database schemas involving students, courses, faculty and other tables.

Uploaded by

puvi ththira
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

SQL Queries

The document describes SQL queries for interactive querying of relational databases. It covers basic SELECT statements with projections, joins, and filters. It also discusses nested queries, aggregate functions, integrity constraints, and other SQL features. Sample queries are provided on university database schemas involving students, courses, faculty and other tables.

Uploaded by

puvi ththira
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

SQL: Interactive Queries

Basic Select Statement

• Basic form of the select statement:


select target-attribute-list
from table-list
where conditions;

• Correspondence to relational algebra:


select-clause  projection ()
from-clause  Cartesian product ()
where-clause  selection ()
select --- project(pi)
from ----- cartesian product(x)
where ----- selection(sigma)
A Sample University Schema

• Students(SID, Name, Age, Sex, Major, GPA)


• Courses(Cno, Title, Hours, Dept)
• Enrollment(SID, Cno, Year, Grade)
• Offers(Cno, Year, FID)
• Faculty(FID, Name, Rank, Dept, Salary)
• Departments(Name, Location, ChairID)

Assume a natural choice of data types and foreign key


constraints.
Single Table Queries

• Find SID, Name and GPA of students with GPA higher


than 3.8.
select SID, Name, GPA all => select * from
from Students
where GPA > 3.8;
• Use shorthand * to select all columns.
select * from Students
where GPA > 3.8;

• Find names of students with GPA between 3.5 and 3.8.


select Name from Students
where GPA between 3.5 and 3.8; where ____ between ___ and
Duplicate Removal

• How to remove duplicate rows?


• Use key word distinct.
select distinct SID, Cno
from Enrollment;

remove duplicate rows ---> select distinct ____


from ____
SQL Integrity Constraints
• Rules or regulations imposed to ensure data
integrity
• Column Constraints
• Table Constraints
• Triggers
• Primary Key, Foreign Key, Check, Not Null,
Unique…
Column Constraints
• Not null: Cannot take null value
• Unique: Cannot have identical non-null values
• Primary key: Both not null and unique
• Check(Condition): Values must satisfy the check
condition

not null check == must satisfy condition


primary key
unique
Referential Integrity
• Assume that Courses.Dept references Departments.Name.
What should the system do to students if we cange a
department’s name or delete a department?

• SQL provides four options:


o No action: Disallow such an update
o Cascade: Accept update & update all affected foreign key
values
o Set default: Accept update & set default FK
o Set null: Accept update & set FK to null
Referential Integrity Example
Create table Courses(
Cno char(6) not null primary key
Title char(35) not null
Hours int check (Hours between 1 and 5)
Dept char(20)
Foreign key (Dept) references
Departments(Name)
On delete no action on update cascade)

foreign key(----) references


A Multiple Table Query

Find id of faculty members who taught Database I in 1998


select FID from Offers, Courses
where Title = ‘Database I’ and Year = 1998
and Offers.Cno = Courses.Cno;
table.column

Offers Courses
Cno Year FID Cno Title Hours Dept
CS374 1999 2010 CS374 Database I 3 CS
M150 1998 1557 M150 Calculus I 3 Math
CS374 1998 2158
Tuple Variables
• Renaming (Relation Aliases) can simplify query
specifications.
You can rename a table or a column temporarily by giving another name known as Alias.
The use of table aliases is to rename a table in a specific SQL statement. The renaming is
a temporary change and the actual table name does not change in the database.

• Find names and GPAs of students who take Database I.


select Name, GPA
from Students S, Enrollment E, Courses C students s
where Title = ‘Database I’ and S.SID = E.SID enrollment e
courses c
and E.Cno = C.Cno;
When Are Aliases Necessary?
• Find pairs of students who have same GPA.
select s1.SID, s2.SID
from Students s1, Students s2
where s1.GPA = s2.GPA and s1.SID < s2.SID
➢ Why use “s1.SSN < s2.SSN”? Think!

• Find names of students with GPA higher than Tom's.


select s1.Name from Students s1, Students s2
where s2.Name = `Tom' and s1.GPA > s2.GPA
➢ Compare to all Tom’s or any one Tom? Think!
String Matching Operators
• Find numbers and titles of courses that have “systems”
match 0 or more
in the title.
select Cno, Title from Courses
where ___ like '*___*'
where Title like `*systems*'
➢ * matches 0 or more characters.

• Find students with a six-letter name starting with an ‘M’.


match exactly one
select * from Students
where Name like `M?????'
➢ ? matches exactly one character
where____ like '_?????'
Set Operations
• SQL supports three set operations:
union, intersect, except (or minus)

• Requires union compatibility. Recall that


o They have same number of attributes;
o Corresponding attributes have same type.
• Applied on (relations specified by) subqueries.

➢ Set operations automatically removes duplicate rows. To keep duplicate in


union, use union all.
Examples Using Set Operations
• Find SID of students who either take Database I or
major in CS.

(select SID
from Enrollment E, Courses C
where E.Cno = C.Cno and Title = ‘Database I’)
union
(select ____ from ____ where)
(select SID union
from Students (select ___ from _____ where)
where Major = ‘CS’)

➢ What do we get if use intersect or except? Think!


outer query
Nested (Sub)Query
• Find names of students who take at least one course
offered by CS department.
select ___ from ___ where ___ in
( select___ from____ where ___)
select Name
from Students S, Enrollment E
where S.SID = E.SID and E.Cno in
intersection
(select Cno from Courses
where Dept = 'CS')

inner query

Outer query Inner query


Correlated Nested Query
• List SID and Cno pairs for which the student takes the
course and has the same name as the instructor.
select ____ from students s,
entrollment e
select SID, Cno where s.sid=e.sid and(__,__)
from Students S, Enrollment E
in
where S.SID = E.SID and (Cno, Year) in
(select __,___ from ___ O, ___F
where O.___=F.___ and ___=S.__)
(select Cno, Year
from Offers O, Faculty F
where O.FID=F.FID and correlation
Name = S.Name)
Flatten Nested Queries
• Every nested query has equivalent flat queries.
• The last query is equivalent to the following.
select SID, Cno
from Students S, Enrollment E,
Offers O, Faculty F
where S.SID = E.SID and E.Cno = O.Cno and
E.Year = O.Year and O.FID=F.FID and
F.Name = S.Name

➢ Why nested query? Why flatten nested query?


Another Nested Query

• Find enrollments where a 25-year-old student takes a


CS course.

select * from Enrollment


where (SID, Cno) in
(select S.SID, C.Cno
from Students S, Courses C
where S.Age = 25 and C.Dept = 'CS‘)
Another Nested Query (cont.)

Other ways to write the query:


• select * from Enrollment
where SID in (select SID from Students
where Age = 25)
and Cno in (select Cno from Courses
where Dept = 'CS')

• select E.* from Enrollment E, Students S, Courses C


where S.SID=E.SID
and E.Cno=C.Cno
and S.Age = 25
and C.Dept = ‘CS’
Quantified Comparisons
• Find names of students who are 18 or younger with a
GPA higher than the GPA of some students who are 25
or older.

select Name from Students


where Age <= 18 and GPA >some
(select GPA from Students
where Age >= 25)

➢ Also <some, <=some, >=some, =some, <>some.


➢ Can also use any (same as some). Also have all.
Aggregate Functions
• Functions that take a set of tuples and compute an
aggregated value.
• Five standard functions:
count, min, max, avg, sum
• They ignore null values.
• Find the total number, the average, minimum, and
maximum GPA of students whose age is 17.
select count(*), avg(GPA), min(GPA), max(GPA)
from Students
select count(*) , avg(___) , min( ___ ), max( ___ )
where Age = 17 from _____
where _____
Aggregate Functions (cont.)
• Find id and name of students who take 5 or more
courses.
select ____ from ____ where ___
select SID, Name ( select count(___) from ____ where ____ )
from Students s
where 5 <= (select count(distinct Cno)
from Enrollment
where SID = s.SID)

➢ Count(distinct Cno)  distinct count(Cno). Why?


➢ Must make sure the subquery generates a value comparable in the
predicate.
Group By Clause
• List id and name of students together with the number
of hours still needed to graduate, assuming 120 hours
are required.

select s.SID, Name,


120 - sum(Hours) Hours-Needed
from Students s, Enrollment e, Courses c
where s.SID = e.SID and e.Cno = c.Cno
and Grade <= ‘C’
group by s.SID, Name

➢ Enrolled courses are grouped by students.


Group By Clause (cont.)
 Aggregate functions often applied to groups.
 One tuple is generated per group
 When using group by, select clause can contain only
grouping attributes and aggregate func.
 Every grouping attribute must be in the select
clause.The following is an illegal query (why?):
select Age, SID, avg(GPA)
from Students
group by Age
Having Clause
• For each student age group with more than 50
members, list the age and the number of students
with that age.
select Age, count(*) select ____ count(*) from ____ group by ____
from Students having count(*) ____
group by Age
having count(*) > 50

➢ Conditions on aggregate functions are specified in the having clause.


➢ Select & Having may have different functions.
Order By Clause
• List student names in ascending order.
select Name from Students
order by Name asc
• The default is ascending order.
• List students with GPA higher than 3.5, first in
descending order of GPA, and then in ascending order
of name. select * from ___ where ____ order by ___
desc, _____,asc
select * from Students
where GPA > 3.5
order by GPA desc, Name asc

You might also like