0% found this document useful (0 votes)
59 views

Chap05 - SQL

The document summarizes Chapter 5 on Structured Query Language (SQL). It covers SQL's introduction, data definition including commands like CREATE TABLE and ALTER TABLE, data manipulation including queries and aggregate functions, data updates, view definition, and indexes. SQL is a declarative language that allows users to specify the result without specifying how to execute query operations.

Uploaded by

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

Chap05 - SQL

The document summarizes Chapter 5 on Structured Query Language (SQL). It covers SQL's introduction, data definition including commands like CREATE TABLE and ALTER TABLE, data manipulation including queries and aggregate functions, data updates, view definition, and indexes. SQL is a declarative language that allows users to specify the result without specifying how to execute query operations.

Uploaded by

Khanh Son
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 151

Chapter 5

Structured Query Language


Content
¡ Introduction
¡ Data definition
¡ Data manipulation
- Query
- Update
¡ View definition
¡ Index

Introduction2DB - FIT - HCMUS 2


Introduction
¡ Relational algebra language
- How to execute the query operations (in what order)
- Difficult for users
¡ SQL (Structured Query Language)
- High level declarative language interface
- The user only specifies what the result is to be
- Developed at IBM Research (1970s)
- Also pronounced SEQUEL
- Expanded to a standard by ANSI
• SQL1: SQL-86
• SQL2: SQL-92
• SQL3: SQL-99, SQL-2003, SQL-2006, SQL-2008

Introduction2DB - FIT - HCMUS 3


Introduction
¡ SQL includes
- Data definition
- Data manipulation
- View definition
- Integrity constraint

- Security and authorization


- Transaction control

- Rules for embedding SQL into programming languages

Introduction2DB - FIT - HCMUS 4


Content
¡ Introduction
¡ Data definition
- Data type
- Data definition commands
¡ Data manipulation
¡ View defintion
¡ Index

Introduction2DB - FIT - HCMUS 5


Data definition
¡ Describes the structure of information in the DB
- Schema for the relation
- Domain of each attribute
- Integrity constraint
- Index on each relation
¡ Consists of
- CREATE TABLE
- DROP TABLE
- ALTER TABLE
- CREATE DOMAIN
- CREATE DATABASE
- …
Introduction2DB - FIT - HCMUS 6
Data type
¡ Numeric
- INTEGER
- SMALLINT
- NUMERIC, NUMERIC(p), NUMERIC(p,s)
- DECIMAL, DECIMAL(p), DECIMAL(p,s)
- REAL
- DOUBLE PRECISION
- FLOAT, FLOAT(p)

Introduction2DB - FIT - HCMUS 7


Data type
¡ Character string
- CHARACTER, CHARACTER(n)
- CHARACTER VARYING(x)

¡ Bit string
- BIT, BIT(x)
- BIT VARYING(x)

¡ Datetime
- DATE
- TIME
- TIMESTAMP

Introduction2DB - FIT - HCMUS 8


Create table command
¡ Define a new relation by giving
- A name
- Attributes
• Names
• Data types
• Integrity constraints on attributes
¡ Syntax
CREATE TABLE <Table_name> (
<Column_name> <Data_type> [<Constraint>],
<Column_name> <Data_type> [<Constraint>],

[<Constraint>]
)

Introduction2DB - FIT - HCMUS 9


Example
CREATE TABLE EMPLOYEE (
SSN CHAR(9),
LName VARCHAR(10),
MName VARCHAR(20),
FName VARCHAR(10),
BDate DATETIME,
Address VARCHAR(50),
Sex CHAR(3),
Salary INT,
SuperSSN CHAR(9),
DNo INT
)

Introduction2DB - FIT - HCMUS 10


Create table command
¡ Basic <Constraint>
- NOT NULL
- NULL
- UNIQUE
- DEFAULT
- PRIMARY KEY
- FOREIGN KEY / REFERENCES
- CHECK

¡ Give a name to constraints


CONSTRAINT <Constraint_name> <Constraint>

Introduction2DB - FIT - HCMUS 11


Example – Constraint
CREATE TABLE EMPLOYEE (
LName VARCHAR(10) NOT NULL,
MName VARCHAR(20) NOT NULL,
FName VARCHAR(10) NOT NULL,
SSN CHAR(9) PRIMARY KEY,
BDate DATETIME,
Address VARCHAR(50),
Sex CHAR(3) CHECK (Sex IN ( Nam , Nu )),
Salary INT DEFAULT (10000),
SuperSSN CHAR(9),
DNo INT
)

Introduction2DB - FIT - HCMUS 12


Example – Constraint
CREATE TABLE DEPARTMENT (
DName VARCHAR(20) UNIQUE,
DNumber INT NOT NULL,
MgrSSN CHAR(9),
MgrStartDate DATETIME DEFAULT (GETDATE())
)

CREATE TABLE WORKS_ON (


SSN CHAR(9) FOREIGN KEY (SSN)
REFERENCES EMPLOYEE(SSN),
PNo INT REFERENCES PROJECT(PNumber),
Hours DECIMAL(3,1)
)

Introduction2DB - FIT - HCMUS 13


Example – Constraint name
CREATE TABLE EMPLOYEE (
LName VARCHAR(10) CONSTRAINT EM_LName_NN NOT NULL,
MName VARCHAR(20) NOT NULL,
FName VARCHAR(10) NOT NULL,
SSN CHAR(9) CONSTRAINT EM_SSN_PK PRIMARY KEY,
BDate DATETIME,
Address VARCHAR(50),
Sex CHAR(3) CONSTRAINT EM_Sex_CHK
CHECK (Sex IN ( Nam , Nu )),
Salary INT CONSTRAINT EM_Salary_DF DEFAULT (10000),
SuperSSN CHAR(9),
DNo INT
)
Introduction2DB - FIT - HCMUS 14
Example – Constraint name

CREATE TABLE WORKS_ON (


SSN CHAR(9),
PNo INT,
Hours DECIMAL(3,1),
CONSTRAINT WO_SSN_PNo_PK PRIMARY KEY (SSN, PNo),
CONSTRAINT WO_SSN_FK FOREIGN KEY (SSN)
REFERENCES EMPLOYEE(SSN),
CONSTRAINT WO_PNo_FK FOREIGN KEY (PNo)
REFERENCES PROJECT(PNumber)
)

Introduction2DB - FIT - HCMUS 15


Alter table command
¡ Is used for modification
- The structure of tables
- Integrity constraints

¡ Columns
ALTER TABLE <Table_name> ADD COLUMN
<Column_name> <Data_type> [<Constraint>]

ALTER TABLE <Table_name> DROP COLUMN <Column_name>

ALTER TABLE <Table_name> ALTER COLUMN


<Column_name> <New_data_type>

Introduction2DB - FIT - HCMUS 16


Alter table command
¡ Constraints

ALTER TABLE <Table_name> ADD


CONSTRAINT <Constraint_name> <Constraint>,
CONSTRAINT <Constraint_name> <Constraint>,

ALTER TABLE <Table_name> DROP <Constraint_name>

