SQL Workshop
SQL Workshop
2010
Schedule
DAT module
http://www.hkedcity.net/teachernet/sharing/forum/index.phtml?forum_id=52 5
DAT Module
What is SQL?
SQL Scope
DDL:
i) Create, change and delete
database object (e.g. tables,
indexes, views)
ii) Command Keywords:
CREATE, DROP,ALTER
Only select is
allowed in
WebSAMS!
DML:
i) Syntax for executing
queries
DCL:
Control access right
select * from
TB_STU_STUDENT
e.g. GRANT
10
Tables
Fields
Records
Keys
Views
Indexes
11
Tables
VW_STU_LATESTSTUDENT
12
Fields
13
Records
Table:
Records
(rows)
Sex
1293
2006
1A
John
1293
2006
1B
Mary
1293
2006
1C
Ken
.
14
Keys
Primary key: A Primary Key is a field (or a group of fields ) that can
be used to identify a unique row in a table.
Foreign key: A Foreign Key in one table refers to the primary key
of another table.
For example, I write an email to introduce a book to you, with ISBN of the
book (not the entire text of the book). The ISBN is the primary-key of the
book, and it is used as a foreign-key in the e-mail.
15
Indexes
16
Table:
(columns)
Student
name
Sex
Records 1293
2006
1A
John
(rows)
1293
2006
1B
Mary
1293
2006
1C
Ken
SQL :
create index .
*School
ID
*Schyear
*Class
*Class
no
1293
2006
1A
1293
2006
1B
1293
* = Keys
2006
1C
Index:
17
18
Table: TB_SCH_SCHCLASS
19
Related Information
Table Structure
Field description
Data type
Key
Index
Table Structure
Table
Field of Record
Index
21
Data Types
DATE, TIMESTAMP
Mandatory
23
25
SELECT statement
SELECT column_list
FROM table_list
[WHERE search_condition]
[GROUP BY column_list]
constrains
[HAVING search_condition]
[ORDER BY {column_list | column_index}]
Keys:
[ ] - optional
{ } - list of parameters
| - or
Notice:
The result set usually becomes smaller in size
when no. of constrains increase
26
Simplest Query
SELECT column_list FROM table_list
27
Sample Queries
SELECT * FROM TB_STU_Student
Sample Queries
select
enname as 'English Name',
chname 'Chinese Name',
enname + ' (' + chname + ')' Student
from TB_STU_STUDENT
Syntax:
Column-name AS alias
Column-name alias
29
Table alias
select
a.enname AS 'English Name',
a.chname 'Chinese Name',
a.enname + ' (' + a.chname + ')' Student
from TB_STU_STUDENT a
30
ORDER BY clause
select distinct classcode
from TB_STU_STUDENT
order by classcode
Suggested answers:
select classcode, classno, enname, chname
from TB_STU_STUDENT
order by classcode, classno
32
[WHERE search_condition]
fields
select
Table (or table list)
from
where
An expression
which return true or
false
order by
fields
33
Sample Queries
select classcode, classno, enname, chname
from TB_STU_STUDENT
where classlvl ='S1'
order by classcode, classno
34
Membership
Pattern Match
NULL
IS [NOT] NULL
35
Sample Queries
SELECT ClassCode, EnName, ChName
FROM TB_STU_Student
WHERE ClassCode BETWEEN '4' AND '5Z'
ORDER BY ClassCode, EnName
SELECT ClassCode, EnName, ChName
FROM TB_STU_Student
WHERE ClassLvl IN (S4', S5')
ORDER BY ClassCode, EnName
36
Sample Queries
SELECT ClassCode, EnName, ChName
FROM TB_STU_Student
WHERE EnName LIKE 'CHAN %'
ORDER BY EnName
SELECT ClassCode, EnName, ChName
FROM TB_STU_Student
WHERE HKID IS NULL
ORDER BY ClassCode, EnName
37
select .
from .
from .
T or T = True
T and T = True
F or F = False
F and F = False
T or F = True
T and F = False
F or T = True
F and T = False
38
where
where
or
or
or
where
39
where
and
or
or
where
40
where
and (
or
and
where
41
Sample Queries
SELECT ClassCode, EnName, ChName
FROM TB_STU_Student
True or False?
WHERE
ClassLvl IN (S4', S5')
AND
True or False?
EnName LIKE 'CHAN %'
ORDER BY ClassCode, EnName
42
Sample Queries
SELECT ClassCode, ClassNo, EnName, ChName,
STRN, HKID
FROM TB_STU_Student
True or False?
WHERE
( HKID IS NULL OR STRN IS NULL )
True or False?
AND
ClassCode BETWEEN '1' AND '2Z'
True or False?
ORDER BY ClassCode, ClassNo
43
YEAR(date_field)
MONTH(date_field)
DAY(date_field)
NOW()
getDate()
DateFormat(date_field, date_format)
44
Sample Queries
SELECT
DOB,
YEAR(DOB),
MONTH(DOB),
DAY(DOB),
NOW(),
DATEFORMAT(DOB, 'DD/MM-YYYY')
FROM TB_STU_Student
Notice:
A field can be selected more than once,
depends on the data set you need
45
UPPER(text_field)
LOWER(text_field)
TRIM(text_field)
LEFT(text_field, length)
RIGHT(text_field, length)
SUBSTRING(text_field, start position, length)
LENGTH(text_field)
46
Sample Queries
SELECT
EnName,
LOWER(EnName),
TRIM(EnName),
SUBSTRING(EnName, 3, 5),
LENGTH(EnName)
FROM TB_STU_Student
47
Exercise 2 ( substring )
Find out the classcode, class no. , student name, first 6 digits of strn
of each student, order by class and class no., and format the student
name as , e.g. Chan Tai Man ()
Hints: How to check the field name? Go to Data Mgmt > Report
Use function: substring(text_field, start position, length)
Syntax: text_field + ( + text_field2 + )
Suggested Answer:
select classcode, classno, enname +' ('+chname+')' ,
substring( strn, 2, 6 ) 'first 6 digits'
from TB_STU_STUDENT
order by classcode, classno
48
Exercise 3 ( where )
Also display the date of birth field, with format DD/MM/YYYY
Filter the students with birth year 1999,
and the class code of the student should not be empty.
Hints:
Use function: dateformat( date_field, 'DD/MM/YYYY')
Year(field_name)
Suggested answers:
select classcode, classno, enname +' ('+chname+')' , substring(
strn, 2, 6 ) 'first 6 digits' , dateformat( dob, 'DD/MM/YYYY')
from TB_STU_STUDENT
where YEAR(dob) = ? and classcode <> ''
order by classcode, classno
49
Aggregate Functions
COUNT([DISTINCT] field)
SUM([DISTINCT] field)
AVG([DISTINCT] field)
MAX(field)
MIN(field)
50
GROUP BY clause
[GROUP BY column_list]
When you use aggregate functions in the
SELECT clause to produce summary
information, you use the GROUP BY clause
to divide the information into distinct groups.
The GROUP BY clause is optional.
51
ClassCode
EnName
1A
Mary
1A
John
1A
Ken
1B
David
1B
Peter
1C
Calvin
Count(EnNam)
3
2
1
52
Sample Queries 1
This SQL find out the number of student in each class:
select
ClassCode 'Class',
COUNT(EnName) 'No. of Student'
from TB_STU_Student
group by ClassCode
order by ClassCode
Think: a SQL has count(..) but no 'group by'
e.g. select count(*) from TB_STU_STUDENT
53
Sample Queries 2
This SQL find out the number of student in Form 1,
group by class and gender:
SELECT
ClassCode 'Class', Sex, COUNT(*) 'No. of Student'
FROM TB_STU_Student
WHERE ClassCode in ('1A','1B','1C','1D','1E')
GROUP BY ClassCode, Sex
ORDER BY ClassCode, Sex
54
Sample Query 3
The table TB_STU_STUSCHREC stores all the schooling record of each
student in each year.
select stuid,
MIN( firstattdate ) 'First Attend Date'
from TB_STU_STUSCHREC
group by stuid
stuid
firstattdate
Class
0001
1-9-2006
1A
0002
1-9-2005
1A
0002
31-9-2006
1B
0003
1-9-2004
2E
0003
12-9-2005
2E
0003
1-9-2006
2B
0004
1-9-2004
2B
0004
1-9-2005
2B
0005
1-9-2006
5A
0006
1-9-2006
5B
55
Exercise 4 (function )
1)
Suggested answers:
select stuid, min(firstattdate) 'First Attend Date'
from TB_STU_STUSCHREC
group by stuid
56
HAVING clause
[HAVING search_condition]
The HAVING clause is specifically associated with
the GROUP BY clause, and you use it to filter the
grouped information.
*It is similar to the WHERE clause in that the
HAVING keyword is followed by an expression that
evaluates to TRUE, FALSE or UNKNOWN.
HAVING is also an optional clause.
57
Sample Queries 1
SELECT
ClassCode 'Class',
COUNT(EnName) 'No. of Student'
FROM TB_STU_Student
WHERE ClassCode <> ''
GROUP BY ClassCode
HAVING COUNT(EnName) > 40
ORDER BY ClassCode
Note:
1) HAVING is needed only when GROUP BY exists.
2) This is a wrong syntax:
where COUNT(EnName) > 40
58
Exercise 5 ( having )
1) Continue Ex.4.1, find out the class with more than 40 students
within the class 1A, 2B and 3C and 4D :
Suggested answers:
select classcode, count( enname ) from TB_STU_STUDENT
where classcode in ( '1A', '2B' , '3C' , '4D' )
group by classcode
having count( enname ) > 40
order by classcode
2) Continue Ex.4.2, find out the student who join the school after
2006-09-02:
Hint: First find the minimum First Attend Date for each stuid, then use having
for filtering
Use function: datetime( YYYY-MM-DD )
Suggested answers:
select stuid, min(firstattdate) 'First Attend Date'
from TB_STU_STUSCHREC
group by stuid
having min(firstattdate) > datetime('2006-09-02')
59
Useful Syntax
CASE
WHEN condition1
THEN result1
WHEN condition2
THEN result3
....
ELSE
result
END
60
Sample Queries
SELECT
ClassCode, ClassNo, AreaCode,
CASE
WHEN AreaCode = 1 THEN Hong Kong'
WHEN AreaCode = 2 THEN Kowloon'
WHEN AreaCode = 3 THEN N.T.'
ELSE 'N/A'
END 'AREA'
FROM TB_STU_Student
ORDER BY ClassCode DESC, ClassNo
61
SYNTAX:
CASE
WHEN . THEN .
WHEN . THEN .
ELSE .
END
School year and time sequence should be 2006 and 1100 respectively.
Modify this SQL:
Suggested answers:
select
stuid,
subjcode,
subjcode Subject Name,
sysscore
from TB_ASR_SUBJASSESSDATA
where schyear=2006
and timeseq=1100
63
Revision:
SELECT column_list
FROM table_list
[WHERE search_condition]
[GROUP BY column_list]
constrains
[HAVING search_condition]
[ORDER BY {column_list | column_index}]
Keys:
[ ] - optional
{ } - list of parameters
| - or
64
65
Join table
Sub-query
Combining query
66
Join Table
Inner join
Left Outer join
67
Join Table
TB_NAME
*stuid
name
001
Ken
002
May
003
John
*stuid
classcode classno
001
4A
18
002
2E
004
1C
26
TB_CLASS
68
Inner Join
Example:
69
a.stuid
a.name
b.classcode b.classno
001
Ken
4A
18
002
May
2E
70
suid
stuid
suid
schyear
stuid
schyear
syspercscore
a.suid=b.suid
a.stuid=b.stuid
a.schyear=b.schyear
?
Inner join
Result set
classlevel
classcode
classno
Student
name
syspercscore
71
72
73
74
75
a.suid
b.suid
TB_HSE_COMMON (b)
SBJ
b.code_id
suid
tb_id
Code_id
Description
9999
RELATE
01
Mother
9999
RELATE
02
Father
suid
subjcode
score
9999
076
33
9999
SBJ
076
History
9999
085
45
9999
SBJ
085
Chinese
9999
9999
ECACD
1010
Drama Club
INNER JOIN
(values match both table)
Result set
a.suid
a.Stuid
a.subjcode
b.description
a.score
9999
250
076
History
33
9999
394
085
Chinese
45
76
Contd
Step 3) Combine the SQLs by inner join:
select a.schyear, a.suid, a.stuid, a.subjcode, b.en_des, a.sysscore
from TB_ASR_SUBJASSESSDATA a
join TB_HSE_COMMON b
on a.suid=b.suid and b.tb_id='SBJ' and a.subjcode = b.code_id
where a.schyear=2006 and a.timeseq=1100
77
79
A left outer join is very different from an inner join. Instead of limiting
results to those in both tables, it limits results to those in the "left" table (A).
This means that if the ON clause matches 0 records in B, a row in the result
will still be returnedbut with NULL values for each column from B.
It returns all the values from left table + only matched values from
right table.
80
TB_CLASS
001
4A
18
002
2E
004
1C
26
TB_NAME
TB_CLASS
001
Ken
001
4A
18
002
May
002
2E
003
John
004
1C
26
TB_CLASS
Result :
001
4A
18
002
2E
004
1C
26
a.stuid
a.name
b.classcode
b.classno
001
Ken
4A
18
002
May
2E
003
John
(NULL)
(NULL)
Left outer join: left table as master table , and join the right table
81
Sample Queries
Getting the parent name of each student:
This returns the name of each student, whenever he/she has a parent
record or not
select
a.EnName 'Student Name',
b.EnName 'Parent Name'
from TB_STU_Student a
left outer join TB_STU_Parent b
on
a.StuID = b.StuID and
a.SUID = b.SUID
ORDER BY a.EnName
82
TB_STU_Parent
Example
Get Student and Parent Name,
Order by class and class no.:
SUID
SELECT
a.ClassCode 'Class Code',
a.ClassNo 'Class No',
a.EnName 'Student Name,
b.EnName Parent Name
FROM TB_STU_Student a
LEFT OUTER JOIN
TB_STU_Parent b
ON
b.StuID = a.StuID and
b.SUID = a.SUID
WHERE
a.ClassCode <> ''
ORDER BY a.ClassCode, a.ClassNo
STUID
SUID
STUID
Parent
Class
No
Stud
Name
Parent Name
1A
Peter
Mr. Wong
1A
John
(NULL)
1B
Mary
Mr. Chang
1B
Tim
Mr. Lee
1B
Joe
(NULL)
1C
Jack
Mr. Yan
1C
Henry
Mr. Lau
1C
Eric
Mr. Kwan
84
VW_STU_LATESTSTUDENT and
TB_ASR_SUBJASSESSDATA
Use left outer join join.
VW_STU_LatestStudent
Left outer
join
TB_ASR_SUBJASSESSDATA
85
a.classno ,
a.chname ,
from VW_STU_LATESTSTUDENT a
left outer join TB_ASR_SUBJASSESSDATA b
on a.suid = b.suid and a.stuid = b.stuid and a.schyear = b.schyear and
b.subjcode='080' and b.timeseq = 1100
where a.schyear = 2007 and a.classlvl = 'S1'
order by a.classcode, a.classno
86
Exercise 8.2
2007Term1
Hints: subject code = 165
Suggested answer:
select
a.schyear , a.classlvl , a.classcode , a.classno ,
b.sysscore 'chi subj score', b.OMclasslvl 'chi OM',
c.sysscore 'eng subj score', c.OMclasslvl 'eng OM'
a.chname ,
from VW_STU_LATESTSTUDENT a
left outer join TB_ASR_SUBJASSESSDATA b
on a.suid = b.suid and a.stuid = b.stuid and a.schyear = b.schyear and
b.subjcode='080' and b.timeseq = 1100
left outer join TB_ASR_SUBJASSESSDATA c
on a.suid = c.suid and a.stuid = c.stuid and a.schyear = c.schyear and
c.subjcode='165' and c.timeseq = 1100
where a.schyear = 2007 and a.classlvl = 'S1'
order by a.classcode, a.classno
87
Advanced Topics
88
Sub-Query
89
SUID
STUID
SUID
STUID
Required Query
Parent
Class
code
Class
No
Stud
Name
Parent Name
SELECT
a.ClassCode 'Class Code',
a.ClassNo 'Class No',
a.EnName 'Student Name'
FROM TB_STU_Student a
LEFT OUTER JOIN TB_STU_Parent b
ON
b.StuID = a.StuID and
b.SUID = a.SUID
WHERE
a.ClassCode <> '' AND
b.EnName IS NULL
ORDER BY a.ClassCode, a.ClassNo
1A
Peter
Mr. Wong
1A
John
(NULL)
1B
Mary
Mr. Chang
1B
Tim
Mr. Lee
1B
Joe
(NULL)
1C
Jack
Mr. Yan
1C
Henry
Mr. Lau
1C
Eric
Mr. Kwan
WHERE
Class
code
Class
No
Stud
Name
Parent Name
1A
John
(NULL)
1B
Joe
(NULL)
90
Transformed to
Sub-Query
STUID
Class
code
Class
No
Stud
Name
001
1A
Peter
002
1A
John
003
1B
Mary
004
1B
Tim
005
1B
Joe
SELECT
006
1C
1
Jack
a.STUID ,
a.ClassCode 'Class Code',
STUID Parent Name
a.ClassNo 'Class No',
a.EnName 'Student Name'
001
Mr. Wong
WHERE
FROM TB_STU_Student a
003
Mr. Chang
where
004
Mr. Lee
006
Mr. Yan
a.classcode <> '' and
a.stuid not in
(select stuid from tb_stu_parent) STUID Class
Class
Stud
STUID
NOT
IN
ORDER BY a.ClassCode,
code
No
Name
a.ClassNo
002
1A
2
John
005
1B
Joe
91
Evaluation Order
Evaluation Order
Type of Operator
NOT
AND
OR
92
93
94
96
Query Repository
Student
Assessment
Staff
97
Student information
Student information with parent
Student information with user-defined fields
Student information with last year's class
code
S5 & S7 graduated student list
98
Examination score
Examination score with component
Top 20 students of a subject
English subject component score
Score of Chinese subject with component
List of student that fail Chinese, English or
Mathematics
99
100
101
Sybase Central
103
Sybase Central
Play DEMO
Points to note :
Connect the database with valid account
104
End of Workshop
105