DB Systems - Chapter 4 - SQL Language - Used
DB Systems - Chapter 4 - SQL Language - Used
Database Systems
(CO2013)
Computer Science Program
Assoc. Prof. Dr. Võ Thị Ngọc Châu
([email protected])
Semester 1 – 2022-2023
Content
Chapter 1: An Overview of Database Systems
2
Chapter 4: The SQL Language
4.1. Introduction to the SQL language
4.2. DDL
4.3. DML
4.4. DCL
4.5. Stored Functions
4.6. Stored Procedures
4.7. Triggers
3
Main References
Text:
[1] R. Elmasri, S. R. Navathe, Fundamentals of Database
Systems- 6th Edition, Pearson- Addison Wesley, 2011.
R. Elmasri, S. R. Navathe, Fundamentals of Database Systems- 7th
Edition, Pearson, 2016.
References:
[1] S. Chittayasothorn, Relational Database Systems: Language,
Conceptual Modeling and Design for Engineers, Nutcha Printing Co.
Ltd, 2017.
[3] A. Silberschatz, H. F. Korth, S. Sudarshan, Database System
Concepts – 7th Edition, McGraw-Hill, 2020.
[4] H. G. Molina, J. D. Ullman, J. Widom, Database Systems: The
Complete Book - 2nd Edition, Prentice-Hall, 2009.
[5] R. Ramakrishnan, J. Gehrke, Database Management Systems – 4th
Edition, McGraw-Hill, 2018.
[6] M. P. Papazoglou, S. Spaccapietra, Z. Tari, Advances in Object-
Oriented Data Modeling, MIT Press, 2000.
[7]. G. Simsion, Data Modeling: Theory and Practice, Technics
Publications, LLC, 2007. 4
Introduction to the SQL language
True T F U True F
False F F F False T
Unknown U F U Unknown U
True T T T X: True,
False T F U False,
Unknown T U U Unknown
11
Introduction to the SQL language
Data Definition Language (DDL)
CREATE, ALTER, DROP
Data Manipulation Language (DML)
For queries: SELECT
For data modifications: INSERT, DELETE, UPDATE
Data Control Language (DCL)
For access control: GRANT, REVOKE
For transaction control: COMMIT, ROLLBACK,
SET AUTOCOMMIT OFF
SQL: case-insensitive, extended in DBMSs 12
SQL
Simplified
SQL
Statements
(Checked
with each
DBMS)
13
Source: [1]
Data Definition Language
Purpose
Create, modify, and remove the constructs at the
structure level of a database
Named constructs
Database (schema), tables, types, domains,
constraints, indexes, views, assertions, triggers, …
DDL statements
CREATE
DROP
ALTER
14
CREATE SCHEMA
Starting with SQL2, a schema is defined to group
together tables and other constructs that belong to
the same database application.
tables, types, constraints, views, domains, indexes,
authorization grants, etc.
A catalog is a named collection of schemas.
Database installations typically have a default environment
and schema, so when a user connects and logs in to that
database installation, the user can refer directly to tables
and other constructs within that schema without having to
specify a particular schema name.
In a catalog, a special schema is INFORMATION_SCHEMA,
which provides information on all the schemas in the catalog
and all the element descriptors in these schemas.
Schemas within the same catalog can also share certain
elements, such as type and domain definitions. 15
DBMS-dependent
- MySQL
CREATE SCHEMA + PostgreSQL
...
the structure
of the whole (Relational
database for a database
community of schema)
users
the physical
storage
structure of the
database
- Conceptual schema in the three-schema architecture ≠ the conceptual EER schema in design!!!
- Conceptual schema in the three-schema architecture is in fact the relational database schema.
- External Schemas are supported with CREATE VIEW. 17
NOTES on SCHEMAS
MySQL
CREATE SCHEMA = CREATE DATABASE
Concepts are equivalent to the standard.
MS SQL Server
CREATE DATABASE with more physical properties
Data/ log files
dbo (the default schema of the database owner) is a default schema
for each database to group objects of similar scope or ownership.
Oracle
CREATE DATABASE with more physical properties
Data/ log files
CREATE USER with a schema of the same name created by default
A user is an account through which we can log in to the database.
CREATE SCHEMA does not actually create a schema. Oracle
Database automatically creates a schema when a user is created.
This statement populates the schema (the one with the username)
with tables and views and grant privileges on those objects without
having to issue multiple SQL statements in multiple transactions. 18
CREATE TABLE
A base table is created and actually stored
as a file by a DBMS with CREATE TABLE.
The attributes in a base table are considered to
be ordered in the sequence in which they are
specified in the CREATE TABLE statement.
Rows (tuples) are not considered to be ordered
within a table (relation).
21
22
23
24
CREATE TABLE - CONSTRAINTS
Basic constraints are specified as part of
table creation.
Primary key
Foreign key (Referential integrity constraint)
UNIQUE
NOT NULL
Attribute defaults
Restrictions on attribute domains and other
constraints on individual tuples within a table
using the CHECK clause 25
CREATE TABLE - CONSTRAINTS
Primary key: specified only one for each table
CREATE TABLE DEPARTMENT (
DNAME VARCHAR(15),
DNUMBER INT PRIMARY KEY,
MGRSSN CHAR(9),
MGRSTARTDATE DATE
);
CREATE TABLE WORKS_ON (
ESSN CHAR(9),
PNO INT,
HOURS DECIMAL(3,1),
PRIMARY KEY (ESSN, PNO)
); 26
CREATE TABLE - CONSTRAINTS
Foreign key: specified for referential integrity
CREATE TABLE DEPARTMENT (
DNAME VARCHAR(15),
DNUMBER INT PRIMARY KEY,
MGRSSN CHAR(9),
MGRSTARTDATE DATE
);
DROP SCHEMA
DROP SCHEMA Company CASCADE;
DROP SCHEMA Company RESTRICT; 36
DROP Statement
DROP TABLE:
DROP TABLE Dependent CASCADE;
CASCADE: all such constraints, views, and other
elements that reference the table are dropped
automatically from the schema along with the
table itself.
DROP TABLE Dependent RESTRICT;
RESTRICT: dropped if it is not referenced in any
constraints, views, and other elements.
DROP TABLE DEPARTMENT RESTRICT;
ALTER TABLE:
COLUMN: ADD, MODIFY, DROP, …
CONSTRAINT: ADD, DROP, …
TABLE PROPERTIES
… 38
ALTER Statement
Add an attribute for keeping track of jobs of
employees to EMPLOYEE table in COMPANY schema
ALTER TABLE Company.Employee ADD (Job VARCHAR(12));
Job value for each existing row: default value
ALTER TABLE Company.Employee ADD (Job VARCHAR(12)
DEFAULT ‗EMPLOYEE‘);
What value does each existing row take for attribute Job if?
ALTER TABLE Company.Employee ADD (Job VARCHAR(12)
NOT NULL);
What happens to two or more existing rows if attribute Job
is not null and unique?
ALTER TABLE Company.Employee ADD (Job VARCHAR(12)
NOT NULL UNIQUE);
39
ALTER Statement
Drop a column: similarly to drop a table, CASCADE
or RESTRICT option must be specified
Foreign key
ALTER TABLE Works_on ADD CONSTRAINT ssn_fk
FOREIGN KEY (Ssn) REFERENCES Employee (Ssn)
ON DELETE CASCADE ON UPDATE CASCADE;
Default values
ALTER TABLE Employee ALTER COLUMN Dno SET DEFAULT 1;
Unique
ALTER TABLE Department ADD UNIQUE (Dname); 41
Data Definition Language
Drop a constraint
ALTER TABLE Works_on
DROP PRIMARY KEY;
//Oracle
ALTER TABLE Department
DROP UNIQUE (Dname);
table 1
SELECT a table or a scalar value
table 2
… statement
table n
44
SELECT Statement
[WHERE rowCondition]
[GROUP BY columnList]
[HAVING groupCondition]
45
SELECT Statement
Typical processing of a query block
Execution
Clause Meaning
order
Specifies and joins table(s)/ view(s) to
1 FROM
be used
2 WHERE Filters rows by row-level conditions
Source: [1] 47
SELECT Statement
For each project in Stafford, on which more than two employees
work, retrieve the project name and the number of employees
who work on that project in descending order of the project name.
GROUP BY PNAME
48
SELECT Statement
FROM PROJECT JOIN WORKS_ON ON PNUMBER=PNO
PNUMBER=PNO
49
SELECT Statement
FROM PROJECT JOIN WORKS_ON ON PNUMBER=PNO
Pname Pnumber Plocation Dnum Essn Pno Hours
ProductX 1 Bellaire 5 123456789 1 32.5
ProductX 1 Bellaire 5 453453453 1 20.0
ProductY 2 Sugarland 5 123456789 2 7.5
ProductY 2 Sugarland 5 453453453 2 20.0
ProductY 2 Sugarland 5 333445555 2 10.0
ProductZ 3 Houston 5 666884444 3 40.0
ProductZ 3 Houston 5 333445555 3 10.0
Computerization 10 Stafford 4 333445555 10 10.0
Computerization 10 Stafford 4 999887777 10 10.0
Computerization 10 Stafford 4 987987987 10 35.0
Reorganization 20 Houston 1 333445555 20 10.0
Reorganization 20 Houston 1 987654321 20 15.0
Reorganization 20 Houston 1 888665555 20 NULL
Newbenefits 30 Stafford 4 999887777 30 30.0
Newbenefits 30 Stafford 4 987987987 30 5.0
Newbenefits 30 Stafford 4 987654321 30 20.0 50
SELECT Statement
WHERE PLOCATION = ‗Stafford‘
Pname Pnumber Plocation Dnum Essn Pno Hours
ProductX 1 Bellaire 5 123456789 1 32.5
ProductX 1 Bellaire 5 453453453 1 20.0
ProductY 2 Sugarland 5 123456789 2 7.5
ProductY 2 Sugarland 5 453453453 2 20.0
ProductY 2 Sugarland 5 333445555 2 10.0
ProductZ 3 Houston 5 666884444 3 40.0
ProductZ 3 Houston 5 333445555 3 10.0
Computerization 10 Stafford 4 333445555 10 10.0
Computerization 10 Stafford 4 999887777 10 10.0
Computerization 10 Stafford 4 987987987 10 35.0
Reorganization 20 Houston 1 333445555 20 10.0
Reorganization 20 Houston 1 987654321 20 15.0
Reorganization 20 Houston 1 888665555 20 NULL
Newbenefits 30 Stafford 4 999887777 30 30.0
Newbenefits 30 Stafford 4 987987987 30 5.0
Newbenefits 30 Stafford 4 987654321 30 20.0 51
SELECT Statement
WHERE PLOCATION = ‗Stafford‘
Pname Pnumber Plocation Dnum Essn Pno Hours
Computerization 10 Stafford 4 333445555 10 10.0
Computerization 10 Stafford 4 999887777 10 10.0
Computerization 10 Stafford 4 987987987 10 35.0
Newbenefits 30 Stafford 4 999887777 30 30.0
Newbenefits 30 Stafford 4 987987987 30 5.0
Newbenefits 30 Stafford 4 987654321 30 20.0
52
SELECT Statement
GROUP BY PNAME
Pname Pnumber Plocation Dnum Essn Pno Hours
Computerization 10 Stafford 4 333445555 10 10.0
Group 1
Computerization 10 Stafford 4 999887777 10 10.0
Computerization 10 Stafford 4 987987987 10 35.0
Newbenefits 30 Stafford 4 999887777 30 30.0
Group 2 Newbenefits 30 Stafford 4 987987987 30 5.0
Newbenefits 30 Stafford 4 987654321 30 20.0
53
SELECT Statement
HAVING COUNT (*) > 2
Pname Pnumber Plocation Dnum Essn Pno Hours
Computerization 10 Stafford 4 333445555 10 10.0
Group 1
Computerization 10 Stafford 4 999887777 10 10.0
Computerization 10 Stafford 4 987987987 10 35.0
Newbenefits 30 Stafford 4 999887777 30 30.0
Group 2 Newbenefits 30 Stafford 4 987987987 30 5.0
Newbenefits 30 Stafford 4 987654321 30 20.0
54
SELECT Statement
SELECT PNAME, COUNT (*)
Pname Pnumber Plocation Dnum Essn Pno Hours
Computerization 10 Stafford 4 333445555 10 10.0
Group 1
Computerization 10 Stafford 4 999887777 10 10.0
Computerization 10 Stafford 4 987987987 10 35.0
Newbenefits 30 Stafford 4 999887777 30 30.0
Group 2 Newbenefits 30 Stafford 4 987987987 30 5.0
Newbenefits 30 Stafford 4 987654321 30 20.0
Pname COUNT(*)
Computerization 3
Newbenefits 3 55
SELECT Statement
ORDER BY PNAME DESC;
Pname COUNT(*)
Computerization 3
Newbenefits 3
Descending
order
Pname COUNT(*)
Newbenefits 3
Computerization 3
56
For each project in Stafford, on which more than two employees
work, retrieve the project name and the number of employees
who work on that project in descending order of the project name.
SELECT PNAME, COUNT (*)
FROM PROJECT JOIN WORKS_ON ON PNUMBER=PNO
WHERE PLOCATION = ‗Stafford‘
GROUP BY PNAME
HAVING COUNT (*) > 2
ORDER BY PNAME DESC;
Query Result
Pname COUNT(*)
Newbenefits 3
Computerization 3
Input Tables
57
Retrieve all the information of each employee who is with department 4
and salary > 25000 or with department 5 and salary > 30000.
(Dno=4 AND Salary>25000) OR (Dno=5 AND Salary>30000)(EMPLOYEE)
SELECT *
FROM EMPLOYEE
WHERE (Dno = 4 AND Salary > 25000) OR (Dno = 5 AND SALARY > 30000);
* (asterisk): all columns in the previous process are included in the output.
The primary key in the output => the output is a set (relation). 58
Retrieve Ssn, date of birth, and
department number of each employee.
Ssn, Bdate, Dno (EMPLOYEE)
FROM DEPARTMENT
Administration4 CROSS JOIN
987654321 DEPT_LOCATIONS;
1995-01-01 5 Houston
Headquarters 1 888665555 1981-06-19 1 Houston
Headquarters 1 888665555 1981-06-19 4 Stafford
Headquarters 1 888665555 1981-06-19 5 Bellaire
Headquarters 1 888665555 1981-06-19 5 Sugarland
60
Headquarters 1 888665555 1981-06-19 5 Houston
Return all the combinations of Research department with Houston location.
DEPARTMENT Dname = ‘Research’ AND Dlocation = ‘Houston’ DEPT_LOCATIONS
SELECT *
FROM DEPARTMENT, DEPT_LOCATIONS;
WHERE Dname = ‗Research‘ AND Dlocation = ‗Houston‘;
SELECT *
FROM DEPARTMENT CROSS JOIN DEPT_LOCATIONS;
WHERE Dname = ‗Research‘ AND Dlocation = ‗Houston‘; 61
Retrieve all the information of each department and its locations.
DEPARTMENT Dnumber = Dnumber DEPT_LOCATIONS
SELECT *
FROM DEPARTMENT d, DEPT_LOCATIONS dl;
WHERE d.Dnumber = dl.Dnumber;
SELECT *
FROM DEPARTMENT d CROSS JOIN DEPT_LOCATIONS dl;
WHERE d.Dnumber = dl.Dnumber;
SELECT *
FROM DEPARTMENT d JOIN DEPT_LOCATIONS dl ON d.Dnumber = dl.Dnumber;
SELECT *
FROM DEPARTMENT NATURAL JOIN DEPT_LOCATIONS;
63
Return the information of all the employees and their departments they manage.
EMPLOYEE Ssn = Mgr_ssn DEPARTMENT
Fname Minit Lname Ssn B Address Sex Salary Super_ Dno Dname Dnumber Mgr_ Mgr_
date ssn ssn start_
date
Franklin T Wong 33344 1955 638 M 40000 888665 5 Resear 5 33344 1988-
5555 -12- Voss, 555 ch 5555 05-22
08 Houst
on, TX
Jennifer S Wallace 98765 1941 291 F 43000 888665 4 Admini 4 98765 1995-
4321 -06- Berry, 555 stration 4321 01-01
20 Bellair
e, TX
James E Borg 88866 1937 450 M 55000 NULL 1 Headqu 1 88866 1981-
5555 -11- Stone, aters 5555 06-09
10 Houst
on, TX
SELECT *
FROM EMPLOYEE, DEPARTMENT;
WHERE Ssn = Mgr_ssn;
SELECT *
FROM EMPLOYEE CROSS JOIN DEPARTMENT;
WHERE Ssn = Mgr_ssn;
SELECT *
FROM EMPLOYEE JOIN DEPARTMENT ON Ssn = Mgr_ssn;
64
Return the information of all the employees and their departments that they manage if any.
EMPLOYEE Ssn = Mgr_ssn DEPARTMENT
Fname Minit Lname Ssn B Address Sex Salary Super_ Dno Dname Dnumber Mgr_ Mgr_
date ssn ssn start_
date
Franklin T Wong 3334 1955 638 M 40000 888665 5 Resear 5 3334 1988-
4555 -12- Voss, 555 ch 4555 05-22
5 08 Houst 5
on, TX
Jennifer S Wallace 9876 1941 291 F 43000 888665 4 Admini 4 9876 1995-
5432 -06- Berry, 555 stration 5432 01-01
1 20 Bellair 1
e, TX
James E Borg 8886 1937 450 M 55000 NULL 1 Headqu 1 8886 1981-
6555 -11- Stone, aters 6555 06-09
5 10 Houst 5
on, TX
John B Smith 1234 1965 732 M 30000 333445 5 NULL NULL NULL NULL
5678 -01- Fondre 555
9 09 n,
Houst
on, TX
Alicia J Zelaya 9997 … … … … … 4 NULL NULL NULL NULL
7888
8
Ramesh K Narayan … … … … … … 5 NULL NULL NULL NULL
Joyce A English … … … … … … 5 NULL NULL NULL NULL
Ahmad V Jabbar … … … … … … 4 NULL NULL NULL NULL
SELECT *
FROM EMPLOYEE LEFT OUTER JOIN DEPARTMENT ON Ssn = Mgr_ssn; 65
SEMI-JOIN: T1 T1.X=T2.Y T2
Return the information of all the departments with at least one employee
who has salary > 30000.
DEPARTMENT Dnumber=Dno (Salary>30000(EMPLOYEE))
SELECT *
FROM DEPARTMENT
WHERE Dnumber IN (SELECT Dno FROM EMPLOYEE WHERE Salary > 30000);
SELECT * SEMI-JOIN
(Oracle, MySQL, …)
FROM DEPARTMENT d
(DBMS-specific implementation)
WHERE EXISTS
(SELECT * FROM EMPLOYEE WHERE Dno = d.Dnumber AND Salary > 30000);
66
EXISTS vs. NOT EXISTS
EXISTS function returns TRUE or FALSE.
TRUE: if the nested query result contains at least one tuple
List Ssn and name of each manager who has at least one dependent.
Return the information of all the employees who do not work in any
department which was managed since 1990.
SELECT *
FROM EMPLOYEE
WHERE Dno NOT IN ( SELECT Dnumber
FROM DEPARTMENT
WHERE Mgr_start_date >= ‗1990-01-01‘);
69
IN vs. NOT IN
IN: comparison operator, which compares a value v
with a set (or multiset) of values V and evaluates to
TRUE if v is one of the elements in V.
V: a nested query or an explicit set
= ANY (or = SOME) operator: equivalent to IN operator
T1 = Y(R)
T2 = Y(T1 x S – R)
T = T1 – T2
CREATE TABLE T1 AS
SELECT DISTINCT ESSN
FROM SSN_PNOS;
CREATE TABLE T2 AS
SELECT DISTINCT ESSN
FROM ( SELECT * FROM T1, SMITH_PNOS
MINUS
SELECT * FROM SSN_PNOS);
Smith‘s projects
SELECT * FROM T1
MINUS
SELECT * FROM T2; 77
AGGREGATION: <a grouping attribute list> ℑ <function list> (R)
82
SELECT Statement –
More Comparison Operators
=, >, >=, <, <=, <>, BETWEEN
ANY, SOME, ALL
The comparison condition (v > ALL V) returns TRUE if the
value v is greater than all the values in the set (or multiset) V.
Retrieve Ssn, Fname, Lname, and Salary of each employee whose salary is
greater than the salary of all employees in department 5.
SELECT Ssn, Fname, Lname, Salary
FROM EMPLOYEE
WHERE Salary > ALL (SELECT Salary FROM Employee WHERE Dno=5);
84
SELECT Statement –
Nested Queries
Nested queries: complete [select-from-where-…] query blocks
within another query which is called the outer query.
These nested queries can also appear in the WHERE clause or
the FROM clause or the SELECT clause or other SQL clauses as
needed.
If a nested query returns a single attribute and a single tuple,
the result will be a single (scalar) value. In such cases, it is
permissible to use = instead of IN for the comparison operator.
In general, the nested query will return a table, which is a set
or multiset of tuples.
SQL allows the use of tuples of values in comparisons by
placing them within parentheses.
List the name of the department where Smith works.
SELECT Dname
FROM DEPARTMENT
WHERE Dnumber IN (SELECT Dno FROM EMPLOYEE WHERE Lname = ‗Smith‘);
85
SELECT Statement –
Nested Queries
Retrieve Ssn, name, and address of all employees whose salary is greater
than the average salary of the employees in 'Research' department.
SELECT SSN, FNAME, LNAME, ADDRESS
FROM EMPLOYEE
WHERE SALARY > (SELECT AVG(SALARY)
FROM EMPLOYEE
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research'));
For each department that has more than two employees, retrieve the
department number and the number of its employees who are making
more than $30,000.
SELECT Dno, count(*) ENumber
FROM EMPLOYEE
WHERE Salary>30000 AND Dno IN (SELECT Dno
FROM EMPLOYEE
GROUP BY Dno
HAVING count(*) > 2)
86
GROUP BY Dno;
SELECT Statement –
Correlated Nested Queries
If a condition in the WHERE-clause of a nested query references
an attribute of a relation declared in the outer query, the two
queries are said to be correlated.
A correlated query is the query where the nested query is
evaluated once for each tuple (or combination of tuples) in the
outer query.
List Ssn, name, and department number of each employee who has the salary
greater than the average salary of the employees in his/her department.
FROM EMPLOYEE E
FROM EMPLOYEE
Retrieve Ssn and name of each employee who has two or more
dependents.
90
INSERT Statement
A second form of the INSERT statement
allows the user to specify explicit attribute
names that correspond to the values
provided in the INSERT command.
This is useful if a relation has many attributes
but only a few of those attributes are
assigned values in the new tuple.
The values must include all attributes with NOT
NULL specification and no default value.
Attributes with NULL allowed or DEFAULT values
are the ones that can be left out.
91
INSERT Statement
92
INSERT Statement
INSERT INTO EMPLOYEE (Fname, Lname, Dno)
VALUES (‗Jack‘, ‗Sparrow‘, 1);
Error Code: 1364. Field 'SSN' doesn't have a default value
? COMPARED with:
CREATE TABLE D5EMPS AS
SELECT *
FROM EMPLOYEE
WHERE Dno = 5; 96
DELETE Statement
The DELETE command removes tuples from a relation.
It includes a WHERE clause, similar to that used in an
SQL query, to select the tuples to be deleted.
Tuples are explicitly deleted from only one table at a
time. However, the deletion may propagate to tuples
in other relations if referential triggered actions are
specified in the referential integrity constraints of the
DDL.
A missing WHERE clause specifies that all tuples in the
relation are to be deleted; however, the table remains
in the database as an empty table.
The DROP TABLE command is used to remove the table definition.
97
DELETE Statement
Remove from EMPLOYEE table the details of the employees whose last
name is Brown.
DELETE FROM EMPLOYEE
How many rows are deleted?
WHERE LNAME='Brown';
Is any constraint violated?
Remove from EMPLOYEE table the details of the employee whose SSN is
123456789.
DELETE FROM EMPLOYEE
WHERE SSN='123456789';
Remove from EMPLOYEE table the details of all the employees who work in
Research department.
DELETE FROM EMPLOYEE
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME = 'Research');
UPDATE PROJECT
SET PLOCATION = 'Bellaire', DNUM = 5
WHERE PNUMBER=10;
UPDATE WORKS_ON
SET HOURS = HOURS + 2
WHERE ESSN IN (SELECT DISTINCT SSN
FROM EMPLOYEE
WHERE DNO = 1); 100
Data Control Language -
Access Control
Database access control: restricting data
access and database activities, e.g. restrict
users from querying specified tables or
executing specified database statements.
Privilege: the right to perform some action,
e.g. run specific SQL statements.
User: an account through which you can
log in to the database, and to establish the
means by which Oracle Database (DBMS)
permits access by the user
Role: a named set of privileges that can be
granted to users or to other roles 101
Data Control Language -
Access Control
Privilege categories
System privilege
This is the right to perform a specific action in the
database, or perform an action on any objects of a
specific type. For example, CREATE USER and CREATE
SESSION are system privileges.
Object privilege
This is the right to perform a specified action on an
object, for example, query the employees table.
Privilege types are defined by the database.
Source: Oracle 19c - Real Application Security Administrator's and Developer's Guide 102
Oracle Database Real Application
Security Components – Oracle 19c
Grant the UPDATE, INSERT, and DELETE object privileges for all
columns of the EMPLOYEE table to the user psmith.
GRANT UPDATE, INSERT, DELETE ON EMPLOYEE TO psmith;
The WITH GRANT OPTION clause with the GRANT statement can
enable a grantee, psmith, to grant object privileges to other users.
GRANT SELECT ON EMPLOYEE TO psmith WITH GRANT OPTION;
Revoke SELECT and INSERT privileges on the EMPLOYEE table from user psmith.
REVOKE SELECT, INSERT ON EMPLOYEE FROM psmith;
Revoke all object privileges for DEPARTMENT table that was originally granted to
the human_resources role.
REVOKE ALL ON DEPARTMENT FROM human_resources;
Source: Oracle 19c – Oracle Database Security Guide 105
GRANT and REVOKE Statements
-- from user 'root'@'localhost'
CREATE USER 'chau2'@'localhost' IDENTIFIED BY 'chau2';
select *
from department
where dept_count (dname) > 10;
112
Stored Functions
113
Source: a demonstration on MS SQL Server
Stored Functions
Return the department number, department name, and
average salary of each department of more than n employees.
create function dept_avg_salary (n int)
returns d_a_s TABLE (
dname varchar (15),
dnumber int,
avg_sal decimal (10,2)
)
begin
insert into d_a_s
select dname, dnumber, AVG(salary)
from employee join department on dno = dnumber
where dept_count(dname) > n
group by dnumber, dname;
return;
end
select *
from dept_avg_salary (2);
114
Stored Functions
115
Source: a demonstration on MS SQL Server
Stored Procedures
Given a department name, return the number of employees
who work for the corresponding department.
116
Source: a demonstration on MS SQL Server
Stored Procedures
Return the department number, department name, and
average salary of each department of more than n employees.
117
Source: a demonstration on MS SQL Server
Procedural language constructs
SQL supports constructs that gives it almost all the
power of a general-purpose programming language.
Warning: most database management systems implement
their own variant of the standard syntax.
Compound statement: begin … end,
Multiple SQL statements are given between begin and end.
Local variables can be declared within a compound
statements.
for, while and repeat statements
if, if … else … statements
case statements, …
Source: A. Silberschatz, H. F. Korth, S. Sudarshan, Database System Concepts –
118
6th Edition, McGraw-Hill, 2006.
Procedural language constructs
119
Source: a demonstration on MySQL
Procedural language constructs
120
Source: a demonstration on MySQL
Stored Procedures
Insert data of a new employee using 20000 if salary is <=0.
121
Source: a demonstration on MySQL
Stored Procedures
Insert data of a new employee using the average salary of
the department if no salary is specified (<=0).
122
Source: a demonstration on MS SQL Server
(DBMS-specific implementation)
Triggers
A trigger is a named database object that is
associated with a table, and that automatically
activates when a particular event occurs for the table.
Activation time
BEFORE or AFTER an event
INSTEAD OF an event
Event: INSERT, DELETE, UPDATE
Refer to columns in the table associated with the trigger by
using the aliases OLD (deleted) and NEW (inserted).
OLD.col_name: a column of an existing row before it is updated
or deleted
NEW.col_name: a column of a new row to be inserted or an
existing row after it is updated
123
Triggers
When to use triggers
Enforce application-based semantic constraints
Maintain summary data
Replicate databases by recording changes to other
special tables
When not to use triggers Cascading execution
Encapsulation facilities available for update (insert,
delete, update) methods with constraints
Materialized views available for maintaining
summary data
Built-in DBMS support ready to replicate databases
Source: A. Silberschatz, H. F. Korth, S. Sudarshan, Database System Concepts –
124
6th Edition, McGraw-Hill, 2006.
Triggers
DELIMITER $$
END $$
125
Source: a demonstration on MySQL
Triggers
Update the number of employees of the
department from which an employee is removed.
126
Source: a demonstration on MS SQL Server
Triggers
Check if a new employee is with the same
department as his/her supervisor before inserted.
127
Source: a demonstration on MS SQL Server
NOTES on Functions, Procedures,
and Triggers
128
Summary
SQL = Structured Query Language ANSI/ISO
Standard:
Data Definition Language SQL-86,
SQL-89,
Data Manipulation Language SQL-92,
SQL-1999,
Data Control Language SQL-2003,
SQL-2006,
Stored Functions SQL-2008,
Stored Procedures SQL-2011,
SQL-2016,
Triggers SQL-2019
MS SQL Server
MySQL
PostgreSQL
SQLite
… 130
Chapter 4: The SQL Language
131
Review
1. Given the Company database, write a
SELECT statement for each requirement:
1.1. Retrieve Ssn, name, and address of the employees who
work in department 5.
1.2. Retrieve Ssn, name, and address of the employees who
work in ‗Research‘ department.
1.3. Retrieve Ssn, name, and address of the employees who
work in departments in Houston.
1.4. Return the average salary of the employees who work in
department 1.
1.5. Return the maximum salary of the employees in each
department.
1.6. Return the number of the employees who have salaries
greater than the average salary of the employees who work in
department 1. 132
Review
1. Given the Company database, write a
SELECT statement for each requirement:
1.7. For every project located in ‗Stafford‘, list the project
number, the controlling department number, and the
department manager‘s last name, address, and birth date.
1.8. Find the names of employees who work on all the
projects controlled by department number 5.
1.9. Make a list of project numbers for projects that involve
an employee whose last name is ‗Smith‘, either as a worker
or as a manager of the department that controls the project.
1.10. List the names of all employees with two or more
dependents in department 5.
1.11. Retrieve the names of employees who have no
dependents.
133
Review
1. Given the Company database, write a
SELECT statement for each requirement:
1.12. List the names of managers who have at least one
dependent.
1.13. Retrieve the names of all employees in department
5 who work more than 10 hours per week on the ProductX
project.
1.14. List the names of all employees who have a
dependent with the same first name as themselves.
1.15. Find the names of all employees who are directly
supervised by ‗Franklin Wong‘.
1.16. For each project, list the project name and the total
hours per week (by all employees) spent on that project.
1.17. Retrieve the names of all employees who work on
every project. 134
Review
1. Given the Company database, write a
SELECT statement for each requirement:
1.18. Retrieve the names of all employees who do not work
on any project.
1.19. For each department, retrieve the department name
and the average salary of all employees working in that
department.
1.20. Retrieve the average salary of all female employees.
1.21. Find the names and addresses of all employees who
work on at least one project located in Houston but whose
department has no location in Houston.
1.22. List the last names of all department managers who
have no dependents.
1.23. List the department name, the number of projects,
and the number of employees of each department that
controls those projects in the same location. 135
Review
2. For the Company database, write a DML
statement for each requirement. Is any constraint
violated?
2.1. Insert <‗Robert‘, ‗F‘, ‗Scott‘, ‗943775543‘, ‗1972-06-21‘,
‗2365 Newcastle Rd, Bellaire, TX‘, M, 58000, ‗888665555‘,
1> into EMPLOYEE.
2.2. Insert <‗ProductA‘, 4, ‗Bellaire‘, 2> into PROJECT.
2.3. Insert <‗Production‘, 4, ‗943775543‘, ‗2007-10-01‘> into
DEPARTMENT.
2.4. Insert <‗677678989‘, NULL, ‗40.0‘> into WORKS_ON.
2.5. Insert <‗453453453‘, ‗John‘, ‗M‘, ‗1990-12-12‘,
‗spouse‘> into DEPENDENT.
2.6. Delete the WORKS_ON tuples with Essn = ‗333445555‘.
2.7. Delete the EMPLOYEE tuple with Ssn = ‗987654321‘.
2.8. Delete the PROJECT tuple with Pname = ‗ProductX‘.
2.9. Delete the DEPARTMENT tuple with Dname =
‗Administration‘. 136
Review
2. For the Company database, write a DML
statement for each requirement. Is any constraint
violated?
2.10. Modify the Mgr_ssn and Mgr_start_date of the
DEPARTMENT tuple with Dnumber = 5 to ‗123456789‘ and
‗2007-10-01‘, respectively.
2.11. Modify the Super_ssn attribute of the EMPLOYEE tuple
with Ssn = ‗999887777‘ to ‗943775543‘.
2.12. Modify the Hours attribute of the WORKS_ON tuple
with Essn = ‗999887777‘ and Pno = 10 to ‗5.0‘.
2.13. Modify the Dname attribute of the DEPARTMENT tuple
with Dname = ‗Administration‘ to ‗Headquarters‘.
2.14. Modify the Salary attribute of the EMPLOYEE tuples
with the average salary of the department ‗Research‘ where
the salary of its manager is 10% higher.
2.15. Modify the Dno attribute of the EMPLOYEE tuples with
Dno = 1 to Dno = 2. 137
Review
3. Given the
relational schema of
the LIBRARY
database, write DDL
statements to
implement this
schema with any
assumption needed
for data types and
constraints. 138
Review
4. Write SQL statements on the LIBRARY database in question 3.
4.1. Add an ISBN attribute of varchar(13) into BOOK relation schema where
ISBN is a secondary key.
4.2. How many copies of the book titled The Lost Tribe are owned by the
library branch whose name is ‗Sharpstown‘?
4.3. How many copies of the book titled The Lost Tribe are owned by each
library branch?
4.4. Retrieve the names of all borrowers who do not have any books checked
out.
4.5. For each book that is loaned out from the Sharpstown branch and whose
Due_date is today, retrieve the book title, the borrower‘s name, and the
borrower‘s address.
4.6. For each library branch, retrieve the branch name and the total number
of books loaned out from that branch.
4.7. Retrieve the names, addresses, and number of books checked out for all
borrowers who have more than five books checked out.
4.8. For each book authored (or coauthored) by Stephen King, retrieve the
title and the number of copies owned by the library branch whose name is
Central. 139
Review
5. Write stored functions to process the data in
the LIBRARY database as follows:
5.1. Return ISBN and book title of each book
available in every library branch.
143