Escolar Documentos
Profissional Documentos
Cultura Documentos
1
4/7/19
PART
I
Review:
Single
Table
Queries
2
4/7/19
§ The SELECT statement is used to get data out of the database
§ The
data
returned
is
stored
in
a
result
table,
called
the
result-‐set,
which
is
temporary,
hence
not
stored
in
the
database,
but
what
user
want
to
see
3
4/7/19
4
4/7/19
5
4/7/19
WHERE
Clause
The
conditions
can
be
written
using:
§ Column
names
§ Logical
and
comparison
operators
§ Mathematical
expressions
§ Constants
§ Built-‐in
DBMS
functions
§ Sub-‐queries
6
4/7/19
7
4/7/19
§ The WHERE clause can be combined with AND, OR, and NOT operators
§ The
AND and
OR operators
are
used
to
filter
records
based
on
more
than
one
condition
§ The
AND operator
displays
a
record
if
all
the
conditions
separated
by
AND
is
TRUE
§ The
OR operator
displays
a
record
if
any
of
the
conditions
separated
by
OR
is
TRUE
§ The NOT operator displays a record if the condition(s) is NOT TRUE
Query2: Give
me
all
data
about
Students
whose
from
“Berlin”
or
“London”
SELECT *
FROM Student
WHERE City=‘Berlin’ OR City=‘London’;
Query3: Give
me
all
data
about
Students
whose
not
from
“Berlin”
SELECT *
FROM Student
WHERE NOT City=‘Berlin’;
8
4/7/19
Query2: Give
me
all
data
about
Students
whose
country
is
NOT
“Germany”
and
NOT
“USA”
SELECT *
FROM Student
WHERE NOT Country=‘Germany’ AND NOT Country=‘USA’;
9
4/7/19
SELECT *
FROM Student
WHERE StudentNo NOT BETWEEN 10 AND 20;
10
4/7/19
SELECT *
FROM Student
WHERE Name NOT IN (’Anne’, ‘Boris’);
SELECT *
FROM Student
WHERE Name IN (SELECT LecturerName FROM Lecturer);
11
4/7/19
Note: A NULL value
is
different
from a
zero
value
or
a
field
that
contains
spaces.
A
field
with
a
NULL value
is
one
that
has
been
left
blank
during
record
creation!
Query: List
all
Students
that
Query: List
all
Students
that
has
NO
address do
have
an
address
SELECT * SELECT *
FROM Students FROM Students
WHERE Address IS NULL; WHERE Address IS NOT NULL
12
4/7/19
Rule in SQL: include only tuples that yield TRUE (1.0)
13
4/7/19
14
4/7/19
Query: “Select
all
customers
from
the
”Customer"
table,
sorted
DESCENDING
by
the
“contactLastName”
and
ASCENDING
by
the
”contactFirstName"
column
SELECT *
FROM Customer
ORDER BY contactLastName DESC,
contactFirstName ASC;
Note:
In
the
query
above,
the ORDER
BY clause
sorts
the
result
set
by
the
last
name
in
descending
order
first
and
then
sorts
the
sorted
result
set
by
the
first
name
in
ascending
order
to
produce
the
final
result
set
15
4/7/19
TOP-‐N
Analysis
§ Used
to
specify
the
number
of
records
to
return
§ Useful
on
large
tables
with
thousands
of
records,
since
returning
a
large
number
of
records
can
impact
on
performance
§ Ex: Select
the
first
three
records
from
the
”Student"
table
16
4/7/19
PART
II
Multi-‐Table
Queries
RA:
𝑆𝑡𝑢𝑑𝑒𝑛𝑡
×
𝑃𝑟𝑜𝑓𝑒𝑠𝑠𝑜𝑟
17
4/7/19
SELECT *
Cross-‐Product
(×) -‐ Example FROM Student, Professor;
Student Professor
sid sname address professorid pid pname address
1 Dave 320FL 1 ×
1 MM 141FL
2 Greg 320FL 1
2 ER 201FL
3 Matt 320FL 2
𝑺𝒕𝒖𝒅𝒆𝒏𝒕𝒔
×
𝑷𝒓𝒐𝒇𝒆𝒔𝒔𝒐𝒓
List
of
tables
without
sid sname address professorid pid pname address
any
condition
in
the
WHERE
clause
produces
1 Dave 320FL 1 1 MM 141FL
…
Unexpected
result!! 1 Dave 320FL 1 2 ER 201FL
2 Greg 320FL 1 1 MM 141FL
Cartesian
Products
2 Greg 320FL 1 2 ER 201FL
usually
don’t
make
a
3 Matt 320FL 2 1 MM 141FL
lot
of
sense 3 Matt 320FL 2 2 ER 201FL
18
4/7/19
§ What
if
we
insert
a
tuple
into
student,
but
no
corresponding
professor?
§ INSERT
is
rejected
(foreign
keys
are
constraints)!
The
FOREIGN
KEY
constraint
is
used
to
prevent
actions
that
would
destroy
links
between
tables
§ What
if
we
delete
a
professor?
§ Disallow
the
delete The
FOREIGN
KEY
constraint
also
prevents
invalid
data
from
being
inserted
into the
foreign
key
column,
because
it
has
to
be
one
of
the
values
contained
in
the
table
it
points
to
19
4/7/19
§ The
JOIN
operation
links
across
several
tables as
part
of
a
SELECT
operation
§ You
must
tell
the
JOIN
how
to
use
the
keys
that
make
the
connection
between
the
tables
using
an
ON
clause
SELECT sname, pname Several
equivalent
ways
to
write
a
FROM Student, Professor basic
join
in
SQL
WHERE professorid = pid
Be
Careful…
§ Joining
two
tables
without
an
On
clause
(OR
without
any
condition
in
the
WHERE
clause)
gives
all
possible
combinations
of
rows
(3
x
2
=
total
6
tuples)
à Cartesian
Product
§ When
there
is
no
ON
clause,
we
are
getting
rows,
where
two
things
do
not
match
§ So,
the
On
clause
is
really
important
to
throw
away
non-‐matching
rows
§ With
ON
clause
you
would
see
only
the
matching
rows,
which
is
what
you
want
sid sname address professorid pid pname address
20
4/7/19
Product
PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Example: Joins
Product(PName, Price, Category, Manufacturer)
FK Company(CName, StockPrice, Country)
21
4/7/19
Example: Joins
Product
Company
PName Price Category Manuf
Cname Stock Country
Gizmo $19 Gadgets GWorks
GWorks 25 USA
Powergizmo $29 Gadgets GWorks
Canon 65 Japan
SingleTouch $149 Photography Canon
Hitachi 15 Japan
MultiTouch $203 Household Hitachi
Example: Joins
Product(PName, Price, Category, Manufacturer)
FK Company(CName, StockPrice, Country)
22
4/7/19
= Filtering!
An
example
of
A
SELECT R.A Output
SQL
semantics FROM R,
S 3
1 A B C
3 1 2 3
23
4/7/19
§ Not actually how the DBMS executes it under the covers
Which “name”s??
24
4/7/19
Aliases
§ SQL
aliases
are
used
to
give
a
table,
or
a
column
in
a
table,
a
temporary
name
§ Aliases
can
also
be
used
to
make
column
names
more
readable
§ An
alias
only
exists
for
the
duration
of
the
query
Result Table
StudentNo Name
Alias
for
Columns
1 John
SELECT StudentNo, Name 2 Anne Result Table
FROM Student; 3 Betty No Student
4 Boris 1 John
SELECT StudentNo AS No, Name AS Student 2 Anne
FROM Student; 3 Betty
4 Boris
25
4/7/19
Aliases
Note: It
requires
double
quotation
marks
or
square
brackets
if
the
alias
name
contains
spaces
SELECT StudentNo AS “Student No”, Name AS “Student Name”
FROM Student;
Ex: Create
an
alias
named
"Address"
that
combine
four
columns
(Address,
PostalCode,
City
and
Country)
from
customer
table
SELECT Address + ', ' + PostalCode + ’, ' + City + ', ' + Country AS Address
FROM Customer;
26
4/7/19
Inner
Joins
By default,
joins
in
SQL are
“inner
joins”
Product(name, category)
Purchase(prodName, store)
However: Products that never sold (with no Purchase tuple) will be lost!
27
4/7/19
Outer
Joins
§ An
outer
join returns
tuples
from
the
joined
relations
that
don’t
have
a
corresponding
tuple
in
the
other
relations
§ I.e.
If
we
join
relations
A
and
B
on
a.X =
b.X,
and
there
is
an
entry
in
A
with
X=5,
but
none
in
B
with
X=5…
§ A
LEFT
OUTER
JOIN
will
return
a
tuple
(a,
NULL)!
name store
SELECT Product.name, Purchase.store Gizmo Wiz
FROM Product Camera Ritz
LEFT OUTER JOIN Purchase
ON Product.name = Purchase.prodName Camera Wiz
OneClick NULL
28
4/7/19
name store
SELECT Product.name, Purchase.store Gizmo Wiz
FROM Product Camera Ritz
RIGHT OUTER JOIN Purchase
ON Product.name = Purchase.prodName Camera Wiz
NULL Kiz
29
4/7/19
30
4/7/19
PART
III
Set
Operators
&
Nested
Queries
31
4/7/19
Set
Operations
§ The
usual
set
operations
are
also
available
in
SQL
§ UNION
§ INTERSECT
§ EXCEPT
(set
difference)
SQL
UNION
§ The
UNION operator
is
used
to
combine
the
result-‐set
of
two
or
more
SELECT statements
§ Each
SELECT statement
within
UNION must
have
the
same
number
of
columns
§ The
columns must
also
have
similar
data
types
§ The
columns in
each
SELECT statement
must
also
be
in
the
same
order
SELECT column_name(s) A
∪ 𝐵
There
will
be
NO
duplicates!!
FROM table1 Only
distinct
values
UNION A B
SELECT column_name(s)
Why
aren’t
there
duplicates?
FROM table2
By
default:
SQL
retains set
semantics
for
UNIONs,
INTERSECTs!
32
4/7/19
Example: UNION
A
∪ 𝐵
SELECT column_name(s)
ALL
indicates
FROM table1
UNION ALL A B Multiset
SELECT column_name(s) operations
FROM table2
33
4/7/19
A B A B
What
is
the
multiset
versions?
Example: EXCEPT
34
4/7/19
Example: INTERSECT
35
4/7/19
36
4/7/19
37
4/7/19
PART
IV
Aggregation
-‐ GROUP
BY
-‐ HAVING
38
4/7/19
SQL
Functions
§ SQL
has
many
built-‐in
functions
for
performing
calculations
on
data
§ SQL
String
Functions
§ SQL
Date
Functions
§ SQL
Aggregate
Functions
Function Description
SQL
String
CHARINDEX
Searches
an
expression
in
a
string
expression
and
returns
its
starting
position
if
found
Functions CONCAT()
LEFT()
LEN() / LENGTH() Returns the length of the value in a text field
LTRIM()
SUBSTRING()
/
Extract
characters
from
a
text
field
MID()
PATINDEX()
REPLACE()
RIGHT()
RTRIM()
39
4/7/19
DATE() Extracts the date part of a date or date/time expression
40
4/7/19
Example: Aggregation
41
4/7/19
Aggregation: COUNT
SELECT COUNT(category)
FROM Product Note: Same
as
COUNT(*)
WHERE year > 1995
We
probably
want:
SELECT COUNT(DISTINCT category)
FROM Product
WHERE year > 1995
More
Examples
Purchase(product, date, price, quantity)
42
4/7/19
Simple
Aggregations
Purchase
Product Date Price Quantity
bagel 10/21/2005 1 20
banana 10/03/2005 0.5 10
banana 10/10/2005 1 10
bagel 10/25/2005 1.50 20
43
4/7/19
Purchase
Product Date Price Quantity
FROM bagel 10/21/2005 1 20
banana 10/03/2005 0.5 10
banana 10/10/2005 1 10
bagel 10/25/2005 1.50 20
44
4/7/19
45
4/7/19
HAVING
Clause
The HAVING clause was added to SQL because the WHERE keyword
could not be used with aggregate functions
SELECT product, SUM(price*quantity) Same
query
as
FROM Purchase before,
except
that
WHERE date > ‘10/1/2005’ we
consider
only
GROUP BY product
HAVING SUM(quantity) > 100
products
that
have
more
than
100
buyers
HAVING
clauses
contains
conditions
on
aggregates
§ S
=
Can
ONLY
contain
attributes
a1,…,ak and/or
aggregates
over
other
attributes
§ C1 =
is
any
condition
on
the
attributes
in
R1,…,Rn
§ C2 =
is
any
condition
on
the
aggregate
expressions
46
4/7/19
Evaluation
steps
1. Evaluate
FROM-‐WHERE:
apply
condition
C1 on
the
attributes
in
R1,…,Rn
2. GROUP
BY
the
attributes
a1,…,ak
3. Apply
condition
C2 to
each
group
(may
have
aggregates)
4. Compute
aggregates
in
S
and
return
the
result
47
4/7/19
§ Attempt
#1-‐ With
nested:
How
many
times
do
we
do
a
SFW
query
over
all
of
the
Wrote
relations?
§ Attempt #2-‐ With group-‐by: How about when written this way?
48
4/7/19
49
4/7/19
Summary
50