Introduction2DB - FIT - HCMUS 17


Example

ALTER TABLE EMPLOYEE ADD


JobTitle CHAR(20)

ALTER TABLE EMPLOYEE DROP COLUMN JobTitle

ALTER TABLE EMPLOYEE ALTER COLUMN


JobTitle CHAR(50)

Introduction2DB - FIT - HCMUS 18


Example
CREATE TABLE DEPARTMENT (
DName VARCHAR(20),
DNumber INT NOT NULL,
MgrSSN CHAR(9),
MgrStartDate DATETIME
)
ALTER TABLE DEPARTMENT ADD
CONSTRAINT DE_DNumber_PK PRIMARY KEY (DNumber),
CONSTRAINT DE_MgrSSN_FK FOREIGN KEY (MgrSSN)
REFERENCES EMPLOYEE(SSN),
CONSTRAINT DE_MgrStartDate_DF DEFAULT (GETDATE())
FOR (MgrStartDate),
CONSTRAINT DE_DName_UN UNIQUE (DName)
Introduction2DB - FIT - HCMUS 19
Drop table command
¡ Is used for deleting the structure of tables
- All the data in a table are also deleted

¡ Syntax
DROP TABLE <Table_name>

¡ Example
DROP TABLE EMPLOYEE

DROP TABLE DEPARTMENT

DROP TABLE WORKS_ON

Introduction2DB - FIT - HCMUS 20


Example

EMPLOYEE

LName MName FName SSN BDate Address Sex Salary SuperSSN DNo

DEPARTMENT

DName DNumber MgrSSN MgrStartDate

Introduction2DB - FIT - HCMUS 21


Content
¡ Introduction
¡ Data definition
¡ Data manipulation
- Basic queries
- Set, set/multiset comparison and nested queries
- Aggregate functions and grouping
- Others
¡ Data update
¡ View definition
¡ Index

Introduction2DB - FIT - HCMUS 22


Query
¡ Data manipulation language is used for retrieving
information from a database
- These tuples often satisfy a certain condition

¡ Based on
Relational Some
+
algebra supplements
operations

- Allow a table to have two or more tuples that are


identical in all their attribute values
- Not a set of tuples, but a multiset or bag

Introduction2DB - FIT - HCMUS 23


Basic query
¡ Is formed of the three clauses
SELECT <List_of_columns>
FROM <List_of_tables>
[WHERE] <Condition>

- <List_of_columns>
• Column names showed in the result of the query
- <List_of_tables>
• Table names required to process the query
- <Condition>
• Boolean expression that identifies the rows to be retrieved
• Expression’s connection : AND, OR, and NOT
• Operations: < , > , <=, >=, <>, =, LIKE and BETWEEN
Introduction2DB - FIT - HCMUS 24
Basic query
¡ SQL and Relational Algebra

p
SELECT <List_of_columns>
´
FROM <List_of_tables>
s
WHERE <Condition>

SELECT L
p s
L ( R C (R))
FROM
WHERE C

Introduction2DB - FIT - HCMUS 25


Example
The entire tuple is produced

SELECT *
FROM EMPLOYEE
WHERE DNo=5

SSN LName MName FName BirthDate Address Sex Salary SuperSSN DNo

333445555 Nguyen Thanh Tung 12/08/1955 638 NVC Q5 Nam 40000 888665555 5
987987987 Nguyen Manh Hung 09/15/1962 Ba Ria VT Nam 38000 333445555 5

s DNo=5 (EMPLOYEE)

Introduction2DB - FIT - HCMUS 26


SELECT clause

SELECT SSN, LName, MName, FName


FROM EMPLOYEE
WHERE DNo=5 AND Sex= Nam

SSN LName MName FName

333445555 Nguyen Thanh Tung


987987987 Nguyen Manh Hung

p SSN, LName, MName, FName( s DNo=5 Ù Sex= Nam (EMPLOYEE))

Introduction2DB - FIT - HCMUS 27


SELECT clause
Alias name

SELECT SSN, LName AS Last Name , MName AS Middle Name ,


FName AS First Name
FROM EMPLOYEE
WHERE DNo=5 AND Sex= Nam

SSN Last Name Middle Name First Name

333445555 Nguyen Thanh Tung


987987987 Nguyen Manh Hung

R1 ¬ (pSSN, LName, MName, FName(sDNo=5ÙSex= Nam (EMPLOYEE)))


