Uploaded by r11522812

ML111 Lecture 4 Basic SQL

advertisement
Lecture 4 Basic SQL
Ming-Ling Lo
20220314
High-Level Concepts
about SQL
2
How Should We See SQL?
●
SELECT * FROM department
WHERE name = 'EE';
●
●
An important factor of the success of
Relational DB
Name:
○
○
●
An Interface to Relational Database
○
○
●
Originally: SEQUEL (Structured English
Query Language) - But violate trademark
Now: SQL (Structured Query Language)
A language for defining relational database
model (DDL)
A language for access relational database
(DML)
An important tool for DBMS management
Important characteristics
○
○
○
○
●
●
●
A declarative language
A language with “life”: keep evolving
A language with many dialects
Borrowed from and extended to many
applications beyond RDB
We will present the “principles” of SQL
SQL you encounter in actual systems in
the future will all have small variations.
Other high level features
○
○
○
○
Integrity constraints
Transaction controls
Views on the database
Rules for embedding SQL statements into
a general-purpose programming language
3
Brief History of SQL
●
1970s
○
○
○
●
○
Commercial systems
Became ANSI and ISO standards in 1986
SQL-86 (SQL1)
1989
○
●
○
1986
○
○
●
SQL:1999 (SQL3)
1979 - early 1980+:
○
●
Invented at IBM research
By Donald Chamberlin and Raymond
Boyce
As the interface for the experimental
relationship database, SYSTEM-R
●
A minor improvement
SQL-92 (SQL2): add many features
Key versions SQL92 & SQL99 (SQL2 and SQL3)
○
Divided into core specification and
specialized extensions
Core: must implement to claim SQL
compliant.
■
Regular expression matching,
■
recursive queries (e.g. transitive
closure),
■
triggers,
■
Support for procedural and
control-of-flow statements (making
SQL functional complete)
Extensions: optional modules.
■
E.g. to support data mining, spatial
data, temporal data, data
warehousing, online analytical
processing (OLAP), multimedia
data, and so on.
4
Brief History of SQL (2)
●
SQL:2003:
○
○
○
○
●
XML-related features (SQL/XML),
Window functions,
standardized sequences,
Columns with auto-generated values
(including identity-columns).
SQL standards are in:
ISO/IEC 9075, ISO/IEC 19075
●
○
○
○
○
●
○
Importing and storing XML data in SQL DB
Manipulating XML within the DB
Publishing both XML and conventional
SQL-data in XML form.
Lets applications integrate queries into
SQL code with XQuery, to concurrently
access ordinary SQL-data and XML
documents.
●
Adds temporal support (PERIOD FOR)
Enhancements for window functions and
FETCH clause.
SQL:2016
○
●
Formalizes MERGE statement
Legalizes ORDER BY outside cursor
Adds INSTEAD OF triggers, TRUNCATE
FETCH clause in SELECT (retrieve from
offset)
SQL:2011 adds temporal support
○
○
SQL:2006: add XML feature
○
○
○
SQL:2008: add practical features
Adds row pattern matching, polymorphic table
functions, JSON.
SQL:2019 adds MD-array support
○
2021 revises "Guidance for the use of
database language SQL—Part8:
Multidimensional arrays" (MD-array type and
operators) - ISO/IEC 19075-8
5
Terminology: RDB vs SQL
Relational Model
SQL Terminology
Relation
Table
Tuple
Row
Attribute
Column
6
“Containers” of Relations
●
●
Where are relations (tables) stored?
Relations (Tables) are stored in
○
○
○
●
Databases
Database management systems
Computer / Servers
What are their relationships?
7
DB, DBMS Instances and Computers
Computer
Computer
Computer
Computer
DBMS
DB
DB
DB
DB
DB
DBMS
DB
DB
DBMS
DB
Questions: Why are there multiple databases in a DBMS?
8
Namespaces in Systems
System supports users.
User owns data, sees data, speaks of data
When are multi-users → issues of visibility, authorization
Units of data visibility, addressability, authorization →
namespace
How to handle this issue in RDBMS, DBMS?
9
Namespaces in SQL: SQL Schema
●
●
●
Early versions of SQL
○ Did not address the concept of relation namespace
○ One DBMS had one big namespace.
■ All tables (relations) were considered part of this one namespace (schema).
■ Every user can essentially see the same namespace
SQL2
○ Add SQL schema as a unit of namespace
○ To group together tables and other constructs that belong to the same application purposes
An SQL schema
○ Identified by a schema name
○ Owned by a specific group/user
○ Includes description for the schema (called metadata : data about data)
■ Definitions (and data) of tables, constraints, views, domains, authorizations, and
other constructs
○ Created via CREATE SCHEMA statement
10
SQL Catalog and Database
●
SQL catalog
○
A named collection of schemas in an SQL environment (DBMS instance)
○
Different schemas in the same catalog may be allowed to see each other when authorized.
■
●
Integrity constraints such as referential integrity can be defined between relations if they exist in
schemas within the same catalog.
■ Schemas within the same catalog can also share certain elements, such as domain definitions
○ CREATE CATALOG statement
SQL Database
○ A named collection of catalog of schemas
○ CREATE DATABASE statement
11
Databases, Catalogs, Schemas
●
●
The terms and concepts of database, catalog and schema have been used in
the database industry in a somewhat inconsistent and confusing way
For example, there are systems which
○
○
○
●
Implement only schema but not catalog, or
Use the term “database” and “catalog” interchangeably
Use the term “database” and “schema” interchangeably
But in general
○
DBMS instance > Database >= Catalog >= Schema > Relations/Tables
E.g.: MySQL
●
Only has database,
●
Database and schema are treated as
synonym
●
No mention of SQL catalog
12
Most Basic(Useful) SQL Commands
●
Understand your DBMS
●
○ Connect (to a DBMS server)
○ Help
○ Show databases;
Get to your database (namespace)
○
○
○
○
●
Create your DB schema (in database)
○
○
○
○
●
Create database/schema/catalog
Use database/schema/catalog
Drop database/schema/catalog
Show tables
Create table
Alter table
Drop table
Describe table
Access your data
○
Insert, delete, update, select
●
Most useful commands
○
○
○
○
○
○
○
○
○
○
○
Connect
Help
Show
Use
Create
Drop
Insert
Delete
Update
Select
Alter
13
Main “Verbs” in SQL
Sublanguage
objects
create/add
change
delete
read
DDL
Database
create
alter
drop
show
show create
DDL
Table, view
create
alter
drop
describe (explain)
show
Show create
DSL
Tablespace
, index
create
alter
drop
show
DML
Tuple
insert
update
delete
select
14
SQL
Data Definition Language
15
Create Database
Example:
CREATE {DATABASE | SCHEMA} [IF NOT
EXISTS] db_name
[create_option] ...
CREATE DATABASE STUDENT;
CREATE SCHEMA DEPT IF
NOT EXISTS;
create_option: [DEFAULT] {
CHARACTER SET [=] charset_name
| COLLATE [=] collation_name
| ENCRYPTION [=] {'Y' | 'N'}
}
As mentioned, create
database/schema/catalog vary among
systems. Here we use MySQL as
example
16
Create Table
●
CREATE TABLE PROJECT
( Pname VARCHAR(15) NOT NULL,
Pnumber INT NOT NULL,
Plocation VARCHAR(15),
Dnum INT NOT NULL,
PRIMARY KEY (Pnumber),
UNIQUE (Pname),
FOREIGN KEY (Dnum)
REFERENCES DEPARTMENT(Dnumber));
Mainly specify 4 things:
● Table name
● Attribute names
● Attribute domains
● Constraints
○ Immediately follow an
attribute definition
○ At the end of all attribute
definitions
17
Basic Data Types (for Attribute Domains)
●
Numeric
○
○
○
●
○
○
CHAR(n), CHARACTER(n)
Variable length string
■
VARCHAR(N), CHAR VARYING(n)
Character large object
■
CLOB(20M)
Literals: ‘Smith”, “Today ‘
Bit-string
○
○
○
○
BIT(n)
BIT VARYING(n)
Binary large object
■
BLOB(3M), BLOB(5G)
Literal: B’10101’
Boolean
○
○
●
●
BOOLEAN
Value: TRUE, FALSE, UNKNOWN
Date
○
○
○
Character-string
○
○
●
INTEGER, INT, SMALLINT
FLOAT, REAL, DOUBLE PRECISION
Formatted numbers
■
DECIMAL(i, j), DEC(i, j), NUMERIC(i, j)
●
DATE
YYYY-MM-DD
Literals: DATE’2018-03-24’
Time
○
○
○
○
○
TIME
HH:MM:SS
Literals: TIME’14:30:27’
TIME(i)
■
Fractional seconds
TIME WITH TIME ZONE
18
Additional Data Types
●
Timestamp
○
○
●
TIMESTAMP
■
TIMESTAMP’2008-09-27
09:12:47.648302’
TIMESTAMP WITH TIME ZONE
●
DATE, TIME, TIMESTAMP
○
○
Can be considered as special type of
string
Can be cast or coerced into equivalent
strings and operated with strings
Interval
○
○
YEAR/MONTH intervals
DAY/TIME intervals
19
User Defined Attribute Types: CREATE DOMAIN
●
●
CREATE DOMAIN PNUM_TYPE AS CHAR(9);
CREATE TABLE PROJECT
( Pname VARCHAR(15) NOT NULL,
Pnumber PNUM_TYPE NOT NULL,
Plocation VARCHAR(15),
Dnum INT NOT NULL,
PRIMARY KEY (Pnumber),
UNIQUE (Pname),
FOREIGN KEY (Dnum)
REFERENCES DEPARTMENT(Dnumber));
Not all DBMS support this!
(Mostly only supported by large
commercial DBMS)
MySQL (as of v8.0) does not
support this
20
Specifying Constraints in SQL
●
Attribute constraints:
○
○
●
●
Attribute type
Key Constraints
○
○
●
●
Unique
Primary key
Referential integrity constraints
Tuple-based constraints
○
●
NOT NULL, DEFAULT
Value (Column-based CHECK)
○
○
○
○
○
Domain constraints
Constraints on NULLs
Key constraints
Entity integrity constraints
Referential integrity
constraints
Column-based CHECK
Assertions statement
○
● Schema-based constraints
(CREATE TABLE)
Cross-table CHECK
● Semantic constraints in
(CREATE TABLE, assertion)
21
Attribute Constraints and Attribute Defaults
●
●
●
Attribute constraints
○ NOT NULL: specifies this attribute value cannot be NULL
○ CHECK clause
Attribute defaults: Default <value>
Example
CREATE TABLE PROJECT
( Pname VARCHAR(15) NOT NULL, Attribute constraint: not NULL
Pnumber INT NOT NULL,
Plocation VARCHAR(15) DEFAULT ‘TAIPEI’, Attribute defaults
Dnum INT NOT NULL CHECK (Dnum > 0 AND Dnum <21), Attribute constraint
PRIMARY KEY (Pnumber),
UNIQUE (Pname),
FOREIGN KEY (Dnum)
REFERENCES DEPARTMENT(Dnumber));
22
Attribute Constraints and Attribute Defaults (2)
●
The CHECK clause:
○
●
CHECK in CREATE TABLE
○
●
Limit the range of attribute values
When defining attribute
■ CREATE TABLE PROJECT (...
Dnum INT NOT NULL CHECK (Dnum > 0 AND Dnum <21), …);
CHECK in CREATE DOMAIN
○
○
For example,we can write the following statement:
CREATE DOMAIN D_NUM AS INTEGER CHECK (D_NUM > 0 AND D_NUM < 21 )
Note: CREATE DOMAIN is only supported in some of the systems
23
Specifying Key Constraints
●
PRIMARY KEY clause: specify primary key of a relation
○
○
○
●
If a primary key has a single attribute, the clause can follow the attribute directly.
Otherwise, it goes to the end of attribution definition section
For example,the primary key of PROJECT can be specified as follows Dnumber INT
PRIMARY KEY;
UNIQUE clause: specify secondary key of a relation
○
○
○
The UNIQUE clause can also be specified directly for a secondary key if the secondary key is
a single attribute,
Otherwise, it goes to the end of the attribution definition section
For example: Pname VARCHAR(15) UNIQUE;
24
Specifying Key Constraints (2)
●
Example
CREATE TABLE PROJECT
( Pname VARCHAR(15) NOT NULL,
Pnumber INT NOT NULL,
Plocation VARCHAR(15) DEFAULT ‘TAIPEI’,
Dnum INT NOT NULL CHECK (Dnum > 0
AND Dnum <21),
PRIMARY KEY (Pnumber),
UNIQUE (Pname),
FOREIGN KEY (Dnum)
REFERENCES DEPARTMENT(Dnumber));
●
Example
CREATE TABLE PROJECT
( Pname VARCHAR(15) UNIQUE NOT
NULL,
Pnumber INT PRIMARY KEY NOT NULL,
Plocation VARCHAR(15) DEFAULT ‘TAIPEI’,
Dnum INT NOT NULL CHECK (Dnum > 0
AND Dnum <21),
FOREIGN KEY (Dnum)
REFERENCES DEPARTMENT(Dnumber));
equivalent
25
Specifying Referential Integrity Constraints
●
●
FOREIGN KEY clause
Example
CREATE TABLE PROJECT
( Pname VARCHAR(15) NOT NULL,
Pnumber INT NOT NULL,
Plocation VARCHAR(15) DEFAULT ‘TAIPEI’,
Dnum INT NOT NULL CHECK (Dnum > 0 AND Dnum <21),
PRIMARY KEY (Pnumber),
UNIQUE (Pname),
FOREIGN KEY (Dnum)
REFERENCES DEPARTMENT(Dnumber));
What does this constraint
really regulate?
In what situation will this
command fails?
Does it affect other
commands?
26
Specifying Referential Integrity Constraints (2)
●
Table level integrity
○
●
Tuple level integrity
○
●
Affect create, alter and drop table commands
What happens if referential integrity constraint is violated in the future?
At tuple level, in what ways can referential integrity be violated?
○
○
On the referencing side
■ Insert: can have problem, not serious
■ Delete: no problem
■ Update: can have problem, not serious
On the referenced side
■ Insert: no problem
■ Delete: can have BIG problem
■ Update: can have BIG problem
27
Specifying Referential Integrity Constraint (2-1)
Insert
Delete
update
Insert
Delete
update
Student: Referencing relation
Department: Referenced relation
SID
SNAME
DEPT
DID
DNAME
101
John
7
7
EE
203
Mary
8
8
CS
307
Tom
NULL
15
Video game
Referential integrity holds between Student and Department now
28
Specifying Referential Integrity Constraint (2-2)
Insert
Delete
update
If updated to 9
Student: Referencing relation
Department: Referenced relation
SID
SNAME
DEPT
DID
DNAME
101
John
7
7
EE
203
Mary
8
9
CS
307
Tom
NULL
15
Video game
Referential integrity between Student and Department is broken
29
Specifying Referential Integrity Constraints (3)
●
Referential triggered action
○
○
○
○
○
●
Specified with ON UPDATE or ON DELETE
RESTRICT
SET NULL
SET DEFAULT
CASCADE
Attention: for referential integrity constraints:
○
○
Violations are caused by the referenced side,
But actions are taken on the referencing side
30
Specifying Referential Integrity Constraints (4)
●
CREATE TABLE EMPLOYEE ( . . . , Dno INT NOT NULL DEFAULT 1,
CONSTRAINT EMPPK PRIMARY KEY (Ssn),
CONSTRAINT EMPSUPERFK FOREIGN KEY (Super_ssn)
REFERENCES EMPLOYEE(Ssn) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT EMPDEPTFK FOREIGN KEY(Dno)
REFERENCES DEPARTMENT(Dnumber) ON DELETE SET DEFAULT ON UPDATE CASCADE);
●
CREATE TABLE DEPARTMENT ( . . . , Mgr_ssn CHAR(9) NOT NULL DEFAULT ‘888665555’, . . . ,
CONSTRAINT DEPTPK PRIMARY KEY(Dnumber),
CONSTRAINT DEPTSK UNIQUE (Dname),
CONSTRAINT DEPTMGRFK FOREIGN KEY (Mgr_ssn)
REFERENCES EMPLOYEE(Ssn) ON DELETE SET DEFAULT ON UPDATE CASCADE);
●
CREATE TABLE DEPT_LOCATIONS ( . . . ,
PRIMARY KEY (Dnumber, Dlocation),
FOREIGN KEY (Dnumber) REFERENCES DEPARTMENT(Dnumber)
ON DELETE CASCADE ON UPDATE CASCADE);
31
Giving Names to Constraints
●
Giving names to constraints
●
How: use the “constraint” keyword
●
Why: to call it, so that we can drop
or alter it later
●
In fact, most DBMS will generate a
default name for each constraint
even if you don’t give it a name
CREATE TABLE EMPLOYEE ( . . . , Dno INT NOT NULL DEFAULT 1,
CONSTRAINT EMPPK PRIMARY KEY (Ssn),
CONSTRAINT EMPSUPERFK FOREIGN KEY (Super_ssn)
Constraint
REFERENCES EMPLOYEE(Ssn) ON DELETE SET NULL ON UPDATE CASCADE,
names
CONSTRAINT EMPDEPTFK FOREIGN KEY(Dno)
REFERENCES DEPARTMENT(Dnumber) ON DELETE SET DEFAULT ON UPDATE CASCADE);
●
CREATE TABLE DEPARTMENT ( . . . , Mgr_ssn CHAR(9) NOT NULL DEFAULT ‘888665555’, . . . ,
CONSTRAINT DEPTPK PRIMARY KEY(Dnumber),
CONSTRAINT DEPTSK UNIQUE (Dname),
CONSTRAINT DEPTMGRFK FOREIGN KEY (Mgr_ssn)
REFERENCES EMPLOYEE(Ssn) ON DELETE SET DEFAULT ON UPDATE CASCADE);
●
CREATE TABLE DEPT_LOCATIONS ( . . . ,
PRIMARY KEY (Dnumber, Dlocation),
FOREIGN KEY (Dnumber) REFERENCES DEPARTMENT(Dnumber)
No name
ON DELETE CASCADE ON UPDATE CASCADE);
verion
32
Semantic Constraints Using Check Clause
CREATE TABLE t1(
CHECK (c1 <> c2),
Name of CHECK
c1 INT CHECK (c1 > 10),
c2 INT CONSTRAINT c2_positive CHECK (c2 > 0),
c3 INT CHECK (c3 < 100),
CONSTRAINT c1_nonzero CHECK (c1 <> 0),
CHECK (c1 > c3));
●
●
●
●
●
CHECKs and assertions are usually
supported only in large commercial
DBMS
MySQL (as of v8.0) supports CHECK
format but does not process it
DBMS enforces the conditions in CHECK to be always true (when a tuple is inserted/modified)
Constraints in single table: single column, multi-column
But not multi-table semantic constraints
How to enforce multi-table semantic
Can optionally assign a name using the CONSTRAINT keyword
constraints in smaller DBMS?
●
Use a combination of triggers,
How to specify multi-table semantic constraints in DBMS??
○
Assertion statement (only supported by large, enterprise grade DBMS’s.
stored procedures and views
(smaller DBMS’s)
33
Example of Check in Create Table
●
●
●
CREATE TABLE EMPLOYEE
( . . . , Dno INT NOT NULL DEFAULT 1,
CONSTRAINT EMPPK PRIMARY KEY (Ssn),
CONSTRAINT EMPSUPERFK FOREIGN KEY (Super_ssn) REFERENCES EMPLOYEE(Ssn)
ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT EMPDEPTFK FOREIGN KEY(Dno) REFERENCES DEPARTMENT(Dnumber)
ON DELETE SET DEFAULT ON UPDATE CASCADE);
CREATE TABLE DEPARTMENT
( . . . , Mgr_ssn CHAR(9) NOT NULL DEFAULT ‘888665555’, . . . ,
CONSTRAINT DEPTPK PRIMARY KEY(Dnumber),
CONSTRAINT DEPTSK UNIQUE (Dname),
CONSTRAINT DEPTMGRFK FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn)
ON DELETE SET DEFAULT ON UPDATE CASCADE
CHECK (Dept_create_date <= Mgr_start_date);
CREATE TABLE DEPT_LOCATIONS
( . . . , PRIMARY KEY (Dnumber, Dlocation),
FOREIGN KEY (Dnumber) REFERENCES DEPARTMENT(Dnumber)
ON DELETE CASCADE ON UPDATE CASCADE);
34
Assertions in SQL
Name of assertion
CREATE ASSERTION SALARY_CONSTRAINT
CHECK ( NOT EXISTS ( SELECT *
FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D
WHERE E.Salary>M.Salary
AND E.Dno=D.Dnumber
Check
AND D.Mgr_ssn=M.Ssn ) );
condition
●
●
●
●
Implementation of semantic constraints
DBMS enforces the assertion to be always true
Can enforce constraints that exist between multi-tables
Usually implemented in large, commercial DBMS
Delete (Part of) Schema: Drop
●
Drop
○
○
○
●
●
●
●
●
Can drop database, schema, catalog
Can drop table
Restrict or cascade clause: decide what to do with affected objects
DROP DATABASE university
DROP SCHEMA university
DROP TABLE departments
DROP TABLE departments RESTRICT
DROP TABLE departments CASCADE
For MySQL:
DROP {DATABASE | SCHEMA}
[IF EXISTS] db_name
36
Change Schema: Alter
●
ALTER {DATABASE|SCHEMA} db_name alter_specification …;
○
●
ALTER TABLE: change the details of a table definition
○
○
●
●
●
Can add, drop column, constraint, index
Can rename column or change the definition of column
ALTER TABLE students ADD COLUMN grade DECIMAL(5.2);
ALTER TABLE students ADD COLUMN grade int DEFAULT 1.0;
ALTER TABLE students DROP COLUMN grade CASCADE;
○
●
●
Change the characteristics of a database
We can specify CASCADE or RESTRICT when drop column
ALTER TABLE students ALTER COLUMN grade SET DEFAULT 2.0;
ALTER TABLE students ALTER COLUMN grade DROP DEFAULT;
37
SQL
Data Manipulation Language
38
Insert
●
Three kinds of usage
○
○
○
●
Assume we have table:
○
●
Create table students (ID int, name char(20), department char(20));
Examples:
○
○
○
●
Specific all values
Specific attribute names and values
Get value from a select clause
Insert into students values (1, “John smith”, “Math”);
INSERT INTO students (a,b,c) VALUES(1,”a”,”x”), (4,”b”,”y”), (7,”c”,”z”);
INSERT INTO students (a,b,c) VALUES ROW(1,”a”,”x”), ROW(4,”b”,”y”), ROW(7,”c”,”z”);
Insert into students (ID, name) values (2, “Peter Chen”), (3, “Ted Codd”);
Insert into students
Select HID, Hname, Wishdept From highschool_students where status = ‘selected’;
What happens if you insert into table and violate the key constraint(s)?
○
○
An inserted row has the same key value with an existing row
⇒ Use “on duplicate key update” phase
INSERT INTO t1 (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
39
Delete
●
Two types of usage
○
○
●
●
●
With conditions
Without condition
Create table students (
ID int, name char(20), department char(20));
Delete from students
Tuple select condition
Where department = ‘math’;
Delete from students;
○
○
Delete all rows in the table 'students’ ⇒ Be careful
But the schema of ‘students’ still remains
Advanced topics
●
Order by … limit K
●
Multi-table delete
40
Update
●
Modify attribute values of one or more selected tuples
○
●
●
Specify what values to update, and which tuple to update to
“Update tablename set attribute=’value’, attribute=’value’... where condition”
Can also set to NULL and set to default
What values to update
●
Which tuple to update to
Examples
○ UPDATE PROJECT SET Plocation = ‘Taipei’, Dnum =5 WHERE Pnumber=10;
○ UPDATE EMPLOYEE SET Salary = Salary * 1.1 WHERE Dno = 5;
○ UPDATE EMPLOYEE SET Salary = DEFAULT WHERE Dno = 5;
○ UPDATE EMPLOYEE SET Salary = NULL WHERE Dno = 5;
41
Select (Basic)
●
●
●
●
Most important command in SQL
The way to execute query and get answers!
Basic format
SELECT <attribute list>
FROM <table list>
WHERE <condition>;
Notes:
○
○
When there are multiple tables in the <table list>
■ It means some kind of join operation
■ Will often (but not always) involve foreign key relationship
<condition> typically contains atomic condition expressions connected by AND, OR, NOT
42
Select (2-1)
●
Select SID, Sname
From students, departments
Where Dname=’EE’’ and DEPTID = DID;
Student: Referencing relation
Department: Referenced relation
SID
SNAME
DEPTID
DID
DNAME
101
John
7
7
EE
203
Mary
8
8
CS
307
Tom
NULL
15
Video game
Assume referential integrity holds between Student and Department
43
Select (2)
●
●
●
●
Create table students (
SID int, Sname char(20), deptID int
Foreign key (deptID) REFERENCES departments(DID));
Create table departments (
DID int, Dname char(20));
Select SID, Sname
From students
Where deptID = 7;
Select SID, Sname
From students, departments
Where Dname=”EE’’ and deptID=did;
44
Select all attributes
●
●
Use * to denote all attributes
SELECT *
FROM EMPLOYEE
WHERE Dno=5;
Set and Multiset in SQL
●
●
●
SELECT ALL Salary
FROM EMPLOYEE
SELECT Salary
FROM EMPLOYEE
SELECT DISTINCT Salary
FROM EMPLOYEE
Return a multiset
Return a set
Use String Matching in Select
●
●
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Address LIKE ‘%Houston,TX%’;
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Bdate LIKE ‘_ _ 5 _ _ _ _ _ _ _’;
Replaces zero or more characters
Replaces one character
Between
●
●
SELECT *
FROM EMPLOYEE
WHERE (Salary BETWEEN 30000 AND 40000) AND Dno = 5;
For convenience
Ordering of Query Output
●
●
Order the output result of SELECT statement
SELECT
D.Dname, E.Lname, E.Fname, P.Pname
FROM
DEPARTMENT D, EMPLOYEE E,
WORKS_ON W, PROJECT P
WHERE
D.Dnumber= E.Dno AND E.Ssn= W.Essn AND
W.Pno= P.Pnumber
ORDER BY D.Dname, E.Lname, E.Fname
This cause can also appear in update
and delete
First
●
Second
Third
ORDER BY D.Dname DESC, E.Lname ASC, E.Fname ASC
Views: DDL That Depends on DML
●
Can consider VIEW as virtual table
○
●
Once created, it behaves almost like a table, at least from READ point of view
Purpose: provide users with convenient, easy access; security and authorization purposes
Name of view
CREATE VIEW WORKS_ON1
AS SELECT Fname, Lname, Pname, Hours
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE Ssn=Essn AND Pno=Pnumber;
CREATE VIEW DEPT_INFO(Dept_name, No_of_emps, Total_sal)
AS SELECT Dname, COUNT (*), SUM (Salary)
FROM DEPARTMENT, EMPLOYEE
Name of view
WHERE Dnumber=Dno
GROUP BY Dname;
Names of attributes
of view
50
Beyond Essential SQL
51
Other Advanced Aspects of SQL
●
●
●
User variables
Compound statements
DCL: database control language (not a rigorously defined term)
○
○
○
●
Active database
○
●
Stored procedure, stored function, trigger, events, (views)
■
Compound statements used in stored objects
SDL: storage definition language
Admin: other administration commands
Object-relational model extension
○
●
Triggers, events
Stored objects
○
●
●
●
Transaction and concurrency control: transaction control, concurrency control,
Session control: access control and authorization
System control: see admin
Object identifiers
XML extension, JSON extension, Spatial extension, …..
52
User-Defined
Variable
●
●
●
A.k.a user variable
A user can define variable in an
SQL session
An user variable can be used in
any position where a value is
expected
○
However, it cannot be
used in a place where a
column name or a table
name is expected
mysql> SET @v1 = 'A';
mysql> SET @v2 = 65;
mysql> SET @v3 = 101;
mysql> SELECT @v1, @v2, @v3;
+------+------+------+
| @v1 | @v2 | @v3 |
+------+------+------+
| A
|
65 | 101 |
+------+------+------+
53
Compound
Statement
●
●
●
●
Multiple statements
between BEGIN and
END
The whole compound
statement is treated as
one statement
Can contain control
flow such as
IF…THEN…ELSE
Mainly used with
stored objects
mysql> delimiter //
mysql> CREATE TRIGGER upd_check BEFORE
UPDATE ON account
FOR EACH ROW
BEGIN
IF NEW.amount < 0 THEN
SET NEW.amount = 0;
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END;//
mysql> delimiter ;
Just be aware of
For now
54
Transaction
●
Basic syntax:
○
○
●
Just be aware of
For now
START TRANSACTION;
<sql commands>...
<sql commands>...
<sql commands>...
COMMIT (or ROLLBACK)
SET autocommit = {0|1}
■ Default is ‘1’
Example:
○
START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1;
COMMIT;
55
Trigger
●
Automatically take action when
making changes to DB if certain
conditions are met
mysql> delimiter //
mysql> CREATE TRIGGER upd_check
BEFORE UPDATE ON account
FOR EACH ROW
BEGIN
IF NEW.amount < 0 THEN
SET NEW.amount = 0;
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END;//
mysql> delimiter ;
mysql> CREATE TABLE account (acct_num INT,
amount DECIMAL(10,2));
Query OK, 0 rows affected (0.03 sec)
mysql> CREATE TRIGGER ins_sum
BEFORE INSERT ON account
FOR EACH ROW SET @sum = @sum +
NEW.amount;
Query OK, 0 rows affected (0.01 sec)
mysql> SET @sum = 0;
mysql> INSERT INTO account
VALUES(137,14.98),(141,1937.50),(97,-100.00);
mysql> SELECT @sum AS 'Total amount inserted';
+-----------------------+
| Total amount inserted |
+-----------------------+
|
1852.48 |
Just be aware of
+-----------------------+
For now
56
Triggers (2)
Name of trigger
CREATE TRIGGER SALARY_VIOLATION
BEFORE INSERT OR UPDATE OF SALARY, SUPERVISOR_SSN ON
EMPLOYEE
Event
Condition
FOR EACH ROW
WHEN ( NEW.SALARY >(SELECT SALARY FROM EMPLOYEE
WHERE SSN = NEW.SUPERVISOR_SSN ))
INFORM_SUPERVISOR(NEW.Supervisor_ssn, NEW.Ssn );
Action: It is a stored procedure
Can be a potential
topic of final project
MySQL community edition
does not support “when”
and sending email from
within DBMS
Events
●
Statements that are scheduled
to be executed at specific time
or at specific interval
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP +
INTERVAL 1 HOUR
DO
UPDATE myschema.mytable SET mycol =
mycol + 1;
CREATE EVENT e_hourly
ON SCHEDULE
EVERY 1 HOUR
COMMENT 'Clears out sessions table
each hour.'
DO
DELETE FROM site_activity.sessions;
58
Window Functions in SQL
SELECT
val,
ROW_NUMBER()
OVER w AS 'row_number',
CUME_DIST()
OVER w AS 'cume_dist',
PERCENT_RANK()
OVER w AS 'percent_rank'
FROM numbers
WINDOW w AS (ORDER BY val);
Just be aware of
For now
+------+------------+--------------------+--------------+
| val | row_number | cume_dist
| percent_rank |
+------+------------+--------------------+--------------+
| 1|
1 | 0.2222222222222222 |
0|
| 1|
2 | 0.2222222222222222 |
0|
| 2|
3 | 0.3333333333333333 |
0.25 |
| 3|
4 | 0.6666666666666666 |
0.375 |
| 3|
5 | 0.6666666666666666 |
0.375 |
| 3|
6 | 0.6666666666666666 |
0.375 |
| 4|
7 | 0.8888888888888888 |
0.75 |
| 4|
8 | 0.8888888888888888 |
0.75 |
| 5|
9|
1|
1|
+------+------------+--------------------+--------------+
Further Readings
●
Recommended reading
○
●
Good to read:
○
●
Elmasri: Chap 5, Chap 6
Misev, Baumann: SQL support for multidimensional arrays
■ https://pdfs.semanticscholar.org/9ca8/581972c162f3338f3b2c9b7733c3c139e05e.pdf
■ Article published in 2018
■ Multidimensional array has become SQL standard in 2019/6
Fun to read: background knowledge building
○
○
Nino Guallart: An overview of type theories
■ https://www.researchgate.net/publication/267811580_An_Overview_of_Type_Theories
John L. Bell: Types, Sets and Categories
■ http://publish.uwo.ca/~jbell/types.pdf
60
Download