4 SQL
4 SQL
COMP 353/453
Database Programming
Prof. Silva
These slides were prepared by Prof. Silva adapting the slides from Fundamentals of Database Systems (Elmasri and Navathe) and Understanding
Relational Database Query Languages (Dietrich)
Declarative Language
Relational algebra is a procedural language, giving the operations to
retrieve the data from the database.
2
Basic Query Expressions
Typical SQL query
SELECT A1,A2,...,An
FROM r1,r2,...,rm
WHERE P
A ,A ,..., A ( P ( r 1 r 2 r m ))
1 2 n
3
Overview: Fundamental Relational Algebra Operators
Relational
SQL
Algebra
p
math_majors
(cs_majors):
cs_majors
ID,NAME
select id, name from cs_majors
id id cs_profs teaches cs_course
name name name tname crsid
class class office tcrsid crstitle
age age
Examples: Additional Relational Algebra Operators
cs_majors Ç math_majors:
select * from cs_majors
intersect
select * from math_majors
cs_profs ⋈NAME=TNAME teaches:
select *
from cs_profs P, teaches T - - note table alias names
where P.name = T.tname
cs_profs ⋈ cs_courses ⋈ teaches:
select P.name, P.office, C.crsid, C.crstitle
from cs_profs P, cs_courses C, teaches T
where P.name = T.tname and
math_majors cs_majors T.tcrsid = C.crsid
id id cs_profs teaches cs_course
name name name tname crsid
class class office tcrsid crstitle
age age
SQL Expressive Power
• The examples illustrate that SQL is at least as powerful as relational algebra
• An SQL relation is not a set of tuples but a multiset (bag) of tuples because
a relation can have two or more tuples that are identical in all their attribute
values. To force the elimination of duplicates, use distinct in the select clause:
select distinct A1,A2,...,An from r
• Note that union and except return a set of tuples. To allow duplicates, use
union all or except all.
• SQL provides an order by clause to display the query result in sorted order:
math_majors cs_majors
id id cs_profs teaches cs_course
name name name tname crsid
class class office tcrsid crstitle
age age
More on Querying
SQL supports more complex queries than the basic select-from-
where statement.
• Nested subqueries
• Explicit Sets
• Nested correlated subqueries (Exists/Not Exists)
• Order by
• Aggregation
• Group by
• Having
Nested Subqueries: Set Comparison
Query:
Find computer science majors who are also majoring in math.
Alternative
SQL: select id, name
from cs_majors (select id, name from cs_majors)
INTERSECT
where id in (select id, name from math_majors)
(select id
from math_majors)
To use an equality comparison, the nested query must return a single value.
math_majors cs_majors
id id cs_profs teaches cs_course
name name name tname crsid
class class office tcrsid crstitle
age age
Explicit Sets Example
Query:
Find upper-level computer science majors
SQL: select id
from cs_majors
where class in ('Junior', 'Senior'); Alternative
select id
from cs_majors
where class = 'Junior’
OR class = 'Senior';
math_majors cs_majors
id id cs_profs teaches cs_course
name name name tname crsid
class class office tcrsid crstitle
age age
Nested Correlated Subqueries: Exists/Not Exists
A nested correlated subquery is a nested query that references a value of the outer
subquery.
Query: Find the professors who are not teaching any courses.
SQL: select name
from cs_profs P Alternative
where not exists Select name from cs_profs
(select * EXCEPT
from teaches T Select DISTINCT tname from teaches
where T.tname = P.name)
EXISTS: Evaluates to FALSE if the subquery evaluates to empty;
TRUE otherwise.
Evaluation:
For each cs_profs tuple, the nested query selects all teaches tuples whose tname value matches
the cs_profs name; if the result of the exists subquery is empty then that professor is not
teaching any classes, so the professor is included in the result.
math_majors cs_majors
id id cs_profs teaches cs_course
name name name tname crsid
class class office tcrsid crstitle
age age
ORDER BY
order by ORDER-SPEC-COMMALIST
b) List the names of the employees who took the course with id
‘DB01’ on June 25, 1990.
e.g., Find the number of courses that are currently being taught.
Query: For each professor teaching more than one course, display the name of
the professor and the number of courses the professor is teaching.
SQL: select T.tname, count(*) as numberOfCoursesForProf
from teaches T
group by T.tname
having count(*) > 1
Evaluation: (1) where - condition on individual tuples
(2) group by - groups by grouping attributes
math_majors cs_majors(3) having - conditions on the group selected
id id cs_profs teaches cs_course
name name name tname crsid
class class office tcrsid crstitle
age age
SQL Arithmetic Expressions
The select statement can include arithmetic expressions using +, -, *, /
Consider a scenario of a student worker who is hired at an hourly rate, and
reports hours weekly:
studentWorker(sID, deptCode, hourlyRate)
hoursReported(payDate, sID, hours)
Query: Compute weekly gross for all students ordered by payDate & sID:
SQL: select payDate, sID, hours * hourlyRate as wklyGross
from studentWorker natural join hoursReported
order by payDate, sID
Query: Compute year to date gross for all students ordered by sID
SQL: select sID, sum(hours * hourlyRate) as ytdGross
from studentWorker natural join hoursReported
group by sID
order by sID
22
SQL Arithmetic Expressions Exercise
Using the EmpDeptCourseTakes enterprise, write a query to compute the
yearly commitment in funds for salary and benefits by department,
assuming that the cost of benefits for an employee is 35% of the salary.
23
SQL Data Definition Language
• The industry-standard query language, SQL, also has a
component for defining data, called the data definition
language (DDL).
Where:
ATTRIBUTE-CONSTRAINT represents constraints on the
attribute, and
TABLE-CONSTRAINT-LIST represents constraints on the table
Attribute Constraints - Simple
update TABLENAME
set COLUMN-NAME = VALUE-EXPRESSION, …
[where UPDATE-CONDITION]
Responsibility of DBA
• account creation to restrict access to the DB
• privilege granting/revocation
• security level assignment
Discretionary Privileges: Account Level