r RESULT(SSN, Last Name, Middle Name, First Name (R1)

Introduction2DB - FIT - HCMUS 28


SELECT clause

Extension

SELECT SSN, LName + + MName+ + FName AS Full Name


FROM EMPLOYEE
WHERE DNo=5 AND Sex= Nam

SSN Full Name

333445555 Nguyen Thanh Tung


987987987 Nguyen Manh Hung

r SSN, Full Name( p SSN,LName+MName+FName(


SSN,LName||MName||FName s DNo=5ÙSex= Nam (EMPLOYEE)))

Introduction2DB - FIT - HCMUS 29


SELECT clause

Extension

SELECT SSN, Salary*1.1 AS 10%SalaryIncrease


FROM EMPLOYEE
WHERE DNo=5 AND Sex= Nam

SSN 10%SalaryIncrease

333445555 33000
987987987 27500

r SSN, 10%SalaryIncrease( p SSN, Salary*1.1( s DNo=5ÙSex= Nam (EMPLOYEE)))

Introduction2DB - FIT - HCMUS 30


SELECT clause

Duplicate tuples are eliminated

SELECT DISTINCT
Salary Salary
FROM EMPLOYEE
WHERE DNo=5 AND Sex= Nam

Salary

30000
25000 - Cost
25000
38000
- Users want to see all tuples
38000

Introduction2DB - FIT - HCMUS 31


Example
¡ Find the SSN and first name of employees who work
for the department Nghien cuu

¬ EMPLOYEE
R1 DNo=DNumber DEPARTMENT

RESULT ¬ pSSN, FName (sDName= Nghien cuu (R1))

SELECT SSN, FName


FROM EMPLOYEE, DEPARTMENT
WHERE DName= Nghien cuu AND DNo=DNumber

Introduction2DB - FIT - HCMUS 32


WHERE clause

Boolean
SELECT SSN, FName expressions

FROM EMPLOYEE, DEPARTMENT


WHERE DName= Nghien cuu AND DNo=DNumber

TRUE TRUE

Introduction2DB - FIT - HCMUS 33


WHERE clause

Priority

SELECT SSN, FName


FROM EMPLOYEE, DEPARTMENT
WHERE (DName= Nghien cuu OR DName= Quan ly ) AND DNo=DNumber

Introduction2DB - FIT - HCMUS 34


WHERE clause

BETWEEN

SELECT SSN, FName


FROM EMPLOYEE
WHERE Salary>=20000 AND Salary=<30000

SELECT SSN, FName


FROM EMPLOYEE
WHERE Salary BETWEEN 20000 AND 30000

Introduction2DB - FIT - HCMUS 35


WHERE clause

NOT BETWEEN

SELECT SSN, FName


FROM EMPLOYEE
WHERE Salary NOT BETWEEN 20000 AND 30000

Introduction2DB - FIT - HCMUS 36


WHERE clause

LIKE

SELECT SSN, FName


FROM EMPLOYEE
WHERE Address LIKE Nguyen _ _ _ _

Arbitrary characters
SELECT SSN, FName
FROM EMPLOYEE
WHERE Address LIKE Nguyen %

Arbitrary strings

Introduction2DB - FIT - HCMUS 37


WHERE clause

NOT LIKE

SELECT SSN, FName


FROM EMPOYEE
WHERE LName LIKE Nguyen

SELECT SSN, FName


FROM EMPLOYEE
WHERE LName NOT LIKE Nguyen

Introduction2DB - FIT - HCMUS 38


WHERE clause

ESCAPE

SELECT SSN, FName


FROM EMPOYEE
WHERE Address LIKE 123x/%Nguyen ESCAPE x

Introduction2DB - FIT - HCMUS 39


WHERE clause

Datetime

SELECT SSN, FName


FROM EMPLOYEE
WHERE BDate BETWEEN 1955-12-08 AND 1966-07-19

1955-12-08 YYYY-MM-DD 17:30:00 HH:MI:SS

12/08/1955 MM/DD/YYYY 05:30 PM


December 8, 1955

1955-12-08 17:30:00

Introduction2DB - FIT - HCMUS 40


WHERE clause

NULL

- SQL allows attributes to have value NULL


• Value unknown
• Value inapplicable
• Value withheld
- Operation on a NULL and any value, the result is NULL
• x has a value NULL
• x + 3 is also NULL
• x + 3 is not a legal SQL expression
- Comparison on a NULL value and any value, the result is
UNKNOWN
• The value of x = 3 is UNKNOWN
• The comparison x = 3 is not correct SQL

Introduction2DB - FIT - HCMUS 41


WHERE clause

NULL

SELECT SSN, FName


FROM EMPLOYEE
WHERE SuperSSN IS NULL

SELECT SSN, FName


FROM EMPLOYEE
WHERE SuperSSN IS NOT NULL

Introduction2DB - FIT - HCMUS 42


WHERE clause

UNKNOWN

- The comparison involving NULL will result the three-


value logic
• True (1)
• False (0)
• Unknown (1/2)

- Logical operator
• x and y (Minimum value)
• x or y (Maximum value)
• not x (1-x)

- The condition in WHERE clauses will result False if


tuples with Unknown value
Introduction2DB - FIT - HCMUS 43
FROM clause

Unspecified WHERE clause

SELECT SSN, DNumber


FROM EMPLOYEE, DEPARTMENT
WHERE TRUE

SSN DNumber

333445555 1
333445555 4
333445555 5
987987987 1
987987987 4
987987987 5
… …

Introduction2DB - FIT - HCMUS 44


FROM clause

Alias name

SELECT DName,
DName,DLocation
DLocation
FROM DEPARTMENT
DEPARTMENT,
AS DEPT_LOCATIONS
DE, DEPT_LOCATIONS AS DL
WHERE DE.DNumber=DL.DNumber
DNumber=DNumber

SELECT FName, EM.BDate,


BDate, Dependent_Name,
Dependent_Name,
BDate
DE.BDate
FROM EMPLOYEE,EM,
EMPLOYEE DEPENDENT
DEPENDENT DE
WHERE SSN=ESSN

Introduction2DB - FIT - HCMUS 45


Example 1
¡ For each project locating in “Ha Noi”, find its number,
the department number that controls it, the last and
first name of the manager, as well as his/her birth
date and address

Introduction2DB - FIT - HCMUS 46


Example 2
¡ Find the last and first name of employees who work
for the department 5 and work on the project San
pham X with working hours are larger than 10

Introduction2DB - FIT - HCMUS 47


Example 3
¡ Find the first and last name of employees and their
supervisor

Introduction2DB - FIT - HCMUS 48


Example 4
¡ Find the last and first name of employees who are
supervised directly by Nguyen Thanh Tung

Introduction2DB - FIT - HCMUS 49


ORDER BY clause
¡ Is used for presenting a query in sorted order

¡ Syntax

SELECT <List_of_columns>
FROM <List_of_tables>
WHERE <Conditions>
ORDER BY<List_of columns>

- ASC (default)
- DESC

Introduction2DB - FIT - HCMUS 50


Example

SELECT ESSN, PNo


FROM WORKS_ON
ORDER BY ESSN DESC, PNo

ESSN PNo

999887777 10
999887777 30
987987987 10
987987987 30
987654321 10
987654321 20
987654321 30

Introduction2DB - FIT - HCMUS 51


Content
¡ Introduction
¡ Data definition
¡ Data manipulation
- Basic queries
- Set, set/multiset comparison and nested queries
- Aggregate functions and grouping
- Others
¡ Data update
¡ View definition
¡ Index

Introduction2DB - FIT - HCMUS 52


Set operations in SQL
¡ SQL has implemented set operators
- UNION
- INTERSECT
- EXCEPT

¡ The result is a set


- Eliminate identical tuples
- To keep identical tuples
• UNION ALL
• INTERSECT ALL
• EXCEPT ALL

Introduction2DB - FIT - HCMUS 53


Set operations in SQL
¡ Syntax
SELECT <Column_list> FROM <Table_list> WHERE <Condition>
UNION [ALL]
SELECT <Column_list> FROM <Table_list> WHERE <Condition>

SELECT <Column_list> FROM <Table_list> WHERE <Condition>


INTERSECT [ALL]
SELECT <Column_list> FROM <Table_list> WHERE <Condition>

SELECT <Column_list> FROM <Table_list> WHERE <Condition>


EXCEPT [ALL]
SELECT <Column_list> FROM <Table_list> WHERE <Condition>

Introduction2DB - FIT - HCMUS 54


Example 5
¡ Find the project numbers that have
- Either employees with the last name Nguyen ,
- Or been controlled by the department whose manager
has the last name Nguyen
SELECT PNo
FROM EMPLOYEE, WORKS_ON
WHERE SSN=ESSN AND LName= Nguyen
UNION
SELECT PNumber
FROM EMPLOYEE, DEPARTMENT, PROJECT
WHERE SSN=MgrSSN AND DNumber=DNum AND LName= Nguyen

Introduction2DB - FIT - HCMUS 55


Example 6
¡ Find employees who have dependents with the
same name and sex

SELECT FName, Sex, SSN FROM EMPLOYEE


INTERSECT
SELECT Dependent_Name, Sex, ESSN FROM DEPENDENT

SELECT EM.*
FROM EMPLOYEE EM, DEPENDENT DE
WHERE EM.SSN=DE.ESSN
AND EM.FName=DE.Dependent_name
AND EM.Sex=DE.Sex

Introduction2DB - FIT - HCMUS 56


Example 6
¡ Find employees who have the same name and sex
to dependents

SELECT FName, Sex FROM EMPLOYEE


INTERSECT
SELECT Dependent_Name, Sex FROM DEPENDENT

SELECT EM.*
FROM EMPLOYEE EM, DEPENDENT DE
WHERE EM.FName=DE.Dependent_Name
AND EM.Sex=DE.Sex

Introduction2DB - FIT - HCMUS 57


Example 7
¡ Find employees who have no dependents

SELECT SSN FROM EMPLOYEE


EXCEPT
SELECT ESSN AS SSN FROM DEPENDENT

Introduction2DB - FIT - HCMUS 58


Nested query

SELECT SSN, FName


FROM EMPLOYEE, DEPARTMENT
WHERE DName= Nghien cuu AND DNo=DNumber

SELECT <List_of_columns>
Outer query
FROM <List_of_tables>
WHERE <Set_comparison> (
SELECT <List_of_columns>
Subquery
FROM <List_of_tables>
WHERE <Condition>)

Introduction2DB - FIT - HCMUS 59


Nested query
¡ Queries can have several nested levels
- Usually three

¡ Subqueries of a WHERE clause are connected by


logical connective
- OR, AND

¡ Subqueries will return


- A single attribute and a single tuple (a single value)
• Can use operators such as = > < <= >= to compare
- A table (a set or multiset of tuples)
• Use IN, NOT IN, = ANY , > ANY, >= ALL .. to compare

Introduction2DB - FIT - HCMUS 60


Nested query
¡ WHERE clause of the outer query
- <Expression> <set operation> <subquery>

- Set comparison includes many operators


• IN, NOT IN
• ALL
• ANY or SOME

- Check whether the result of subqueries is empty or not


• EXISTS
• NOT EXISTS

Introduction2DB - FIT - HCMUS 61


Nested query
¡ Categories
- Non-correlated subqueries
• WHERE clause of subqueries do not refer to attributes of
relations in FROM clause of the outer query
• Subqueries will be performed before the outer query, and be
executed just one time

- Correlated subqueries
• WHERE clause of subqueries refer to at least one attribute of
relations in FROM clause of the outer query
• Subqueries will be executed many times, each time will
correlate to one tuple of the outer query

Introduction2DB - FIT - HCMUS 62


Example – Non-correlated
subqueries
SELECT SSN, FName
FROM EMPLOYEE, DEPT_LOCATIONS
WHERE DLocation= TP HCM AND DNo=DNumber

SELECT SSN, FName


FROM EMPLOYEE
WHERE DNo IN ((1, 5)
SELECT DNumber
FROM DEPT_LOCATIONS
WHERE DLocation= TP HCM )

Introduction2DB - FIT - HCMUS 63


Example 5

SELECT WO.PNo
FROM EMLOYEE EM, WORKS_ON WO
WHERE EM.SSN=WO.ESSN AND EM.LName= Nguyen
UNION
SELECT PR.PNumber
FROM EMPLOYEE EM, DEPARTMENT DE, PROJECT PR
WHERE EM.SSN=DE.MgrSSN AND DE.DNumber=PR.DNum
AND EM.LName= Nguyen

Introduction2DB - FIT - HCMUS 64


Example 5
SELECT DISTINCT PName
FROM PROJECT
WHERE PNumbber IN (
SELECT PNo
FROM EMPLOYEE, WORKS_ON
WHERE SSN=ESSN AND LName= Nguyen )
OR PNumber IN (
SELECT PNumber
FROM EMPLOYEE, DEPARTMENT, PROJECT
WHERE SSN=ESSN AND PNumber=DNum
AND LName= Nguyen )

Introduction2DB - FIT - HCMUS 65


Example 7
¡ Find employees who have no dependents
SELECT *
FROM EMPLOYEE
WHERE SSN NOT IN (
SELECT ESSN
FROM DEPENDENT)

SELECT *
FROM EMPLOYEE
WHERE SSN <> ALL (
SELECT ESSN
FROM DEPENDENT )

Introduction2DB - FIT - HCMUS 66


Example 8
¡ Find employees whose salary is greater than at
least one salary of employees in department 4

SELECT *
FROM EMPLOYEE
WHERE Salary > ANY (
SELECT Salary
FROM EMPLOYEE
WHERE DNo=4 )

SELECT EM1.*
FROM EMPLOYEE EM1, EMPLOYEE EM2
WHERE EM1.Salary > EM2.Salary AND EM2.DNo=4

Introduction2DB - FIT - HCMUS 67


Example 9
¡ Find employees whose salary is greater than all
salaries of employees in the department 4

SELECT *
FROM EMPLOYEE
WHERE Salary > ALL (
SELECT Salary
FROM EMPLOYEE
WHERE DNo=4 )

Introduction2DB - FIT - HCMUS 68


Example 10
¡ Find managers who have at least one dependent

SELECT *
FROM EMPLOYEE
WHERE SSN IN (SELECT ESSN FROM DEPENDENT)
AND SSN IN (SELECT MgrSSN FROM DEPARTMENT)

Introduction2DB - FIT - HCMUS 69


Example - Correlated subquery

SELECT SSN, FName


FROM EMPLOYEE, DEPARTMENT
WHERE DName= Nghien cuu AND DNo=DNumber

SELECT SSN, FName


FROM EMPLOYEE
WHERE EXISTS (
SELECT *
FROM DEPARTMENT
WHERE DName= Nghien cuu AND DNo=DNumber )

Introduction2DB - FIT - HCMUS 70


Example 6
¡ Retrieve employees who have dependents with the
same first name and same sex as the employees
SELECT *
FROM EMPLOYEE EM
WHERE EXISTS (
SELECT *
FROM DEPENDENT DE
WHERE EM.SSN=DE.SSN
AND EM.FName=DE.Name
AND EM.Sex=DE.Sex )

Introduction2DB - FIT - HCMUS 71


Example 7
¡ Find employees who have no dependents

SELECT *
FROM EMPLOYEE
WHERE NOT EXISTS (
SELECT *
FROM DEPENDENT
WHERE SSN=ESSN)

Introduction2DB - FIT - HCMUS 72


Example 8
¡ Find employees whose salary is greater than at
least one salary of employees in department 4

SELECT *
FROM EMPLOYEE EM1
WHERE EXISTS (
SELECT *
FROM EMPLOYEE EM2
WHERE EM2.PNo=4
AND EM1.Salary>EM2.Salary)

Introduction2DB - FIT - HCMUS 73


Example 10
¡ Find managers who have at least one dependent
SELECT *
FROM EMPLOYEE
WHERE EXISTS (
SELECT *
FROM DEPENDENT
WHERE SSN=ESSN )
AND EXISTS (
SELECT *
FROM DEPARTMENT
WHERE SSN=MgrSSN )

Introduction2DB - FIT - HCMUS 74


Discussion IN and EXISTS
¡ IN
- <Column_name> IN <Subquery>
- Attributes in the subquery’s SELECT clause have the
same data types as attributes in the outer query’s
WHERE clause
¡ EXISTS
- Do not need attributes, constants or any expressions
before it
- Do not need to specify column names in the subquery’s
SELECT clause
- Queries containing “= ANY” or IN can be converted
queries containing EXISTS

Introduction2DB - FIT - HCMUS 75


Discussion
¡ Comparison of one value and members in a set
- any/some or exists of nested queries Û equijoin of
basic queries

Introduction2DB - FIT - HCMUS 76


Divide operation in SQL

R A B C D E S D E R÷S A B C

a a a a 1 bi a 1 ai a a g
a a g a 1 b 1 g a g
a a g b 1
b a g a 1
b a g b 3
g a g a 1
g a g b 1
g a b b 1

¡ R÷S is a set of values ai in R such that there is no


values bi in S that makes the tuple (ai, bi) does not
exist in R

Introduction2DB - FIT - HCMUS 77


Example 11
¡ Retrieve the first name of employees who work on
all projects

- Retrieve the first name of employees such that there is


no projects that they do not work on

- R: WORKS_ON(ESSN, PNo)
- S: PROJECT(PNumber)
- R÷S: RESULT(ESSN)
- Joining RESULT to EMPLOYEE to retrieve FName

Introduction2DB - FIT - HCMUS 78


Example 11

¡ Using NOT EXISTS two times


SELECT R1.A, R1.B, R1.C
FROM R R1
WHERE NOT EXISTS (
SELECT *
FROM S
WHERE NOT EXISTS (
SELECT *
FROM R R2
WHERE R2.D=S.D AND R2.E=S.E
AND R1.A=R2.A AND R1.B=R2.B AND R1.C=R2.C ))

Introduction2DB - FIT - HCMUS 79


Example 11

SELECT EM.FName
FROM EMPLOYEE EM, WORKS_ON WO1
WHERE EM.SSN=WO1.ESSN
AND NOT EXISTS (
SELECT *
FROM PROJECT PR
WHERE NOT EXISTS (
SELECT *
FROM WORKS_ON WO2
WHERE WO2.PNo=PR.PNumber
AND WO1.ESSN=WO2.ESSN ))

Introduction2DB - FIT - HCMUS 80


Example 11

¡ Using NOT EXISTS and EXCEPT


SELECT R1.A, R1.B, R1.C
FROM R R1
WHERE NOT EXISTS (
( SELECT D, E FROM S )
EXCEPT
( SELECT D, E FROM R R2 WHERE R1.A=R2.A
AND R1.B=R2.B
AND R1.C=R2.C ))

Introduction2DB - FIT - HCMUS 81


Example 11

SELECT FName
FROM EMPLOYEE
WHERE NOT EXISTS (
( SELECT PNumber FROM PROJECT )
EXCEPT
( SELECT PNo FROM WORKS_ON WHERE SSN=ESSN ))

Introduction2DB - FIT - HCMUS 82


Content
¡ Introduction
¡ Data definition
¡ Data manipulation
- Basic queries
- Set, set/multiset comparison and nested queries
- Aggregate functions and grouping
- Others
¡ Data update
¡ View definition
¡ Index

Introduction2DB - FIT - HCMUS 83


Aggregate functions
¡ COUNT
- COUNT(*) : the number of rows
- COUNT(<Column_name>): the number of non-zero
values of the column
- COUNT(DISTINCT <Column_name>): the number of
different and non-zero values of the column
¡ MIN
¡ MAX
¡ SUM
¡ AVG

¡ These function is in SELECT clause

Introduction2DB - FIT - HCMUS 84


Example 12
¡ Find the sum of salary, highest salary, lowest salary
and average salary of employees

SELECT SUM(Salary), MAX(Salary), MIN(Salary), AVG(Salary)


FROM EMPLOYEE

Introduction2DB - FIT - HCMUS 85


Example 13
¡ Find the number of employees in the department
Nghien cuu

SELECT COUNT(*) AS Num_Emp


FROM EMPLOYEE, DEPARTMENT
WHERE PNo=PNumber AND PName= Nghien cuu

Introduction2DB - FIT - HCMUS 86


Example 14
¡ Find the number of employees for each department
DNo Num_Emp

5 3
4 3
1 1

SSN LName MName FName BirthDate Address Sex Salary SuperSSN DNo

333445555 Nguyen Thanh Tung 12/08/1955 638 NVC Q5 Nam 40000 888665555 5
987987987 Nguyen Manh Hung 09/15/1962 Ba Ria VT Nam 38000 333445555 5
453453453 Tran Thanh Tam 07/31/1972 543 MTL Q1 Nu 25000 333445555 5
999887777 Bui Ngoc Hang 07/19/1968 33 NTH Q1 Nu 38000 987654321 4
987654321 Le Quynh Nhu 07620/1951 219 TD Q3 Nu 43000 888665555 4
987987987 Tran Hong Quang 04/08/1969 980 LHP Q5 Nam 25000 987654321 4
888665555 Pham Van Vinh 11/10/1945 450 TV HN Nam 55000 NULL 1

Introduction2DB - FIT - HCMUS 87


Grouping
¡ Syntax
SELECT <List_of_columns>
FROM <List_of_ tables>
WHERE <Conditions>
GROUP BY <List_of_grouping_columns>

¡ After grouping
- Each group will have identical values at grouping
attributes

Introduction2DB - FIT - HCMUS 88


Example 14
¡ Find the number of employees for each department

SELECT DNo, COUNT(*) AS Num_Emp


FROM EMPLOYEE
GROUP BY DNo

SELECT DName, COUNT(*) AS Num_Emp


FROM EMPLOYEE, DEPARTMENT
WHERE DNo=DNumber
GROUP BY DName

Introduction2DB - FIT - HCMUS 89


Example 15
¡ For each employee, retrieve the SSN, first name,
last name, number of projects as well as total of
hours that the employee works on

Introduction2DB - FIT - HCMUS 90


Example 15

ESSN PNo Hours

123456789 1 32.5
123456789 2 7.5
333445555 2 10.0
333445555 3 10.0
333445555 10 10.0
888665555 20 20.0
987987987 10 35.0
987987987 30 5.0
987654321 30 20.0
987654321 20 15.0
453453453 1 20.0
453453453 2 20.0

Introduction2DB - FIT - HCMUS 91


Example 15

SELECT ESSN, COUNT(*) AS Num_Pro, SUM(Hours) AS Total_Hours


FROM WORKS_ON
GROUP BY ESSN

SELECT LName, FName, COUNT(*) AS Num_Pro,


SUM(THOIGIAN) AS Total_Hours
FROM WORKS_ON, EMPLOYEE
WHERE ESSN=SSN
GROUP BY ESSN, LName, FName

Introduction2DB - FIT - HCMUS 92


Example 16
¡ Find employees who work on two or more projects

ESSN DNo Hours

123456789 1 32.5
123456789 2 7.5
333445555 2 10.0
333445555 3 10.0
333445555 10 10.0
888665555 20 20.0 Eliminated
987987987 10 35.0
987987987 30 5.0
987654321 30 20.0
987654321 20 15.0
453453453 1 20.0
453453453 2 20.0

Introduction2DB - FIT - HCMUS 93


Conditions on groups
¡ Syntax
SELECT <List_of_columns>
FROM <List_of_tables>
WHERE <Conditions>
GROUP BY <List_of_grouping_columns>
HAVING <Conditions>

Introduction2DB - FIT - HCMUS 94


Example 16
¡ Find employees who work on two or more projects

SELECT ESSN
FROM WORKS_ON
GROUP BY ESSN
HAVING COUNT(*) >= 2

Introduction2DB - FIT - HCMUS 95


Example 17
¡ Retrieve the department name whose the average
salary of employees that is greater than 20000

SELECT DNo, AVG(Salary) AS Avg_Salary


FROM EMPLOYEE
GROUP BY DNo
HAVING AVG(Salary) > 20000

SELECT DName, AVG(Salary) AS Avg_Salary


FROM EMPLOYEE, DEPARTMENT
WHERE DNo=DNumber
GROUP BY DNo, DName
HAVING AVG(Salary) > 20000
Introduction2DB - FIT - HCMUS 96
Discussion
¡ GROUP BY
- Attributes in SELECT clause (excepting attributes of
aggregate functions) must appear in GROUP BY clause

¡ HAVING
- Use aggregate functions in SELECT clause to check a
certain condition
- Just validate the conditions for groups, not a condition for
filtering rows
- After grouping, conditions on groups will be performed

Introduction2DB - FIT - HCMUS 97


Discussion
¡ The order of the query execution
- (1) Pick out rows that satify conditions in WHERE clause
- (2) Group these rows into many groups in GROUP BY
clause
- (3) Apply aggregate functions for each group
- (4) Eliminate groups that do not satisfy conditions in
HAVING clause
- (5) Retrieve values from columns and aggregate
functions in SELECT clause

Introduction2DB - FIT - HCMUS 98


Example 18
¡ Find departments that have the highest average
salary

SELECT DNo, AVG(Salary) AS Avg_Salary


FROM EMPLOYEE
GROUP BY DNo
HAVING MAX(AVG(Salary))
AVG(Salary) >= ALL (
SELECT AVG(Salary)
FROM EMPLOYEE
GROUP BY DNo)

Introduction2DB - FIT - HCMUS 99


Example 19
¡ Find three employees who have the highest salary

SELECT FName
FROM EMPLOYEE EM1
WHERE 2 >= (
SELECT COUNT(*)
FROM EMPLOYEE EM2
WHERE EM2.Salary>EM1.Salary )

Introduction2DB - FIT - HCMUS 100


Discussion
¡ Find three employees who have the highest salary
- If salaries are redundant, then ???

Introduction2DB - FIT - HCMUS 101


Example 12
¡ Find the first name of employees who work on all
projects

SELECT SSN, FName


FROM EMPLOYEE, WORKS_ON
WHERE SSN=ESSN
GROUP BY SSN, FName
HAVING COUNT(*) = (
SELECT COUNT(*)
FROM PROJECT)

Introduction2DB - FIT - HCMUS 102


Content
¡ Introduction
¡ Data definition
¡ Data manipulation
- Basic queries
- Set, set/multiset comparison and nested queries
- Aggregate functions and grouping
- Other queries
¡ Data update
¡ View definition
¡ Index

Introduction2DB - FIT - HCMUS 103


Other queries
¡ Subquery in FROM clause

¡ Joining conditions in FROM clause


- Natural join
- Outer join

¡ CASE structure

Introduction2DB - FIT - HCMUS 104


Subquery in FROM clause
¡ The result of a subquery is a table
- Intermediate table in the process of query execution
- Do not store this result into the database

¡ Syntax
SELECT <List_of_columns>
FROM R1, R2, (<Subquery>) AS Table_name
WHERE <Conditions>

Introduction2DB - FIT - HCMUS 105


Example 17
¡ Retrieve the department name whose the average
salary of employees that is greater than 20000
SELECT DNo, AVG(Salary) AS Avg_Salary
FROM EMPLOYEE
GROUP BY DNo
HAVING AVG(Salary) > 20000

SELECT DName, AVG(Salary) AS Avg_Salary


FROM EMPLOYEE, DEPARTMENT
WHERE DNo=DNumber
GROUP BY DNo, DName
HAVING AVG(Salary) > 20000

Introduction2DB - FIT - HCMUS 106


Example 17
¡ Retrieve the department name whose the average
salary of employees that is greater than 20000

SELECT DName, TEMP.Avg_Salary


FROM DEPARTMENT, (SELECT DNo, AVG(Salary) AS Avg_Salary
FROM EMPLOYEE
GROUP BY DNo
HAVING AVG(Salary)> 20000 ) AS TEMP
WHERE DNumber=TEMP.DNo

Introduction2DB - FIT - HCMUS 107


Join conditions in FROM clause
¡ Equijoin
SELECT <List_of_columns>
FROM R1 [INNER] JOIN R2 ON <Expression>
WHERE <Conditions>

¡ Outer join

SELECT <List_of_columns>
FROM R1 LEFT|RIGHT [OUTER] JOIN R2 ON <Expression>
WHERE <Conditions>

Introduction2DB - FIT - HCMUS 108


Example 20
¡ Retrieve the SSN and first name of employees who
work for the department Nghien cuu

SELECT SSN, FName


FROM EMPLOYEE, DEPARTMENT
WHERE DName= Nghien cuu AND DNo=DNumber

SELECT SSN, FName


FROM EMPLOYEE INNER JOIN DEPARTMENT ON DNo=DNumber
WHERE DName= Nghien cuu

Introduction2DB - FIT - HCMUS 109


Example 21
¡ Retrieve the fist and last name of employees, as
well as the department name that they are
managers
FName LName DName

Tung Nguyen Nghien cuu


Hang Bui null
Nhu Le null
Vinh Pham Quan ly

SELECT FName, LName, DName


FROM EMPLOYEE, DEPARTMENT
WHERE SSN=MgrSSN

Introduction2DB - FIT - HCMUS 110


Example 21

FName LName DName

Tung Nguyen Nghien cuu


Hang Bui null
Nhu Le null
Vinh Pham Quan ly
Extending the information
for EMPLOYEE

EMPLOYEE join DEPARTMENT


SSN=MgrSSN

SELECT FName, LName, DName


FROM EMPLOYEE LEFT JOIN DEPARTMENT ON SSN=MgrSSN

Introduction2DB - FIT - HCMUS 111


Example 21

FName LName DName

Tung Nguyen Nghien cuu


Hang Bui null
Nhu Le null
Vinh Pham Quan ly
Extending the information
for EMPLOYEE

DEPARTMENT join EMPLOYEE


MgrSSN=SSN

SELECT FName, LName, DName


FROM DEPARTMENT RIGHT JOIN EMPLOYEE ON SSN=MgrSSN

Introduction2DB - FIT - HCMUS 112


Example 22
¡ Retrieve the first and last name of employees, the
name of projects that they work on (if any)

WORKS_ON join PROJECT join EMPLOYEE

ESSN=SSN

SELECT EM.FName, PR.PName


FROM (WORKS_ON WO JOIN PROJECT PR ON PNO=PNumber)
RIGHT JOIN EMPLOYEE EM ON WO.ESSN=EM.SSN

Introduction2DB - FIT - HCMUS 113


CASE structure
¡ Allow us to check conditions or output the
information in each case

¡ Syntax
CASE <Column_name>
WHEN <Value> THEN <Expression>
WHEN <Value> THEN <Expression>

[ELSE <Expression>]
END

Introduction2DB - FIT - HCMUS 114


Example 23
¡ Retrieve the last and first name of employees who
are gonna reach the retired age (male: 60 years old,
female: 55 years old)

SELECT LName, FName


FROM EMPLOYEE
WHERE YEAR(GETDATE()) – YEAR(BirthDate) >= ( CASE Sex
WHEN 'Nam' THEN 60
WHEN 'Nu' THEN 55
END )

Introduction2DB - FIT - HCMUS 115


Example 24
¡ Retrieve the last and first name of employees, as
well as their retired year

SELECT LName, FName,


(CASE Sex
WHEN 'Nam' THEN YEAR(BirthDate) + 60
WHEN 'Nu’ THEN YEAR(BirthDate) + 55
END ) AS RetiredYear
FROM EMPLOYEE

Introduction2DB - FIT - HCMUS 116


Summary

SELECT <List_of_columns>
FROM <List_of_tables>
[WHERE <Conditions>]
[GROUP BY <List_grouping_columns>]
[HAVING <Conditions>]
[ORDER BY <List_of_ordering_columns>]

Introduction2DB - FIT - HCMUS 117


Content
¡ Introduction
¡ Data definition
¡ Data manipulation
¡ Data update
- Insert
- Delete
- Update
¡ View definition
¡ Index

Introduction2DB - FIT - HCMUS 118


INSERT command
¡ Is used to add 1 or more tuple(s) to a relation

¡ In order to add a tuple


- Relation name
- List of column names
- List of values for the tuple

Introduction2DB - FIT - HCMUS 119


INSERT command
¡ Syntax (one tuple)

INSERT INTO <Table_name>(<List_of_columns>)


VALUES (<List_of_values>)

Introduction2DB - FIT - HCMUS 120


Example

INSERT INTO EMPLOYEE(LName, MName, FName, SSN)


VALUES ( Le , Van , Tuyen , 635635635 )

INSERT INTO EMPLOYEE(LName, MName, FName, SSN, Address)


VALUES ( Le , Van , Tuyen , 635635635 , NULL)

INSERT INTO EMPLOYEE


VALUES ( Le , Van , Tuyen , 635635635 , 12/30/1952 , 98 HV , Nam ,
37000 , 4)

Introduction2DB - FIT - HCMUS 121


INSERT command
¡ Discussion
- The order of values is the same to the order of columns

- The NULL value can be used for non-primary-key


attributes

- INSERT command will raise errors if the integrity


constraint is violated
• Primary key
• Reference
• NOT NULL constraint

Introduction2DB - FIT - HCMUS 122


INSERT command
¡ Syntax (many tuples)

INSERT INTO <Table_name>(<List_of_columns>)


<Query>

Introduction2DB - FIT - HCMUS 123


Example
CREATE TABLE ANALYSE_DEPT (
DName VARCHAR(20),
Number_Emp INT,
Total_Salary INT
)

INSERT INTO ANALYSE_DEPT(DName, Number_Emp, Total_Salary)


SELECT DName, COUNT(SSN), SUM(Salary)
FROM EMPLOYEE, DEPARTMENT
WHERE DNo=DNumber
GROUP BY DName

Introduction2DB - FIT - HCMUS 124


DELETE command
¡ Is used to remove tuples from a relation

¡ Syntax

DELETE FROM <Table_name>


[WHERE <Conditions>]

Introduction2DB - FIT - HCMUS 125


Example

DELETE FROM EMPLOYEE


WHERE LName= Tran

DELETE FROM EMPLOYEE


WHERE SSN= 345345345

DELETE FROM EMPLOYEE

Introduction2DB - FIT - HCMUS 126


Example 25
¡ Remove employees who work for the department
Nghien cuu

DELETE FROM EMPLOYEE


WHERE DNo IN (
SELECT DNumber
FROM DEPARTMENT
WHERE DName= Nghien cuu )

Introduction2DB - FIT - HCMUS 127


DELETE command
¡ Discussion
- The number of removed tuples depends on the condition
in WHERE clause

- A missing WHERE clause specifies that all tuples can be


deleted

- DELETE command can cause the violation of reference


constraints
• Do not permit to remove
• Remove tuples whose value is being referred
* CASCADE
• Set the NULL value to cho những giá trị tham chiếu

Introduction2DB - FIT - HCMUS 128


DELETE command
SSN LName MName FName BirthDate Address Sex Salary SuperSSN DNo

333445555 Nguyen Thanh Tung 12/08/1955 638 NVC Q5 Nam 40000 888665555 5
987987987 Nguyen Manh Hung 09/15/1962 Ba Ria VT Nam 38000 333445555 5
453453453 Tran Thanh Tam 07/31/1972 543 MTL Q1 Nu 25000 333445555 5
999887777 Bui Ngoc Hang 07/19/1968 33 NTH Q1 Nu 38000 987654321 4
987654321 Le Quynh Nhu 07620/1951 219 TD Q3 Nu 43000 888665555 4
987987987 Tran Hong Quang 04/08/1969 980 LHP Q5 Nam 25000 987654321 4
888665555 Pham Van Vinh 11/10/1945 450 TV HN Nam 55000 NULL 1

ESSN DNo Hours

333445555 10 10.0
888665555 20 20.0
987987987 10 35.0
987987987 30 5.0
987654321 30 20.0
453453453 1 20.0

Introduction2DB - FIT - HCMUS 129


DELETE command

DName DNumber MgrSSN MgrStartDate

Nghien cuu 5 333445555 05/22/1988


Dieu hanh 4 987987987 01/01/1995
Quan ly 1 888665555 06/19/1981

SSN LName MName FName BirthDate Address Sex Salary SuperSSN DNo

333445555 Nguyen Thanh Tung 12/08/1955 638 NVC Q5 Nam 40000 888665555 NULL
5
987987987 Nguyen Manh Hung 09/15/1962 Ba Ria VT Nam 38000 333445555 NULL
5
453453453 Tran Thanh Tam 07/31/1972 543 MTL Q1 Nu 25000 333445555 NULL
5
999887777 Bui Ngoc Hang 07/19/1968 33 NTH Q1 Nu 38000 987654321 4
987654321 Le Quynh Nhu 07620/1951 219 TD Q3 Nu 43000 888665555 4
987987987 Tran Hong Quang 04/08/1969 980 LHP Q5 Nam 25000 987654321 4
888665555 Pham Van Vinh 11/10/1945 450 TV HN Nam 55000 NULL 1

Introduction2DB - FIT - HCMUS 130


UPDATE command
¡ Is used to change the value of attributes

¡ Syntax
UPDATE <Table_name>
SET <Attribute_name>=<The_new_value>,
<Attribute_name>=<The_new_value>,

[WHERE <Condition>]

Introduction2DB - FIT - HCMUS 131


Example

UPDATE EMPLOYEE
SET BDate= 08/12/1965
WHERE SSN= 333445555

UPDATE EMPLOYEE
SET Salary=Salary*1.1

Introduction2DB - FIT - HCMUS 132


Example 26
¡ Change the location and controlling department
number of the project 10 to Vung Tau and 5,
respectively

UPDATE PROJECT
SET PLocation= Vung Tau , DNum=5
WHERE PNumber=10

Introduction2DB - FIT - HCMUS 133


UPDATE command
¡ Discussion
- Tuples that satisfy conditions in WHERE clause will be
modified to the new value

- A missing WHERE clause specifies that all tuples can be


modified

- UPDATE command can cause violations of the reference


constraint
• Do not allow to modify
• Modify the values of tuples that are being referred
* CASCADE

Introduction2DB - FIT - HCMUS 134


Content
¡ Introduction
¡ Data definition
¡ Data manipulation
¡ Data update
¡ View definition
- Definition
- Query
- Modification
¡ Index

Introduction2DB - FIT - HCMUS 135


View
¡ Table is a relation that exist actually the database
- Stored in some physical organization
- Persistent

¡ View is also a relation


- Do not exist physically (virtual table)
- Do not contain the data
- Is derived from other tables
- Can query or even modify the data through views

Introduction2DB - FIT - HCMUS 136


View
¡ Why do we use views?
- Hide the complexity of data
- Simplify queries
- Present data with the purpose “easy to use”
- Mechanism of data safety

Introduction2DB - FIT - HCMUS 137


Definition
¡ Syntax
CREATE VIEW <View_name> AS
<Query>

DROP VIEW <View_name>

¡ View contains
- A list of attributes that are the same as attributes in
SELECT clause
- The number of tuples depending on the conditions in
WHERE clause
- Data derived from tables in FROM clause
Introduction2DB - FIT - HCMUS 138
Example

CREATE VIEW EMP_DEP5 AS


SELECT SSN, LName, MName, FName
FROM EMPLOYEE
WHERE DNo=5

CREATE VIEW STATISTIC_DEP AS


SELECT DNo, DName, COUNT(*) AS Number_Emp,
SUM(Salary) AS Total_Salary
FROM EMPLOYEE, DEPARTMENT
WHERE DNo=DNumber
GROUP BY DNumber, DName

Introduction2DB - FIT - HCMUS 139


Querying views
¡ Although views do not contain data, we can do the
query on views

SELECT FName
FROM EMP_DEP5
WHERE LName LIKE Nguyen

EMP_DEP5¬ p SSN, LName, MName, FName s


( DNo=5 (EMPLOYEE))

p FName (s LName= Nguyen (EMP_DEP5))

Introduction2DB - FIT - HCMUS 140


Querying views
¡ Can query data from both tables and views

SELECT LName, FName, PName, Hours


FROM EMP_DEP5, WORKS_ON, PROJECT
WHERE SSN=ESSN AND PNo=PNumber

EMP_DEP5¬ p SSN, LName, MName, FName s


( DNo=5 (EMPLOYEE))

TMP ¬ EMP_DEP5 SSN=ESSN(WORKS_ON PNo=PNumber PROJECT)

p LName,FName,PName,Hours(TMP)

Introduction2DB - FIT - HCMUS 141


Modifying views
¡ Can apply INSERT, DELETE, and UPDATE
commands to simple views
- Views built on one table and having the key attribute of
that table

¡ Cannot modify views


- Views have a key word DISTINCT
- Views use aggregate functions
- Views have extended SELECT clause
- Views are derived from table containing constrains on
columns
- Views are derived from many tables

Introduction2DB - FIT - HCMUS 142


Modifying views
¡ Modify the last name of employee 123456789 in
department 5 to Pham

UPDATE EMP_DEP5
SET LName= Pham
WHERE SSN= 123456789

Introduction2DB - FIT - HCMUS 143


Content
¡ Introduction
¡ Data definition
¡ Data manipulation
¡ Data update
¡ View definition
¡ Index

Introduction2DB - FIT - HCMUS 144


Index
¡ The index on an attribute A is the data structure that
makes it efficient to find tuples having a fixed value
for attribute A

SELECT *
FROM EMPLOYEE Read 10.000
tuples
WHERE DNo=5 AND Sex= Nu
Read 200 tuples

Table EMPLOYEE has 10.000 tuples


Read 70 tuples
There are 200 employees who work for
the department 5

Introduction2DB - FIT - HCMUS 145


Index
¡ Syntax
CREATE INDEX <Index_name> ON <Table_name>(<Column_name>)

DROP INDEX <Index_name>

¡ Example

CREATE INDEX DNo_IND ON EMPLOYEE(DNo)

CREATE INDEX DNo_Sex_IND ON EMPLOYEE(DNo, Sex)

Introduction2DB - FIT - HCMUS 146


Index
¡ Discussion
- Speed up queries in which a value for an attribute is
specified, join operations
- Make insertion, deletion, and update more complex and
time-consuming
- Cost
• Index storage
• Disk access (HDD)

¡ Selection of indexes
- One of the principal factors that influence a database
- One of the hardest parts of database design

Introduction2DB - FIT - HCMUS 147


Example
¡ Examine the relation WORKS_ON(ESSN, PNo, Hours)
¡ Assume that
- WORKS_ON is stored in 10 disk blocks
• The cost of examining the entire relation WORKS_ON is 10
- On the average, an employee works on 3 projects and a
project has 3 employees
• Tuples for a given employee or project are likely to be spread
over the 10 disk blocks
• The cost of finding 3 tuples for an employee or a project will
take 3 disk accesses (if we have indexes)
- Using indexes to locate tuples
• The cost of reading an index’s block is 1 disk access
- Insertion costs 2 disk accesses
Introduction2DB - FIT - HCMUS 148
Example
¡ Suppose that the following queries are performed
frequently
- Q1 SELECT PNo, Hours
FROM WORKS_ON
WHERE ESSN= 123456789

- Q2 SELECT ESSN
FROM WORKS_ON
WHERE PNo=1 AND Hours=20.5

- Q3 INSERT INTO WORKS_ON


VALUES ( 123456789 , 1, 20.5)

Introduction2DB - FIT - HCMUS 149


Example
¡ The costs of each of the 3 queries

No index ESSN index PNo index Both indexes


Queries

Q1 10 4 10 4

Q2 10 10 4 4

Q3 2 4 4 6

Average 2 + 8p1 + 8p2 4 + 6p2 4 + 6p1 6 - 2p1 – 2p2


cost

The fraction of the time we do Q1 is p1


The fraction of the time we do Q2 is p2
The fraction of the time we do Q3 là 1 - p1 - p2

Introduction2DB - FIT - HCMUS 150


Introduction2DB - FIT - HCMUS 151

You might also like