Ivy Ms-Access SQL Slides v6
Ivy Ms-Access SQL Slides v6
1
SQL Agenda
What is SQL?
• DDL Statements
• DML Statement
• DCL Statements
DML Statements
DDL Statements
2
SQL Overview
Creating CREATE
Structure
Modifying
DDL ALTER
Structure
Delete DROP
Structure
Populate INSERT
GRANT
DCL Access
REVOKE
3
1 Introduction to SQL
What is SQL?
– When a user wants to get some information
from a database file, he can issue a query.
– A query is a user–request to retrieve data or
information with a certain condition.
– SQL is a query language that allows user to
specify the conditions. (instead of algorithms)
4
1 Introduction to SQL
Concept of SQL
5
1 SQL Statement Types
• Data Definition Lang. (DDL) for defining
relations, views, integrity constraints
• Data Manipulation Lang. (DML) for
updating and querying
• Database Control Lang. (DCL) for
defining access rights, concurrency
control, etc.
6
DATA MANIPULATION LANG.
7
2 Basic structure of an SQL
query
General SELECT, ALL / DISTINCT, *,
Structure AS, FROM, WHERE
Union UNION
8
Important Points
• Ideal Steps to Write the SQL SELECT Stmt
1. Visualize the Final Report (answer)
2. Think of the Execution Sequence
3. Then, Write the SQL SELECT Statement
9
Important Points
• SQL is not Case-Sensitive, but spelling sensitive
• You can’t write more than ONE SQL Stmt in one
window (in Access)
• Any function –
– A function looks like -> funcName()
– It will always return something
– Some functions accept parameters or arguments. Eg.
Round(8.89, 1) -> 8.9
– Please note – a function will have always have a pair
of bracket as suffix
10
Important Point – Contd.
• How to handle cell values in SQL –
– Numbers – directly without quotes
– Text / Char – with a pair of single or double quotes
(ex – FullName = ‘Matt Haden’)
– Date – with a pair of # (ex: DOB = #01/12/2008#)
– Boolean (Yes/No)– Compare Boolean fields with
Yes/No or True/False or 1/0. Don’t use quotes.
(Wrong -> Remission = ‘No’)
– Please note – Don’t address a field (column name.
ex: FullName) with any quotes or #. (Wrong - #DOB#
= #01/12/2008#)
11
2 The Situation:
Student Particulars
field type width contents
id numeric 4 student id number
name character 10 name
dob date 8 date of birth
sex character 1 sex: M / F
class character 2 class
hcode character 1 house code: R, Y, B, G
dcode character 3 district code
remission logical 1 fee remission
mtest numeric 2 Math test score
12
Try these..
1. List the female students who have scored less
than 92 in Maths
2. List the students who were born before
01/01/2000 (hint: use # for date values)
3. List the students who have not paid their fees
4. List the students who come from district YMT
5. Find the age of students (hint: use date()
function)
6. Show the age in the following format: years in
one column and the month in another. (HW)
13
I General Structure
14
I General Structure
SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;
FROM tablename WHERE condition
– The query will select rows from the source tablename
and output the result in table form.
– Expressions expr1, expr2 can be :
• (1) a column, or
• (2) an expression of functions and fields.
15
I General Structure
SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;
FROM tablename WHERE condition
– DISTINCT will eliminate duplication in the output
while ALL will keep all duplicated rows.
– condition can be :
• (1) an inequality, or
• (2) a string comparison
• using logical operators AND, OR, NOT.
16
I General Structure
Class Class
1A 1A
1A
class="1A"
1A
1A 1A
1B 1B
1B 1B
: :
18
I General Structure
eg. 2 List the names and house code of 1A students.
19
I General Structure
eg. 3 List the residential district of the Red House
members.
SELECT DISTINCT dcode FROM student
WHERE hcode="R"
dcode
Result
HHM
KWC
MKK
SSP
TST
YMT
20
I
eg. 4
General Structure
List the names and ages (1 d.p.) of 1B girls.
1B Girls ?
21
I
eg. 4
General Structure
List the names and ages (1 d.p.) of 1B girls.
What is "age"?
23
I
eg. 4
General Structure
List the names and ages (1 d.p.) of 1B girls.
Functions:
# days : DATE( ) – dob
# years :(DATE( ) – dob) / 365
1 d.p.: ROUND(__ , 1)
24
I
eg. 4
General Structure
List the names and ages (1 d.p.) of 1B girls.
25
I General Structure
eg. 5 List the names, id of 1A students with no fee
remission.
SELECT name, id, class FROM student
WHERE class="1A" AND Remission=False
name id class
Result Peter 9801 1A
Mary 9802 1A
Luke 9810 1A
Bobby 9811 1A
Aaron 9812 1A
Ron 9813 1A
Gigi 9824 1A
: 26 : :
II Comparison
expr IN ( value1, value2, value3)
expr BETWEEN value1 AND value2
expr LIKE “*P“
expr NOT LIKE “*P“
27
Try these..
1. Find the students who have IDs in the
following set – 1,5,9
2. List the names of the students who are
playing a musical instrument (Hint: refer
to Music and Student tables both)
28
II Comparison
eg. 6 List the students who were born on Wednesday
or Saturdays.
SELECT name, class,WeekdayName(weekday(dob),1) AS
bdate FROM student
WHERE WeekDayname(WeekDay(dob)) IN (‘Wednesday’,
‘Saturday’)
name class bdate
Result Peter 1A Wednesday
Wendy 1B Wednesday
Kevin 1C Saturday
Luke 1A Wednesday
Aaron 1A Saturday
: : :
29
II Comparison
eg. 7 List the students who were not born in January,
March, June, September.
SELECT name, class, MonthName(Month(DOB))
FROM student
WHERE MONTH(dob) NOT IN (1,3,6,9)
name class dob
Result Wendy 1B July
Tobe 1B October
Eric 1C May
Patty 1C August
Kevin 1C November
Bobby 1A February
Aaron 1A August
: : :
30
II Comparison
31
II Comparison
eg. 9 List the students whose names start with "T".
32
II Comparison
33
Practice Like Queries
1. List the students whose names contain E
2. List the students who come from Districts ending
with T
3. List the students whose names contain B as the
second last letter
4. List the students who come from districts with M as
the third character
5. List the students who don’t contain ‘A’ and ‘R’ in
their names.
6. List the students who contain only “A” or “B” or “C”
or “D”
34
III Grouping
SELECT ...... FROM ...... WHERE condition ;
GROUP BY groupexpr [HAVING requirement]
Group functions:
COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )
36
Group By Class
class
1A
1A 1A
1A
COUNT( )
1B
1B
1B COUNT( )
1B 1B
1B
1B
1C
1C 1C
1C
COUNT( )
Student
37
III Grouping
eg. 11 List the number of students of each class.
SELECT class, COUNT(*) FROM student
GROUP BY class
class cnt
Result 1A 10
1B 9
1C 9
2A 8
2B 8
2C 6
38
III Grouping
eg. 12 List the average Math test score of each class.
39
Group By Class
class
1A
1A 1A AVG( )
1A
1B
1B
1B
1B AVG( )
1B
1B
1B
1C
1C 1C AVG( )
1C
Student
40
III Grouping
eg. 12 List the average Math test score of each class.
class avg_mtest
Result 1A 85.90
1B 70.33
1C 37.89
2A 89.38
2B 53.13
2C 32.67
41
III Grouping
eg. 13 List the number of girls of each district.
45
IV Display Order
eg. 16 List the boys of class 1A, sorted by their names.
46
IV Display Order
eg. 17 List the 1B students by their residential district.
SELECT name, id, class, dcode FROM student ;
WHERE class=“1B" ORDER BY dcode
Jimmy 9712 1B HHM
Result Tim 9713 1B HHM
Samual 9714 1B SHT
Rosa 9703 1B SSP
Helen 9702 1B TST
Joseph 9715 1B TSW
Paula 9701 1B YMT
Susan 9704 1B YMT
47
IV Display Order
eg. 18 List the number of students of each district
(in desc. order).
SELECT COUNT(*) AS Cnt, dcode FROM student
GROUP BY dcode ORDER BY COUNT(*) DESC
Result
cnt docode
11 YMT
10 HHM
10 SSP
9 MKK
5 TST
2 TSW
1 KWC
1 MMK
1 SHT
48
IV Display Order
eg. 19 List the boys of each house sorted by the
classes. (2-level ordering)
49
IV Display Order
Result
name hcode class
Blue
Bobby B 1A
House Teddy B 1B Order
Joseph B 2A by
Zion B 2B class
Order
Leslie B 2C
by Johnny G 1A
hcode Luke G 1A
Kevin G 1C
Green
House George G 1C
: : :
:
:
50
V Top
SELECT TOP 2 * FROM ... WHERE .....
SELECT TOP 10 Percent * FROM ...
51
V TOP
eg. 20 List the girls students who are in the top 10% in
class 1A
52
Home Work
H/W Find the second rank holder.
H/W How many students have unique names? (Not,
who have unique names)
53
VI Mid()
SELECT MID(col_name, start [,length])
FROM ...
54
V MID()
eg. 21 List the fist initial of all the students coming from
YMT
55
Some More Text Functions
• UCASE(textField1) : Will change the field1 to Upper case
• LCASE(textField1) : Will change the textField1 to Lower
Case
• LEN(textField1) : Will give you the length of a text field
• RIGHT(textField1, position) : Will return right characters
from the position
• LEFT(textField1, position) : Will return left characters from
the position
• REPLACE(textField,”string_to_replace”,”replacement_strin
g”,[Start_Position],[Occurances_To_Replace])
• INSTR([Start Position], TextField, “StringToFind”) – Finds
the position of a char in a string.
56
Text Exercises
A B
A B
A B
62
Try these..
1. Students who are playing either Chess or
Bridge or both
2. Students who are playing both – Chess
and Bridge
3. Students who are playing only Chess
4. Students who are playing either Chess or
Bridge, but not both
63
3 Union, Intersection and
Difference of Tables
Bridge [A] Chess [B]
id name sex class id name sex class
1 9812 Aaron M 1A 1 9802 Mary F 1A
2 9801 Peter M 1A 2 9801 Peter M 1A
3 9814 Kenny M 1B 3 9815 Eddy M 1B
4 9806 Kitty F 1B 4 9814 Kenny M 1B
5 9818 Edmond M 1C 5 9817 George M 1C
: : : : : : : :
64
3 Union, Intersection and
Difference of Tables
SELECT ...... FROM ...... WHERE ......
UNION
SELECT ...... FROM ...... WHERE ......
65
3 Union, Intersection and
Difference of Tables
SELECT ...... FROM table1 ;
WHERE col IN ( SELECT col FROM table2 )
66
3 Union, Intersection and
Difference of Tables
SELECT ...... FROM table1 ;
WHERE col NOT IN ( SELECT col FROM table2 )
67
H/W Exercise
• List the students who are playing only one
of the games
68
Multiple IN Statements Problem
• Select PubID, PubName From Publisher WHERE PubID
IN (SELECT PID From Books WHERE ISBN IN
(SELECT ISBN from Auth_Books WHERE AID IN
(Select AID From Authors WHERE AName =
‘Ramesh’)))
69
4 Multiple Tables:
• SQL provides a convenient operation to
retrieve information from multiple tables.
70
4 Multiple Tables:
field1 field2
A 1
field1 field2
A 2
A 1
A 3
B 2
B 1
3
B 2
B 3
71
4 The Situation:
Music Lesson
Each student should learn a musical instrument.
Two tables: student & music
The common field: student id
72
4 Natural Join
A Natural Join is a join operation that joins two
tables by their common column. This operation
is similar to the setting relation of two tables.
73
4
eg. 25
Natural Join
Make a list of students and the instruments they
learn. (Natural Join)
id name class id type
Same id 9801
9801
Join
Student Music
9801
74
Product
4
eg. 25
Natural Join
Make a list of students and the instruments they
learn. (Natural Join)
SELECT s.class, s.name, s.id, m.type ;
FROM student s, music m ;
WHERE s.id=m.id ORDER BY class, name
class name id type
Result 1A Aaron 9812 Piano
1A Bobby 9811 Flute
1A Gigi 9824 Recorder
1A Jill 9820 Piano
1A Johnny 9803 Violin
1A Luke 9810 Piano
1A Mary 9802 Flute
: : : :
75
4 Natural Join
eg. 26 Find the number of students learning piano in
each class.
Three Parts :
(1) Natural Join.
(2) Condition: m.type="Piano"
(3) GROUP BY class
76
4 Natural Join
eg. 26
Music
77
4 Natural Join
eg. 26 Find the number of students learning piano in
each class.
SELECT s.class, COUNT(*) ;
FROM student s, music m ;
WHERE s.id=m.id AND m.type="Piano" ;
GROUP BY class ORDER BY class
class cnt
Result 1A 4
1B 2
1C 1
78
H/W
• List the pair of students from the same
class (without any repetitions of the pairs).
(Hint: Inner Join the Student table with
itself)
79
4 Outer Join
An Outer Join is a join operation that includes
rows that have a match, plus rows that do not
have a match in the other table.
80
4 Outer Join
eg. 27 List the students who have not yet chosen an
instrument. (No match)
9801
No match
Student Music
81
4 Outer Join
eg. 27 List the students who have not yet chosen an
instrument. (No match)
SELECT class, name, id FROM student
WHERE id NOT IN ( SELECT id FROM music )
ORDER BY class, name
class name id
Result 1A Mandy 9821
1B Kenny 9814
1B Tobe 9805
1C Edmond 9818
1C George 9817
: : :
82
4 Outer Join
eg. 28 Make a checking list of students and the
instruments they learn. The list should also
contain the students without an instrument.
(Outer Join)
83
4 Outer Join
eg. 28
Natural Join
Outer Join
No Match
84
4 Outer Join
eg. 28 SELECT s.class, s.name, s.id, m.type
FROM student s, music m
WHERE s.id=m.id
UNION
SELECT class, name, id, ""
FROM student
WHERE id NOT IN ( SELECT id FROM music )
ORDER BY 1, 2;
85
4
class
Outer Join
name id type
class name id type
1A Aaron 9812 Piano
1A Bobby 9811 Flute 1A Aaron 9812 Piano
1A Gigi 9824 Recorder 1A Bobby 9811 Flute
1A Jill 9820 Piano 1A Gigi 9824 Recorder
1A Johnny 9803 Violin 1A Jill 9820 Piano
1A Luke 9810 Piano 1A Johnny 9803 Violin
1A Mary 9802 Flute 1A Luke 9810 Piano
: : : : 1A Mandy 9821
Natural Join 1A Mary 9802 Flute
1A Peter 9801 Piano
class name id
1A Mandy 9821
1A Ron 9813 Guitar empty
1B Eddy 9815 Piano
1B Kenny 9814
1B Tobe 9805 1B Janet 9822 Guitar
1C Edmond 9818 1B Kenny 9814
1C George 9817 1B Kitty 9806 Recorder
: : : : : : :
No Match 86 Outer Join
Try this.. (Full Join)
• List all the students and all the musical
instruments (Hint: Left Join Union Right
Join)
87
Union Exercise Answer:
• List the students who are playing only one
sport (either Chess or Bridge)
SELECT ID, FullName
FROM Chess
WHERE ID NOT IN (SELECT ID FROM Bridge)
UNION
SELECT ID, FullName
FROM Bridge
WHERE ID NOT IN (SELECT ID FROM CHESS)
88
INSERT, UPDATE, DELETE – DML
CREATE, ALTER, DROP - DDL
89
DDL Statements
• CREATE
• ALTER
• DROP
DML Statements
• INSERT
• UPDATE
• DELETE
90
Important Points
• Unlike DML stmts, you can’t hit-and-try
with DDL
• A DDL stmt, if successfully runs, doesn’t
give a warning
• A DDL stmt makes irreversible change to
the design of the database
91
CREATE (various ways)
• CREATE TABLE branch
(fname char(10),
city char(20),
director char(20),
assets integer,
Constraint CKFnameCity PRIMARY KEY (fname, city));
• CREATE TABLE AuthorsISBN
(AuthorsID INTEGER REFRENCES Authors(ID),
ISBN INTEGER REFRENCES Titles);
• CREATE TABLE Music
(ID INTEGER PRIMARY KEY,
Mtype CHAR(10),
StudID INTEGER,
CONSTRAINT FKSid FOREIGN KEY (StudID) REFRENCES Students(ID));
92
CREATE (One More Method)
• CREATE Table Student2
(ID Integer CONSTRAINT PkID PRIMARY
KEY,
StudRegn Integer CONSTRAINT
PKStudRegn PRIMARY KEY,
StudName Char(10) NOT NULL,
StudGPA Integer
)
93
CREATE (Yet Another Method)
• CREATE Table Student3
(ID Integer,
StudRegn Integer,
StudName Char(10) CONSTRAINT Snn
NOT NULL,
StudGPA Integer,
CONSTRAINT PKStudRegnID PRIMARY
KEY(ID, StudRegn)
) 94
SELECT INTO
• SELECT field1[, field2[, …]] INTO
newtable [IN externaldatabase] FROM
source
• Newtable – name of the new table that will be created
• Source – source table from where the columns and data will be
exported
95
Alter
• ALTER TABLE Student3 DROP Constraint
FKSid;
96
ALTER, DROP, INSERT,
UPDATE
• ALTER TABLE branch ADD zip INTEGER
• UPDATE branch
Set city=‘New York’, Director =‘Peter’
Where director=‘Amit’;
97
INSERT INTO
• INSERT INTO target [(field1[, field2[, …]])]
[IN externaldatabase] SELECT
[source.]field1[, field2[, …] FROM
tableexpression
98
DELETE
• DELETE *
FROM Student
WHERE DOB < #01/01/1980#
99