Professional Documents
Culture Documents
Practice
2014/11/18
Drpengxg@126.com
Relational Algebra
Chapter Outline:
3.1
3.2
3.3
3.4
3.5
3.6
2014/11/18
Relational Algebra(RA)
Simple and Complex Queries using RA
Structure Query Language(SQL)
Creating SQL Database and Tables
Selecting Data
Data InsertionUpdating and Deletion
An Introduction to Database
Drpengxg@126.com
System
Relational Algebra
Drpengxg@126.com
Union ()
2014/11/18
Drpengxg@126.com
Example
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
Example
Notice that Difference has a directionality to it, e.g. RS and S-R are not the same thing.
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
Intersection()
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
Example
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
Cartesian Product ()
The Cartesian product or cross-product is a binary
operation that is used to combine two relations.
Assuming R and S as relations with n and m attributes
respectively, the Cartesian product, R S can be
written as,
R (A1, A2, , An) S (B1, B2, , Bm)
The result of the above set operation is,
Q (A1, A2, , An, B1, B2, , Bm)
Where,
Degree (Q) = n + m
count(Q) = Number of tuples in R * Number of tuples in S.
2014/11/18
Drpengxg@126.com
Example
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
SNAME
GPA
AGE
DEPARTMENTID
2007001003
CHENGLICHONG
3.33
20
31
2007001005
ZHONGWEILONG
3.62
20
33
2007001006
WUYUANLANG
4.01
20
33
2006001001
LUOZI
3.12
20
34
2006001002
GUOHUAXIAN
3.21
21
34
2006001004
LELINGBING
3.75
21
2007002001
ZHUJIANGUO
3.05
19
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
Figure 3.11 SC
SSN
CNO
GRADE
2007001003
001
78
2007001003
002
67
2007001003
003
89
2007001003
004
65
2007001005
001
75
2007001005
002
90
2007001006
002
80
2006001001
002
70
2006001001
004
90
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
The new relation created as the result of this operation consists of one tuple:
SSN
SNAME
GPA
AGE
2007002001
ZHUJIANGUO
3.05
19
2014/11/18
Drpengxg@126.com
DEPARTMENTID
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
2014/11/18
Drpengxg@126.com
Drpengxg@126.com
An Introduction to Database
Drpengxg@126.com
System
Join ()
Join ()
EquiJoin
Natural Join
Left Outer Join
Right Outer Join
Full Outer Join
Theta
2014/11/18
Join
Drpengxg@126.com
Join ()
Format: R join-condition S
Semantics: Return all tuples in R S which
satisfy the join condition.
Derivation from existing operators:
R join-condition S = join-condition(R S)
Format of join condition:
R.A op S.B
2014/11/18
Drpengxg@126.com
Equijoin ( )
R1 R 2
x y
2014/11/18
Drpengxg@126.com
Equijoin
a
d
b
b
b
c
B
b
c
a
C
c
d
d
R R.B = S.B S
A R.B
S.B
a
d
b
b
b
c
b
b
c
2014/11/18
Drpengxg@126.com
c
c
d
Example
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
2014/11/18
Drpengxg@126.com
Example
a1
b1
a1
b2
a2
b3
a2
b4
12
R
2014/11/18
b1
b2
b3
10
b3
b5
S
Drpengxg@126.com
Natural Join
R
2014/11/18
S
A
a1
b1
a1
b2
a2
b3
10
a2
b3
Drpengxg@126.com
R1 R 2
x y
2014/11/18
Drpengxg@126.com
Theta Join
R
CE
2014/11/18
R.B
S.B
a1
b1
b2
a1
b1
b3
10
a1
b2
b2
a1
b2
b3
10
a2
b3
b3
10
Drpengxg@126.com
Example
To find all students name and selected
courses NO, we need student and SC
relations
1.
SNAME ,CNO ( STUDENT .SSN SC .SSN ( STUDENT SC ))
SNAME,CNO ( STUDENT SC )
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
Drpengxg@126.com
Left outer-join
R1
R2 is similar to a natural join but keep all
dangling tuples of R1.
Right Outer-Join
R1
R2 is similar to a natural join but keep all
dangling tuples of R2.
Outer Join (full outer-join)
R1
R2 is similar to a natural join but keep all
dangling tuples of both R1 and R2.
The advantages of outer join is to take the union of
tuples from two relations that are not union
compatible.
2014/11/18
Drpengxg@126.com
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
Division
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
pno
p1
p2
p3
p4
p1
p2
p2
p2
p4
A
2014/11/18
pno
p2
B1
pno
p2
p4
B2
pno
p1
p2
p4
B3
sno
s1
s2
s3
s4
sno
s1
s4
sno
s1
A/B1
A/B2
A/B3
Drpengxg@126.com
Another Example
CNO
CNAME
CREDIT
001
Math
002
Multimedia
003
Computer network
004
Software engineering
005
Bioinformatics
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
cno(course)
2.We can also find all SSN, cno pairs for which
the student has selected courses by:
SSN ,cno ( sc )
An Introduction to Database
Drpengxg@126.com
System
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
Example
Example 1: Get supplier names for
suppliers who supply part P2:
An Introduction to Database
Drpengxg@126.com
System
CON
Example 3:Get supplier names for
suppliers who supply all parts:
sname (( s #, p # ( SP) P )S )
Example 4:Get supplier numbers for
suppliers who supply at least all those
parts supplied by supplier S2:
An Introduction to Database
Drpengxg@126.com
System
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
Cont
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
CON
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
DROP DATABASE
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
CREATE
Create new objects (tables, views, etc.) in the
database
ALTER
Change the structure of an existing object
DROP
Remove the object from the database, (all its data
plus any reference to it in the data dictionary)
2014/11/18
Drpengxg@126.com
CREATE TABLE
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
CON...
The create table statement does exactly that:
CREATE TABLE <table name> (
<attribute name 1> <data type 1>,
...
<attribute name n> <data type n>);
The data types that you will use most frequently are
VARCHAR or CHAR for variable or fixed length strings;
numeric types such as NUMBER or INTEGER; and DATE
or related types. Data type syntax is variable from
system to system.
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
Example
If we have a table for recording students information,
then the columns may include information such as
students number(SSN), name(SNAME), birth
date(BirthDate), depart number(DEPTNO).
CREATE TABLE student
(SSN
NUMBER
NOT NULL,
SNAME CHAR(10) ,
BirthDate DATE ,
DEPTNO
NUMBER);
Note that: The NOT NULL constraint enforces the
field of SSN to always contain a value.
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
ALTER TABLE
The SQL ALTER TABLE command is used
to modify the definition (structure) of a
table by modifying the definition of its
columns. The ALTER command is used
to perform the following functions.
1) Add, drop, modify table columns
2) Add and drop constraints
3) Enable and Disable constraints
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
ADD COLUMN
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
DROP COLUMN
To drop a column
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
MODIFY COLUMN
To modify a column
An Introduction to Database
Drpengxg@126.com
System
DROP TABLE
2014/11/18
An Introduction to Database
Drpengxg@126.com
System
2014/11/18
Drpengxg@126.com
CREATE VIEW
The Syntax to create a view is
CREATE VIEW view_name
AS
SELECT column_list
FROM table_name [WHERE condition];
The SELECT statement is used to define the columns and
rows that you want to display in the view
2014/11/18
Drpengxg@126.com
Example
To create a view on the student table the
SQL statement would be like:
CREATE VIEW view_student
AS
SELECT SSN, SNAME
FROM student;
Where SNAME LIKE ZHANG%
With CHECK_OPTION
Drpengxg@126.com
ALTER VIEW
2014/11/18
Drpengxg@126.com
Example
A one more column by the name of
Address of student table.
ALTER VIEW view_student
AS
SELECT sno, sname,Address
FROM student;
2014/11/18
Drpengxg@126.com
DROP VIEW
2014/11/18
Drpengxg@126.com
Advantages of Views
2014/11/18
Drpengxg@126.com
Disadvantages of Views
2014/11/18
Drpengxg@126.com
Specifying constraints
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
UNIQUE Constraint
Drpengxg@126.com
Drpengxg@126.com
CON
The following SQL creates a PRIMARY KEY
on the " SSN " column when the "
student " table is created:
CREATE TABLE student
(SSN
NUMBER
PRIMARY KEY,
SNAME
CHAR(10) NOT NULL ,
BirthDate DATE ,
DEPTNO NUMBER);
2014/11/18
Drpengxg@126.com
CON
2014/11/18
Drpengxg@126.com
Drpengxg@126.com
Example
To create a SC table,SC(ssn,cno,grade)
the primary key is (ssn, cno) .
CREATE TABLE SC(
ssn NUMBER,
cno NUMBER,
Grade NUMBER,
Primary key (ssn , Cno),
FOREIGN KEY(ssn ) REFERENCES student(ssn ),
FOREIGN KEY(Cno) REFERENCES Course(Cno))
2014/11/18
Drpengxg@126.com
CHECK Constraint
2014/11/18
Drpengxg@126.com
DEFAULT Constraint
2014/11/18
Drpengxg@126.com
CON
The DEFAULT constraint can also be used to
insert system values, by using functions like
GETDATE():
CREATE TABLE SC
(
CNO NUMBER NOT NULL,
SSN NUMBER NOT NULL,
GRADE NUMBER,
TakeCourseDate date DEFAULT GETDATE(),
PRIMARKY KEY(SSN,CNO)
FOREIGN KEY (SSN) REFERENCES student(SSN)
)
2014/11/18
Drpengxg@126.com
Creating indexes
Indexes can be created against a table to
make searches more efficient.
A book index allows you to find
information without having to read
through the whole book.
A database index enables the database
application to find data quickly without
having to scan the whole table.
2014/11/18
Drpengxg@126.com
CON
Example
CREATE INDEX StudentIndex
ON student (SNAME)
2014/11/18
Drpengxg@126.com
SNAME
GPA
AGE
DEPTNO
2007001003
CHENGLICHONG
3.33
20
31
2007001005
ZHONGWEILONG
3.62
20
33
2007001006
WUYUANLANG
4.01
20
2006001001
LUOZI
3.12
20
33
34
2006001002
GUOHUAXIAN
3.21
21
34
2006001004
LELINGBING
3.75
21
2007002001
ZHUJIANGUO
3.05
19
Figure 3.5:student
2014/11/18
Drpengxg@126.com
CNAME
CREDIT
001
Math
002
Multimedia
003
Computer network
004
Software engineering
005
Bioinformatics
2014/11/18
Drpengxg@126.com
Figure 3.11 SC
2014/11/18
SSN
CNO
GRADE
2007001003
001
78
2007001003
002
67
2007001003
003
89
2007001003
004
65
2007001005
001
75
2007001005
002
90
2007001006
002
80
2006001001
002
70
2006001001
004
90
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
CON
The full syntax of the SELECT statement is
complex as follows:
SELECT select_list
FROM table_source
[ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]
2014/11/18
Drpengxg@126.com
CON
2014/11/18
Drpengxg@126.com
Single Table
1)Retrieve specific columns, all rows
(1)Retrieve specific columns
The query retrieves a subset of columns and
all rows from a table.
[Example 1]
Find the SSN, SName and GPA of all students
select SSN, SName, GPA
from Student
2014/11/18
Drpengxg@126.com
CON
(2)Retrieve all columns, all rows
The query retrieves all columns and rows from a
table
[Example 2]
Query all the information of all the students.
Select * from Students
Or
select SSN, SName, GPA,AGE,DEPTNO
from Student
2014/11/18
Drpengxg@126.com
CON
(3)Retrieve calculated columns
The query retrieves some columns by
computing.
[Example 3]
Query the name and the birthday of
students.
Select SName,2011-AGE
From Student
2014/11/18
Drpengxg@126.com
CON
The results will be shown in Fig.21:
Figure 21 Query Result of Example 3
2014/11/18
SName
(No Name)
CHENGLICHONG
1990
ZHANGWEILONG
1990
Drpengxg@126.com
Alias
[Example 4]
Select SName,2011-AGE as Birthdate
From Student
The results will be shown in Fig.21:
2014/11/18
SName
Birthdate
CHENGLICHONG
1990
ZHANGWEILONG
1990
Drpengxg@126.com
CON
(4)Use of Distinct
The DISTINCT keyword can be used to
return only distinct (different) values.
[Example 5]
If we list the AGE of all students from the above
table.
AGE
Select AGE
20
20
From Student
20
20
21
21
19
2014/11/18
Drpengxg@126.com
CON
[Example 6]
Rewriting the query as:
SELECT DISTINCT AGE
From Students
2014/11/18
Drpengxg@126.com
Drpengxg@126.com
2014/11/18
SSN
SNAME
2007001003
GPA
AGE
DEPTNO
CHENGLICHONG 3.33
20
31
2007001005
ZHONGWEILONG 3.62
20
33
2007001006
WUYUANLANG
4.01
20
2006001001
LUOZI
3.12
20
33
34
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
[Example 9]
We would use the negated version to
retrieve any members of students with a
GPA outside between 3 and 3.5 as:
Select *
From student
Where GPA NOT BETWEEN 3 AND 3.5
2014/11/18
Drpengxg@126.com
[Example 10]
We want to select the students with an AGE
equal to 19 or 20 in the table above.
Select * from student
Where AGE IN (19, 20)
2014/11/18
Drpengxg@126.com
SNAME
2007001003
GPA
AGE
DEPTNO
CHENGLICHONG 3.33
20
31
2007001005
ZHONGWEILONG 3.62
20
33
2007001006
WUYUANLANG
4.01
20
2006001001
LUOZI
3.12
20
33
34
2007002001
ZHUJIANGUO
3.05
19
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
CON...
[Example 11]
To match all strings that begin with the
word 'zhang', you would use the pattern
'zhang%':
SELECT SNAME
FROM STUDENT
WHERE SNAME LIKE 'zhang%';
2014/11/18
Drpengxg@126.com
CON...
[Example 12]
To match all strings that end with
'ZHANG', the pattern would look like:
'%zhang':
SELECT SNAME
FROM STUDENT
WHERE SNAME LIKE '%zhang';
2014/11/18
Drpengxg@126.com
CON...
[Example 13]
To match all strings where the word
'zhang' occurs somewhere: '%zhang%':
SELECT SNAME
FROM STUDENT
WHERE SNAME LIKE '%zhang%';
2014/11/18
Drpengxg@126.com
CON...
[Example 14]
To match strings with that begin with
zhang consisting of exactly eight
characters zhang _ _ _
SELECT SNAME
FROM STUDENT
WHERE SNAME LIKE 'zhang _ _ _;
2014/11/18
Drpengxg@126.com
CON...
[Example 15]
To match strings that there are must be
exactly four characters in the string, the
END of which must be an _ _ _ g
SELECT SNAME
FROM STUDENT
WHERE SNAME LIKE ' _ _ _g;
2014/11/18
Drpengxg@126.com
CON...
[Example 16]
To match strings that there are at least one
character between 'a' and 'c' a_%c
SELECT SNAME
FROM STUDENT
WHERE SNAME LIKE 'a_%c';
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
CON...
Drpengxg@126.com
CON...
[Example 18]
If we select only the records with no NULL
values in the " DEPTNO " column, we
will have to use the IS NOT NULL
operator:
SELECT * FROM student
WHERE DEPTNO IS NOT NULL
2014/11/18
Drpengxg@126.com
Drpengxg@126.com
CON...
[Example 19]
If we want to select only the persons with
AGE equal to "20" AND GPA greater
than "3", we use the following SELECT
statement:
SELECT *
FROM student
WHERE AGE=20 AND GPA>3.5
2014/11/18
Drpengxg@126.com
[Example 20]
If we want to sort our Users table by the GPA column, we
have to use the following ORDER BY SQL statement:
SELECT * FROM student
ORDER BY GPA
2014/11/18
Drpengxg@126.com
CON...
[Example 21]
Now we want to select all the persons
from the table above, however, we want
to sort the AGE descending by their last
name.
SELECT *
FROM student
ORDER BY AGE DESC
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
COUNT function
The COUNT function counts the number of rows
in a table, or the number of distinct values for
a given column. It can operate, therefore, at
the column or row level.
[Example 22]
To count the number of students names in the
Student table :
SELECT COUNT(SNAME)
FROM Student
2014/11/18
Drpengxg@126.com
CON...
[Example 23]
To count the number of distinct students names
represented in the students table, issue the following:
SELECT COUNT(DISTINCT SNAME)
FROM Student
2014/11/18
Drpengxg@126.com
AVG function
The AVG function computes the average
of the values for the column or
expression specified as an argument.
This function operates only on numeric
arguments.
[Example 24]
The following example calculates the
average GPA of the students table:
SELECT AVG(GPA)
FROM Student
2014/11/18
Drpengxg@126.com
CON...
[Example 25]
If you want to get the average GPA for a
particular set Students you can do it this
way:
SELECT AVG(GPA)
FROM Student
WHERE DEPTNO=33
2014/11/18
Drpengxg@126.com
MIN function
The MIN function returns the smallest
value in the specified column or
expression.
[Example 26]
To retrieve the smallest GPA given to any
student, issue this SQL statement:
SELECT MIN(GPA)
FROM Student
2014/11/18
Drpengxg@126.com
CON...
The MAX function returns the largest
value in the specified column or
expression.
[Example 27]
The following SQL statement determines
the largest GPA :
SELECT MAX(GPA)
FROM Student
2014/11/18
Drpengxg@126.com
CON...
[Example 28]
It returns the highest GPA belongs to a
student in DEPTNO 32:
SELECT MAX(GPA)
FROM student
WHERE DEPTNO=32
2014/11/18
Drpengxg@126.com
SUM function
The accumulated total of all values in the
specified column or expression are
returned by the SUM column function.
[Example 29]
For example, the following SQL statement
calculates the total GPA for the
students:
SELECT SUM(GPA)
FROM Student
2014/11/18
Drpengxg@126.com
GROUP BY
2014/11/18
Drpengxg@126.com
CON...
[Example 30]
Want to find the average grade of each
student.
SELECT Avg(grade)
FROM SC
GROUP BY SSN
2014/11/18
Drpengxg@126.com
HAVING Clause
The HAVING clause was added to SQL
because the WHERE keyword could not
be used with aggregate functions.
SQL HAVING Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
2014/11/18
Drpengxg@126.com
CON...
[Example 31]
Now we want to find if any of the
students have an average grade of
more than 81.
SELECT Avg(grade)
FROM student
GROUP BY SSN
HAVING Avg(grade)>80
2014/11/18
Drpengxg@126.com
CON...
[Example 32]
Now we want to find if the students
"2007001006" or "2006001001" have
an average grade of less than 81.
SELECT SSN,Avg(grade)
FROM student
WHERE SSN='2007001006' OR SSN =2006001001
GROUP BY SSN
HAVING Avg(grade)<81
2014/11/18
Drpengxg@126.com
Drpengxg@126.com
CON...
6). When using the AVG, MAX, MIN and SUM functions on
nullable columns, all occurrences of NULL are eliminated
before applying the function.
7). You can use the DISTINCT keyword with all aggregate
functions to eliminate duplicates before applying the
given function. DISTINCT has no effect, however, on the
MAX and MIN functions.
8). You can use the ALL keyword to indicate that duplicates
should not be eliminated. ALL is the default.
9). An aggregate function can be specified in a WHERE
clause only if that clause is part of a sub query of a
HAVING clause. Additionally, every column name
specified in the expression of the aggregate function
must be a correlated reference to the same group.
2014/11/18
Drpengxg@126.com
Multiple Tables
SQL allows us to query multiple tables in
one SELECT-FROM-WHERE statement.
The SELECT and WHERE can refer to the
attributes of any of the tables once we
list each table in the FROM clause.
ANSI standard SQL specifies four types
of JOINs: INNER, OUTER, LEFT, and
RIGHT.
a table (base table, view, or joined
table) can JOIN to itself in a self-join.
2014/11/18
Drpengxg@126.com
CON...
2014/11/18
SSN
SNAME
2007001003
GPA
AGE
DEPTNO
CHENGLICHONG
20
31
2007001005
ZHONGWEILONG
20
33
2007001006
WUYUANLANG
4.01
20
33
2006001001
LUOZI
3.12
20
34
2006001001
GUOHUAXIAN
3.21
21
34
2007002001
ZHUJIANGUO
19
Drpengxg@126.com
CON...
DEPTNO
DEPTNAME
31
Computer Science
33
Information Engineering
34
Civil Engineering
35
Life Science
2014/11/18
Drpengxg@126.com
INNER JOIN
Inner join creates a new result table by
combining column values of two tables
(A and B) based upon the joinpredicate.
2014/11/18
Drpengxg@126.com
CON...
2014/11/18
Drpengxg@126.com
CON...
[Example 33]
The following example shows a query
using the inner join statement:
SELECT *
FROM student, department
WHERE student.DeptID =
department.DeptID
2014/11/18
Drpengxg@126.com
CON...
Student. Student.SNA Student. Student. Student.D
SSN
ME
GPA
AGE
EPTID
Department.D Department.DEP
EPTID
TNAME
200700
1003
CHENGLIC
HONG
20
31
31
Computer
Science
200700
1005
ZHONGWEI
LONG
20
33
33
Information
200700
1006
WUYUANL 4.01
ANG
20
200600
1001
LUOZI
20
200600
1001
GUOHUAXI 3.21
AN
2014/11/18
Engineering
3.12
33
33
Information
Engineering
34
34
Civil
Engineering
21
34
34
Civil
Engineering
Drpengxg@126.com
OUTER JOIN
The OUTER JOIN clause differs from the
standard JOIN clause (also known as
the INNER JOIN clause) in that rows are
returned even when there are no
matches through the JOIN critieria.
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
CON...
Student. Student.SNA Student. Student.
SSN
ME
GPA
AGE
Student.D
EPTID
Department.D Department.DEP
EPTID
TNAME
200700
1003
CHENGLIC
HONG
20
31
31
Computer
Science
200700
1005
ZHONGWEI
LONG
20
33
33
Information
Engineering
200700
1006
WUYUANL
ANG
4.01
20
33
33
Information
Engineering
200600
1001
LUOZI
3.12
20
34
34
Civil
Engineering
200600
1001
GUOHUAXI 3.21
AN
21
34
34
Civil
Engineering
ZHUJIANG
UO
19
200700
2001
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
CON...
Student.S
SN
Student.SNAM
E
Student.G Student.A
PA
GE
Stude
nt.
DEPT
ID
Departm
ent.
DEPTID
Department.DEPT
NAME
20070010 CHENGLICH
03
ONG
20
31
31
Computer Science
20070010 ZHONGWEIL
05
ONG
20
33
33
Information
Engineering
20070010 WUYUANLA
06
NG
4.01
20
33
33
Information
Engineering
20060010 LUOZI
01
3.12
20
34
34
Civil Engineering
20060010 GUOHUAXIA
01
N
3.21
21
34
34
Civil Engineering
35
Life Science
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
Departm
ent.
DEPTID
Department.DEPT
NAME
20070010 CHENGLICH
03
ONG
20
31
31
Computer Science
20070010 ZHONGWEIL
05
ONG
20
33
33
Information
Engineering
20070010 WUYUANLA
06
NG
4.01
20
33
33
Information
Engineering
20060010 LUOZI
01
3.12
20
34
34
Civil Engineering
20060010 GUOHUAXIA
01
N
3.21
21
34
34
Civil Engineering
35
Life Science
20070020 ZHUJIANGU
01
O
2014/11/18
19
Drpengxg@126.com
Alias
Table names can be abbreviated in order to simplify what is
typed in with the query.
[Example 36]: Find the names and GPAs of all students
who take CourseA.
select SName, GPA
from Students s, Enrollment e, Courses c
where Title = 'CourseA'
and s.SID = e.SID
and e.Course_no = c.Course_no
2014/11/18
Drpengxg@126.com
Cont
[Example 37]: Find all pairs of students
who have the same GPA.
select s1.SID, s2.SID
from Students s1, Students s2
where s1.GPA = s2.GPA
and s1.SID < s2.SID
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
Cont
[Example 39]Find the names and GPAs of all
students who take database systems.
select SName, GPA from Student, sc, Course
where cname= `DBS and Student.ssn = sc.ssn
and sc.cno= Course.cn
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
Union
[Example 40]: Find the names of those
people who are either select lesson
21001001 or lesson 22003002
(select SName from student
where ssn=any (select ssn from sc
where cno=21001001) )
union
(select SName from students
where ssn=any (select ssn from sc
where cno=22003002) )
2014/11/18
Drpengxg@126.com
Cont
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
Sub queries
A subquery is a SELECT statement that is
nested within another SQL statement.
Return any number of values
Can be found in, the column list of a
SELECT statement, a FROM, GROUP BY,
HAVING, and/or ORDER BY clauses of a
SQL statement.
2014/11/18
Drpengxg@126.com
CON
[Example 48]
To find the names of every student who studies in the
same department as a person called Jones .
SELECT SNAME
FROM student
WHERE DEPTNO =
(SELECT DEPTNO
FROM student
WHERE SNAME = 'JONES')
2014/11/18
Drpengxg@126.com
CON
Or as a join statement, like this:
SELECT e1. SNAME
FROM student e1,student e2
WHERE e1. DEPTNO = e2. DEPTNO
AND e2. SNAME = 'JONES'
2014/11/18
Drpengxg@126.com
CON
[Example 49]: Find the names of all
students who take at least one
course titled multimedia.
select sName
from Student s, SC e
where s.ssn = e.ssn and e.cno in
(select cno from Course
where Cname = ' multimedia')
2014/11/18
Drpengxg@126.com
Nesting levels
SELECT select-list
FROM .........
WHERE (select-field1, selectfield2,.........)
comparison operator
(SELECT select-list2
FROM........
WHERE (..........))
2014/11/18
Drpengxg@126.com
comparison-operator:
2014/11/18
Drpengxg@126.com
Cont
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
Cont
(2)
select SName
from Student where ssn in
(select ssn from sc
where Cno in
(select Cno from Course
where cname = multimidea'))
2014/11/18
Drpengxg@126.com
Correlated Query
2014/11/18
Drpengxg@126.com
CON
[Example 50]:
Find the names of all students who has NOT select a
Course with CNO=1.
SELECT Sname
FROM Student
WHERE NOT EXISTS
(SELECT *
FROM SC
Drpengxg@126.com
Cont
Evaluation of correlated queries: for each
tuple in the outer query, evaluate the
inner query once.
The scoping rule of attribute names:
select ... from R1, ..., Rk where ...
(select ... from S1, ..., Sm
where S1.A = R2.B and C = D and ... )
(1) If attribute C is not an attribute in S1,
..., Sm, and C is an attribute in some Ri,
then C = Ri.C.
(2) If C is in both Sj and Ri, then C = Sj.C.
2014/11/18
Drpengxg@126.com
Cont
[Example 51]: : Find the names of those
students who are 18 or younger and
whose GPA is higher than the GPA of
some students who are 20 or older.
select sName from Student
where Age <= 18 and GPA >some
(select GPA from Student
where Age >= 20)
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
Exists
[Example 52]: Find all students who
take at least one course.
select * from Student s where exists
(select * from sc
Where ssn= s.ssn)
2014/11/18
Drpengxg@126.com
exists ( ) is
empty.
exists ( ) is
not exists (
empty.
not exists (
empty.
2014/11/18
Drpengxg@126.com
Cont
The previous query is equivalent to:
(1)
select s.*
from Student s, sc e
where s.SID = e.SID
(2)
select * from Student where ssn in
(select ssn from sc)
2014/11/18
Drpengxg@126.com
Cont
[Example 53]: Find all students who do
not take 21003001.
select * from Student s where not exists
(select * from sc
where ssn= s.ssn
and Cno = '21003001.')
This query is equivalent to:
select * from Student where ssn not in
(select ssn from sc
where Cno = '21003001.')
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
[Example 54]:
Find the names of all students who study in the
same department with a student with sname=
liucheng .
SELECT ssnSnameDEPTNO
FROM Student S1
WHERE EXISTS
SELECT *
FROM Student S2
WHERE S2.DEPTNO = S1.DEPTNO AND
S2.Sname = liucheng '
2014/11/18
Drpengxg@126.com
Cont
[Example 55]: Find all the students who
take all courses
select * from Student s
where not exists
(select * from Course c
where not exists
(select * from sc
where ssn= s.ssn
and Cno = c.Cno))
2014/11/18
Drpengxg@126.com
Cont
[Example 56] : Find the names and GPAs of
those students who take all courses taken
by a student with SID = 2006002001.
2014/11/18
Drpengxg@126.com
2014/11/18
Drpengxg@126.com
Cont
TRUNCATE or TRUNC
Converts the first numeric argument by truncating it to the
right of the decimal place by the integer number
specified in the second numeric argument.
[Example 34]
SELECT TRUNC(3.014015,2)
FROM SYSIBM.SYSDUMMY1;
Drpengxg@126.com
Cont
ROUND
Rounds the first numeric argument to the
number of places specified in the second
argument.
UPPER or UCASE
Converts a character string into all uppercase
characters
LOWER or LCASE
Converts a character string into all lowercase
characters.
2014/11/18
Drpengxg@126.com
Cont
SUBSTR
Returns the specified portion of a character column from
any starting point to any ending point.
[Example 45]
SNAME is a CHAR(20) column in sample table STUDENT.
When SNAME has the value ZHONGWEILONG:
Function:
Returns:
----------------------------------SUBSTR(SNAME,2,3)
-- 'HON'
SUBSTR(SNAME,2)
-- ' HONGWEILONG'
SUBSTR(SNAME,2,12)
-- ' HONGWEILONG ' followed by one blank
SUBSTR(SNAME,13)
-- a zero-length string
SUBSTR(SNAME,13,4)
-- four blanks
2014/11/18
Drpengxg@126.com
Cont
LTRIM
The LTRIM function removes blanks or
hexadecimal zeros from the beginning of
a string expression.
RTRIM
The RTRIM function removes blanks or
hexadecimal zeros from the end of a
string expression.
2014/11/18
Drpengxg@126.com
Cont
CHAR
The CHAR function returns a fixed-length
character string representation of the
argument .
[Example 46]
SELECT CHAR(CURRENT DATE)
CURRENT DATE is a DATE type which displays current date
time of the system server. When it represents the date
15 March 2011, the example returns the string value
'3/15/2011 in character string .
2014/11/18
Drpengxg@126.com
Cont
CONCAT
Drpengxg@126.com
Cont
WEEK
The WEEK function returns an integer in the
range of 1 to 54 that represents the week of
the year. The week starts with Sunday, and
January 1 is always in the first week.
DAY
The DAY function returns the day part of a value.
If the argument is a date, timestamp, or string
representation of either, the result is the day
part of the value, which is an integer between
1 and 31
2014/11/18
Drpengxg@126.com
Cont
DATE
The DATE function converts a value representing
a date to a DB2 date. The value to be
converted can be a DB2 timestamp, a DB2
date, a positive integer, or a character string.
MONTH
The MONTH function returns the month part of a
value. If the argument is a date, timestamp, or
string representation of either, the result is the
month part of the value, which is an integer
between 1 and 12.
2014/11/18
Drpengxg@126.com
Cont
TIME
The TIME function Converts a value representing
a valid time to a DB2 time. The value to be
converted can be a DB2 timestamp, a DB2
time, or a character string.
YEAR
The YEAR function returns the year part of a
value that is a character or graphic string. The
value must be a valid string representation of a
date or timestamp.
2014/11/18
Drpengxg@126.com