03 2 Structured Query Language Part 2
03 2 Structured Query Language Part 2
3
Outline
1. Data Manipulation: SQL Retrieval statement (Part 2)
2. View
3. Privileges and User Management in SQL
4
Learning objective
• Write retrieval statement in SQL: from simple queries to
complex ones
• Create views and work correctly on predefined views
• Have experience with a DBMS: manage user account and
database access permissions
5
Keywords
Keyword Description
A subquery (inner query, nested query) is a query within another (SQL) query.
Subquery
A view is the result set of a stored query on the data, which the database use
View rs can query just as they would in a persistent database collection object.
6
Data Manipulation:
SQL Retrieval statement (Part 2)
1. Joins operators
2. Subqueries: in FROM clause and in WHERE clause
3. Union, Intersection and Difference of Queries
4. Aggregation operators
5. Grouping and aggregation in SQL , conditions in HAVING clause
6. Controlling the output: duplicate elimination, ordering the result
7
1. Example of a database schema
student(student_id, first_name,last_name, dob, gender,address,note,clazz_id)
clazz(clazz_id, name, lecturer_id, monitor_id)
subject(subject_id, name, credit, percentage_final_exam)
enrollment(student_id, subject_id, semester, midterm_score, final_score)
lecturer(lecturer_id, first_name, last_name, dob, gender, address, email)
teaching(subject_id, lecturer_id)
grade(code, from_score, to_score)
List of all female students ?
DBMS
First name, last name and address of class monitors ?
List of students (id and fullname) have
Client-applications enrolled subject 'Học máy' in semester 20172?
(in C#, Java, php, ...)
List of students (id and fullname) having CPA >= 3.2?
8
1. Example of a database schema
student
student_id first_name last_name dob gender …
List of students (id and fullname)
20160001 Ngọc An Bùi 3/18/1987 M …
have enrolled subject 'Học máy' in
… … … … … …
semester 20172?
20160003 Thu Hồng Trần 6/6/1987 F …
20160004 Minh Anh Nguyễn 5/20/1987 F …
enrollment
midterm_ final_
student_id subject_id semester
score score
subject
20160001 IT1110 20171 9 8.5
percentage_
… … … … … subject_id name credit
final_exam
20160001 IT4866 20172 7 9 IT1110 Tin học đại cương 4 60
20160002 IT3080 20172 9 … … … …
20160003 IT4866 20172 7 6 IT4866 Học máy 2 70
9
1. Data Manipulation: SELECT operation
SELECT[all|distinct]
{*|{table_name.*|expr[alias]}|view_name.*}
[,{table_name.*|expr[alias]}]...}
FROM table_name [alias][,table_name[alias]] ...
[WHERE condition]
[GROUP BY expr [,expr] ...]
[HAVING condition]
[{UNION|UNION ALL|INTERSECT|MINUS}
SELECT ...]
[ORDER BY {expr|position} [ASC|DESC]
[,expr|position}[ASC|DESC]
10
Data Manipulation: Advanced SELECT
• Joins operators
• Subqueries: in FROM clause and in WHERE clause
• Aggregation operators
• Grouping and aggregation in SQL , conditions in HAVING
clause
• Controlling the output: duplicate elimination, ordering the result
11
1.1. Joins operators
• Syntax:
SELECT t1.c1, t1.c2, …, t2.c1, t2.c2
FROM t1, t2
WHERE condition_expression
• Example:
student(student_id, first_name,last_name, dob, gender,address,note,clazz_id)
clazz(clazz_id, name, lecturer_id, monitor_id)
SELECT clazz.clazz_id, name, last_name, first_name
FROM clazz, student
WHERE student_id = monitor_id
12
1.1. Joins operators: Operational semantics
• Example:
SELECT c.clazz_id, name, s.last_name, s.first_name
FROM clazz AS c, student s
WHERE s.student_id = c.monitor_id
14
1.1. Joins operators: Self-join
Find all pairs of subjects id having the same name but the credit of the
first subject is less than the credit of the second one
15
1.1. Joins operators: Example
List of students have enrolled subjects in semester 20172. The list composes of student
fullname, subject name, subject credit:
SELECT last_name ||' ' ||first_name as fullname,
sj.name as subjectname, credit
FROM student s, enrollment e, subject sj
WHERE s.student_id = e.student_id
AND sj.subject_id = e.subject_id
AND semester = '20172'
16
1.1. Joins operators: Join types
• Product:
• R CROSS JOIN S
• Theta join:
• R [INNER] JOIN S ON <condition>
• Natural join: (Be careful!)
• R NATURAL JOIN S
• Outer join:
• R [LEFT|RIGHT|FULL] [OUTER] JOIN S ON <condition>
• R NATURAL [LEFT|RIGHT|FULL] [OUTER] JOIN S
17
1.1. Joins operators: OUTER JOINS
• R [LEFT|RIGHT|FULL] OUTER JOIN S ON <condition>
• R NATURAL [LEFT|RIGHT|FULL] OUTER JOIN S
18
1.1. Joins operators: OUTER JOIN Example
• List of all classes with monitor names (firstname and lastname, NULL if
class has not yet a monitor)
clazz student
clazz_id name lecturer_id monitor_id student_id first_name last_name … clazz_id
20162101 CNTT1.01-K61 02001 20160003 20160003 Thu Hồng Trần … 20162101
20162102 CNTT1.02-K61 20160004 Minh Anh Nguyễn … 20162101
20172201 CNTT2.01-K62 02002 20170001 … … … … …
20172202 CNTT2.02-K62
result
clazz_id name last_name first_name
SELECT c.clazz_id, name, last_name, first_name 20172202 CNTT2.02-K62 NULL NULL
FROM clazz c LEFT OUTER JOIN student 20162102 CNTT1.02-K61 NULL NULL
ON (student_id = monitor_id); 20162101 CNTT1.01-K61 Trần Thu Hồng
20172201 CNTT2.01-K62 Nguyễn Nhật Ánh
19
1.2. Sub-queries
• A SELECT-FROM-WHERE statement can be used within a clause
of another outer query. It can be
• within a WHERE clause
• within a FROM clause
• Creates an intermediate result
• No limit to the number of levels of nesting
• Objectives:
• Check if an element is in a set (IN, NOT IN)
• Set comparison >ALL, >=ALL, <ALL,<=ALL,=ALL, ANY (SOME)
• Check if a relation is empty or not (EXISTS, NOT EXISTS)
20
1.2. Sub-queries: Subquery returns scalar value
• A sub-query provide a single value è we can use it as if it were
a constant
SELECT *
FROM student
WHERE clazz_id = (SELECT clazz_id
FROM clazz
WHERE name = 'CNTT1.01-K61');
21
1.2. Sub-queries: IN operators
• Syntax:
<tuple> [NOT ] IN <subquery>
• Example: First name, last name and address of class monitors?
student(student_id, first_name,last_name, dob, gender, address, note, clazz_id)
clazz(clazz_id, name, lecturer_id, monitor_id)
22
1.2. Sub-queries: EXISTS
• Syntax:
[NOT] EXISTS (<subquery>)
EXISTS (<subquery>): TRUE iff <subquery> result is not empty
• Example: subjects having no lecturer?
teaching(subject_id, lecturer_id)
subject(subject_id, name, credit, percentage_final_exam)
SELECT * FROM subject s
WHERE not exists (SELECT *
FROM teaching
WHERE subject_id = s.subject_id)
23
1.2. Sub-queries: ALL, ANY
• Syntax: <expression> <comparison_operator> ALL|ANY <subquery>
o <comparison_operator>: >, <, <=, >=, =, <>
o X >=ALL<subquery>: TRUE if there is no tuple larger than X in <subquery> result
o X = ANY<subquery>: TRUE if x equals at least one tuple in <subquery> result
o X >ANY<subquery>: TRUE if x is not the smallest tuple produced by <subquery>
• Example:
SELECT *
FROM subject
WHERE credit >= ALL (SELECT credit FROM subject);
24
1.2. Sub-queries: Example
SELECT *
subject
subject_id name credit perc…
FROM subject
IT1110 Tin học đại cương 4 60
WHERE credit > ANY(SELECT credit
IT3080 Mạng máy tính 3 70 FROM subject);
result
IT3090 Cơ sở dữ liệu 3 70 subject_id name credit perc…
IT4857 Thị giác máy tính 3 60 IT1110 Tin học đại cương 4 60
IT4866 Học máy 2 70 IT3080 Mạng máy tính 3 70
IT3090 Cơ sở dữ liệu 3 70
SELECT * IT4857 Thị giác máy tính 3 60
FROM subject
WHERE credit >= ALL(SELECT credit FROM subject);
result
subject_id name credit perc…
IT1110 Tin học đại cương 4 60
25
1.2. Sub-queries: Subquery in FROM Clause
• Subquery is used as a relation in a FROM clause
• Must give it a tuple-variable alias
• Eg.: List of lecturers teaching subject whose id is 'IT3090'
SELECT l.*
FROM lecturer l,
(SELECT lecturer_id
FROM teaching
WHERE subject_id = 'IT3090') lid
WHERE l.lecturer_id = lid.lecturer_id
26
1.3. Union, Intersection and Difference of Queries
27
1.4. Aggregation Operators
28
1.4. Aggregation Operators: Functions
• Aggregate functions: MAX, MIN, SUM, AVG, COUNT
• Functions applying on individual tuples:
• Mathematic functions: ABS, SQRT, LOG, EXP, SIGN, ROUND, ..
• String functions: LEN, LEFT, RIGHT, MID,…
• Date/Time functions: DATE, DAY, MONTH, YEAR, HOUR, MINUTE, …
• Format modification: FORMAT
• Remark:
• In general, common functions are similar between different DBMSs,
• Some functions have different formats or names,… especially for date, time
and string data types è See documentations for each DBMS
29
1.4. Aggregation Operators: Functions
• Example
SELECT sjid, name, MIN(score), MAX(score), AVG(score), stddev_pop(score)
FROM (SELECT student_id sid, e.subject_id sjid, name,
(midterm_score*(1-1.0*percentage_final_exam/100)+
final_score*1.0*percentage_final_exam/100) score
FROM enrollment e, subject sj
WHERE sj.subject_id = e.subject_id) AS t
result
WHERE upper(sjid) LIKE 'IT%'
sjid name min max avg stddev
GROUP BY sjid, name; IT1110 Tin học đại cương 5.4 8.7 7.05 1.254
IT3080 Mạng máy tính
IT3090 Cơ sở dữ liệu 8.1 8.1 8.1 0
IT4857 Thị giác máy tính 8.25 8.25 8.25 0
IT4866 Học máy 8.4 8.4 8.4 0
30
1.4. NULL's ignored in Aggregation
• NULL: no contribution
• no non-NULL values in a column è the result: NULL
– Exception: COUNT of an empty set is 0
subject
SELECT AVG(percentage_final_exam)
subject percentage_
FROM subject; è 64=(60x2+70x3)/5 _id
name credit
final_exam
IT1110 Tin học đại cương 4 60
SELECT AVG(percentage_final_exam), IT3080 Mạng máy tính 3 70
count(percentage_final_exam)
IT3090 Cơ sở dữ liệu 3 70
FROM subject
IT4857 Thị giác máy tính 3 60
WHERE subject_id NOT LIKE 'IT%';
IT4866 Học máy 2 70
result
LI0001 life's happy song 5
AVG COUNT
NULL 0 LI0002 %life's happy song 2 5
31
1.5. Grouping results
student
student_id first_name last_name … gender … clazz_id
• Syntax: 20160001 Ngọc An Bùi … M …
SELECT ... 20160002 Anh Hoàng … M … 20162101
FROM ... 20160003 Thu Hồng Trần … F … 20162101
32
1.5. Grouping results
33
1.5. Grouping results: HAVING
• Syntax:
SELECT ...
FROM ...
[WHERE condition]
GROUP BY expr [,expr]...
HAVING <condition on group>
• Example:
SELECT clazz_id, count(student_id) 4
FROM student result
WHERE gender = 'F'
1 clazz_id count
GROUP BY clazz_id 2 20162101 2
HAVING count(student_id) >= 2; 3
34
1.5. Grouping results: HAVING
• Requirements on HAVING conditions:
• Anything goes in a subquery
• Outside subqueries, they may refer to attributes only if they are:
• either a grouping attribute
• or aggregated
35
1.5. Grouping results: HAVING
36
1.6. Controlling the output: Eliminating Duplicates
37
1.6. Controlling the output: Eliminating Duplicates in
an Aggregation
38
1.6. Controlling the output: Ordering results
SELECT ...
FROM ...
[WHERE condition]
[GROUP BY expr [,expr]... ]
[HAVING …]
ORDER BY {expr|position} [ASC|DESC]
[{,expr|position}[ASC|DESC] 1
39
1.6. Controlling the output: Ordering results
• Example:
40
View
1. View definition
2. Accessing views
3. Updatable views
4. Materialized views
41
2.1. View definition
• A view is a relation defined in terms of stored tables (called base tables)
and other views
• Two kinds:
• Virtual = not stored in the database; just a query for constructing the
relation
• Materialized = actually constructed and stored
• Declaring views:
CREATE [MATERIALIZED] VIEW <name> AS <query>;
• Default is virtual
42
2.1. View definition: View Removal
• Dropping views: DROP VIEW <name>;
DROP VIEW female_student;
• Affection:
• Deleting the definition of views: the female_student view no longer exists
• No tuples of the base relation (student relation) is affected
43
2.2. Accessing views
• Declare:
CREATE VIEW monitor AS
SELECT student_id, first_name, last_name, dob, clazz_id
FROM student, clazz
WHERE student_id = monitor_id ;
• Query a view as if it were a base table
SELECT student_id, first_name, last_name, dob
FROM monitor
WHERE clazz_id = '20172201' ;
• A limited ability to modify views
44
2.3. Updatable views
• The SQL rules are complex
• They permit modifications on views that are defined by selecting (using SELECT,
not SELECT DISTINCT) some attributes from one relation R (which may itself be
an updatable view):
• The WHERE clause must not involve R in a subquery
• The FROM clause can only consist of one occurrence of R and no other
relation
• The list in the SELECT clause must include enough attributes that for every
tuple inserted into the relation R (other attributes filled with NULL values or
the proper default)
- There is no GROUP BY clause
45
2.3. Updatable views: Example
46
2.3. Updatable views: Example
• Delete from views:
DELETE FROM female_student WHERE first_name LIKE '%An' ;
means
DELETE FROM student
WHERE first_name LIKE '%An' AND gender = 'F';
• Update views:
UPDATE female_student SET first_name = 'Hoài Ân'
WHERE first_name = 'Hoai An' ;
means
UPDATE student SET first_name = 'Hoài Ân'
WHERE first_name = 'Hoai An' AND gender = 'F';
47
2.3. Updatable views: Views and INSTEAD OF
trigger
• Generally, it is impossible to modify a virtual view, because it doesn’t exist.
• But an INSTEAD OF trigger (next lesson) lets us interpret view
modifications in a way that makes sense
CREATE TRIGGER delete_viewtrigger
INSTEAD OF DELETE ON monitor
FOR EACH ROW
BEGIN
UPDATE clazz SET monitor_id = NULL
WHERE clazz_id = OLD.clazz_id;
END;
48
2.4. Materialized Views
• Results of a query can be stored
• Problems:
• each time a base table changes, the materialized view may change
• Solutions:
• Periodic reconstruction (REFRESH) of the materialized view
• Triggers (next lesson)
49
Privileges and User Management in SQL
1. Privileges
2. Creating users
3. Granting privileges
4. Revoking privileges
50
3.1. Privileges
• SELECT, INSERT, DELETE, UPDATE: privileges on table/view
• REFERENCES: privilege on a relation; the right to refer to that relation in an
integrity constraint
• USAGE: the right to use that element in one’s own declarations
• TRIGGER: privilege on a relation; the right to define triggers on that relation
• EXECUTE: the right to execute a piece of code, such as a procedure or
function
• UNDER: the right to create subtypes of a given type
51
3.2. Creating users
• Syntax: variations in different database platforms
• Creating an user in Oracle, MySQL:
CREATE USER username IDENTIFIED BY password;
• Creating an user in PostgreSQL:
CREATE USER username
[[WITH] options] PASSWORD password;
• Deleting:
DROP USER username [CASCADE];
• Example:
CREATE USER toto IDENTIFIED BY pwdtoto
52
3.3. Granting privileges
• Syntax:
GRANT <privilege list> ON <database element> TO <user list>
[WITH GRANT OPTION] ;
• <privilege list> : INSERT, SELECT, …, ALL PRIVILEGES
• <database element>: a table, a view
• WITH GRANT OPTION:
• the user may grant the privilege to other user
• Example:
GRANT SELECT, INSERT ON student TO tom WITH GRANT OPTION;
53
3.4. Revoking privileges
• Syntax:
REVOKE <privilege list> ON <database element> FROM <user list>
[CASCADE| RESTRICT] ;
• CASCADE : revoke any privileges that were granted only because of the
revoked privileges
• RESTRICT: the revoke statement cannot be executed if the revoked privileges
have been passed on to others
REVOKE GRANT OPTION FOR …..; : remove the grant option
• Example:
REVOKE INSERT ON student FROM tom CASCADE;
54
Remark
• Complex query
• Clauses in SQL statement are not exchangeable
• A SQL statement executed successfully, it's not sure that this
statement provides the correct result
• A query provides correct result at a moment, it may not the correct
query for a demand
• Be careful with "natural join"
• Virtual vs. materialized view
• Privileges and User Management
• Superuser account is not for everybody
• An user no need to access all database objects
55
Quiz 1.
OX Example Select
Quiz Number 1 Quiz Type
56
Quiz 2.
OX Example Select
Quiz Number 2 Quiz Type
We must always have join conditions if there are more than one relation in
Question FROM clause ?
A. Yes
Example
B. No
Answer B
No, it is as cross join (called a Cartesian product), but the product by itself
Feedback is rarely a useful operation
57
Quiz 3.
Quiz Number 3 Quiz Type
OX Example Select
Can we put the condition in HAVING clause into the WHERE clause ?
Question
A. Sometimes yes
Example B. No, never
C. Yes, we can
Answer A
Conditions in HAVING clause and in WHERE clause are not the same
meaning. Conditions in HAVING clause apply to groups as a whose.
Conditions in WHERE clause apply to individual tuples.
- If condition in HAVING clause refers to grouping attribute, then this
Feedback condition can be placed in WHERE clause.
- If condition in HAVING clause refers to aggregated attributes, it can not
be moved to WHERE clause.
58
Quiz 4.
OX Example Select
Quiz Number 4 Quiz Type
A. Empty relation
B. List of student_ids that have enrolled both two subjects IT3090 and
Example IT4859.
C. List of student_ids that have enrolled at least one subject whose subject
_id is IT3090 or IT4859
Answer A
The condition in WHERE clause is always false.
Feedback
59
Summary
• Data manipulation (part 2)
• Joins operators
• Subqueries: in FROM clause and in WHERE clause
• Aggregation operators
• Grouping and aggregation in SQL , conditions in HAVING clause
• Controlling the output: duplicate elimination, ordering the result
• View
• View definition
• View accessing
• Updatable view
• Materialized view
• Privileges and User Managements
• Privileges
• Creating user
• Granting / Revoking privileges
Thank you for
your attention!
61