Professional Documents
Culture Documents
Unit 1
Definitions
SQL - Structured Query Language
SQL is probably one of the simplest
languages you will ever learn
learn. It is
also very simple to underestimate.
DONT!!! This is arguably the most
powerful language you will learn
learn.
SQL is a set oriented language. It
was designed and built to manage
groups of data
data.
ER Diagram - Entity Relationship
diagram
An ER Diagram, also known as a
database schema, gives you a
graphical depiction of the database
you are working
ki with.
ith
PUBS Database
sales
stor_id
ord_num
ord_date
qty
payterms
title_id
char(4)
varchar(20)
datetime
smallint
varchar(12)
varchar(6)
stor_id = stor_id
stores
stor_id
char(4)
stor_name
varchar(40)
stor_address varchar(40)
city
varchar(20)
state
char(2)
zip
char(5)
stor_id = stor_id
title_id = title_id
titleauthor
au_id
title_id
au_ord
royaltyper
varchar(11)
varchar(6)
tinyint
int
au_id = au_id
authors
au_id
varchar(11)
au_lname
varchar(40)
au_fname
varchar(20)
phone
char(12)
address
varchar(40)
city
varchar(20)
state
char(2)
zip
char(5)
contract
bit
titles
title_id = title_id
title_id
title
type
pub_id
price
advance
royalty
ytd_sales
notes
pubdate
varchar(6)
varchar(80)
char(12)
char(4)
money
money
int
int
varchar(200)
datetime
title_id = title_id
roysched
title_id
titl
id
varchar(6)
h (6)
lorange int
hirange int
int
royalty
discounts
publishers
pub_id = pub_id
pub_id
pub_name
city
state
country
char(4)
varchar(40)
varchar(20)
char(2)
varchar(30)
discounttype
stor_id
lowqty
highqty
discount
varchar(40)
char(4)
smallint
smallint
decimal
pub_id = pub_id
employee
emp_id
fname
minit
lname
job_id
jjob_lvl
pub_id
hire_date
char(9)
varchar(20)
char
varchar(30)
smallint
tinyint
y
char(4)
datetime
pub_id = pub_id
pub_info
pub_id char(4)
logo
image
pr_info text
authors_tmp
job_id = job_id
jobs
job_id
job_desc
min_lvl
max_lvl
smallint
varchar(50)
tinyint
y
tinyint
au_lname
au_fname
phone
address
city
state
zip
varchar(40)
varchar(20)
char(12)
varchar(40)
varchar(20)
char(2)
char(5)
Unit 1
Goals
What is a database
What is a table
Rows and columns
Connecting to your database
Change databases
Overview of PUBS database
Simple select
Select all columns from a table
Select specific
p
columns from a table
Concatenate two columns
Create a query to give formatted
output
Databases
At the most basic level a database is
really just a file.
Databases come in all shapes and
sizes. Some are large and some are
small.
ll But
B t each
h database
d t b
generally
ll
serves a particular purpose.
Examples: Tracking employee
payroll, sales data on a particular
sales line, stock data for a particular
industry
All databases are made up
p of
objects. The most important object
(and the one we will learn how to use
in this class) is a table.
Tables
A table is a storage structure made up
of rows and columns. (Sort of like a
spreadsheet )
spreadsheet.)
Due to the differing terminologies,
th
there
are interchangeable
i t h
bl sets
t off
terms:
Database
Table
Row
Column
Mathematical
Relation
Tuple
Attribute
Data Processing
File
Record
Field
Tables cont.
You will also hear a table referred to
as an entity. (Hence the name Entity
Relationship Diagram)
In the most basic sense, an entity is
a person, place,
l
thi
thing, or id
idea.
Entities usually become tables
Example: books, publishers, titles,
authors
Connect to a database
In this class we will use a tool called
ISQL/W. This stands for Interactive
SQL / Windows
Windows. This is where we
will execute all of our queries from.
A query as the term implies is a
question we ask the database
database.
In other environments you will see
this query tool called by different
names. It is generally referred to as
just isql.
Regardless of name, they all perform
the same purpose. This is to give
you an interface
i t f
for
f sending
di SQL
statements and receiving results.
Rules cont.
Spacing does not matter (for the
most part).
select title_id
is the same as
select
title_id
However
However, you must still separate
words. You can not use the
following:
selecttitle id
selecttitle_id
This will give a
syntax error, because SQL Server
must be able to find your SQL
keywords.
keywords
Rules cont.
Carriage returns are ignored
select title_id from titles
is the same as
select title_id
from titles
The spacing and carriage returns just
make reading your SQL a lot easier.
The general format used by most
people is to place the separate
clauses of the statement on different
lilines
PUBS Database
Select
SELECT Statement Retrieves rows from the database.
SELECT [ALL | DISTINCT] <select_list> INTO [<new_table_name>]
[FROM <table_name> [, <table_name2> [..., <table_name16>]]
[WHERE <clause>] [GROUP BY <clause>] [HAVING <clause>] [ORDER
BY <clause>]
[COMPUTE <clause>] [FOR BROWSE]
where <table_name> | <view_name> =
[[<database>.]<owner>.]{<table_name>. | <view_name>.}
<joined_table> =
{{<table_name> CROSS JOIN <table_name> | <table_name> {{INNER | LEFT
[OUTER] | RIGHT [OUTER] |
FULL [OUTER]} JOIN <table_name> ON <search_conditions>}
<optimizer_hints>
One or more of the following, separated with a space:
[INDEX = {<index_name> | <index_id>}]
[NOLOCK] [HOLDLOCK] [UPDLOCK] [TABLOCK] [PAGLOCK]
[TABLOCKX] [FASTFIRSTROW]
WHERE <clause> =
WHERE <search_conditions>
GROUP BY <clause> =
GROUP BY [ALL] <aggregate
aggregate_free_expression
free expression> [[,
<aggregate_free_expression>]...]
[WITH {CUBE | ROLLUP}]
HAVING <clause> =
HAVING <search_conditions>
ORDER BY <clause> =
ORDER BY {{<table_name>. | <view_name>.}<column_name> |
<select_list_number> | <expression>} [ASC | DESC]
[...{{<table_name16>. | <view_name16>.}<column_name> |
<select_list_number> | <expression>} [ASC | DESC]]
COMPUTE <clause> =
COMPUTE <row
<row_aggregate>(<column_name>)
aggregate>(<column name>) [[,
<row_aggregate>(<column_name>)...]
[BY <column_name> [, <column_name>]...]
Select
A select statement is used to retrieve
data from a database. As you can
see from the syntax above
above, a select
statement can get very complicated.
D
Depending
di on th
the ttype off SQL
statement you are using most of this
is optional.
Select
Select
An asterisk (*) is used to designate
all columns in a table.
select *
Select
select * from authors
au_id
au_lname
phone ...
----------- --------------------------172-32-1176 White
496-7223...
213-46-8915 Green
986-7020...
238 95 7766 C
238-95-7766
Carson
548-7723...
267-41-2394 O'Leary
286-2428...
274-80-9391 Straight
834-2919...
341-22-1782 Smith
843-0462...
409-56-7008 Bennet
658-9932...
427-17-2319 Dull
836-7128...
472-27-2349 Gringlesby
938-6445...
486-29-1786 Locksley
585-4620...
527-72-3246 Greene
297-2723...
297-2723
648-92-1872 Blotchet-Halls
745-6402...
672-71-3249 Yokomoto
935-4228...
712-45-1867 del Castillo
996-8275...
722-51-5454 DeFrance
547-9982...
724-08-9931 Stringer
843-2991...
724-80-9391 MacFeather
au_fname
-------------------- ---Johnson
408
Marjorie
415
Ch
Cheryl
l
415
Michael
408
Dean
415
Meander
913
Abraham
415
Ann
415
Burt
707
Charlene
415
Morningstar
615
Reginald
503
Akiko
415
Innes
615
Michel
219
Dirk
415
Stearns
415
Select
We can limit the columns returned by
specifying them instead of using *.
select au_lname,
au lname au
au_fname
fname from
authors
au_lname
----------------------------------------------White
Green
Carson
O'Leary
Straight
Smith
Bennet
Dull
Gringlesby
Locksley
G
Greene
Blotchet-Halls
Yokomoto
del Castillo
DeFrance
Stringer
MacFeather
Karsen
Panteley
Hunter
McBadden
Ringer
Ringer
(23 row(s) affected)
au_fname
-----------Johnson
Marjorie
Cheryl
Michael
Dean
Meander
Abraham
Ann
Burt
Charlene
M
Morningstar
i
t
Reginald
Akiko
Innes
Michel
Dirk
Stearns
Livia
Sylvia
Sheryl
Heather
Anne
Albert
Select
When you specify columns, you do not
have to specify them in the order they
appear in the table
table.
You could have also executed the
f ll i
following:
select au_fname, au_lname from
authors
au fname
----------------------------Johnson
Marjorie
Cheryl
Michael
Dean
Meander
Abraham
Ann
Burt
...
(23 row(s) affected)
au lname
-----------------------------White
Green
Carson
O'Leary
Straight
Smith
Bennet
Dull
Gringlesby
Concatenation
We can also combine data together.
This is called concatenation.
We really want to display the first
name and the last name separated
by a space and then the rest of the
data The plus symbol (+) is the
data.
most widely used symbol for
concatenation. (A double pipe || is
sometimes used
used, but very rarely
rarely.))
select au_fname+au_lname from authors
JohnsonWhite
MarjorieGreen
CherylCarson
y
MichaelO'Leary
DeanStraight
MeanderSmith
AbrahamBennet
AnnDull
BurtGringlesby
CharleneLocksley
MorningstarGreene
ReginaldBlotchet-Halls
AkikoYokomoto
Innesdel Castillo
...
(23 row(s) affected)
Concatenation cont.
Concatenation is used for string
(character) data. If a concatenation
operator (+) is used on numeric data
data,
the data is simply added together.
select
l t title_id,price,advance
titl id i
d
ffrom titl
titles
title id price
-------- -----------------------------BU1032
19.99
BU1111
11.95
BU2075
2.99
BU7832
19.99
MC2222
19.99
...
(18 row(s)
( ) affected)
ff
d)
advance
--------------------5,000.00
5,000.00
10,125.00
5,000.00
0.00
Select
Aliases
Aliases
We can apply aliases in two places
within our SQL statements
Select clause
From clause
B
By specifying
if i an alias
li iin th
the select
l t
clause we can rename the column
headers for the output
By specifying an alias in the from
clause, we can save some typing
and also perform some higher level
queries which will require this. (This
will be demonstrated in subsequent
units.)
it )
Unit 1 Review
A database is a collection of objects, the
most prominent of which is a table.
A table consists of rows/tuples/records
and columns/attributes/fields.
use <dbname> allows you to select a
d t b
database
SQL keywords are not case sensitive.
Spacing and carriage returns are not
needed.
You can include a constant in your result
set byy hadding
g it jjust as yyou would a
column
An * allows you to select all columns in a
table
A + is used for concatenating two
strings.
Unit 1 Exercises
Time allotted for exercises is 30
minutes
Introduction To SQL
UnitIntroduction
2
To TSQL
Unit 2
Modern Business
Technology
Unit 2
Goals
Limit result set with where
Use compound criteria
Grouping conditions
Comparison
p
operators
p
Ranges
Wildcards
Escape characters
Pattern Matching
Negation
Where
So far we have returned the entire
contents of a table.
This is usually not very practical
Suppose we wanted to see the
authors that live in California.
We could do a select * from authors
and scroll through the result set
looking for those where state = CA
While feasible for a small table, this
is not practical.
practical
Where
So to limit the result set to just the
data you need, we will use the third
major SQL clause: where
The where clause tells the database
which
hi h rows tto retrieve.
ti
To just retrieve those authors that
live in CA, we would use the
following:
select au_lname, aufname, state
from authors where state = 'CA'
au_lname
---------------------------------------White
Green
Carson
O'Leary
...
(15 row(s) affected)
au_fname
state
-------------------- ----Johnson
CA
Marjorie
CA
Cheryl
CA
Michael
CA
Compound Criteria
This limited our result set to just
those authors in CA
But our list of authors could begin to
get very large and were only looking
f those
for
th
authors
th
with
ith a last
l t name off
Green.
We would do this with the following:
select au
au_lname,
lname, au
au_fname,
fname, state
from authors where state = 'CA' and
lname = 'Green'
au_lname
au_fname
state
---------------------------------------- -------------------- ----Green
Marjorie
CA
(1 row(s) affected)
Compound Criteria
Compound Criteria
Compound Criteria
So, what is the difference between
using an AND and an OR?
The AND is exclusive
This means that the row must meet all of the
conditions in order to be selected
The OR is inclusive
This means that for a row to be selected
selected, it
has to meet just one of the criteria
Compound Criteria
Now we are going to get a little more
complicated.
We want to select all authors who
live in KS with a last name of Smith
and
d also
l every author
th ffrom CA
CA.
We know how to do the first part
select au_lname, au_fname, state
from authors where state = 'KS'
KS and
au_lname = 'Smith'
Compound Criteria
au_fname
state
-------------------- ----George
CA
Johnson
CA
Marjorie
CA
Cheryl
CA
Michael
CA
Dean
CA
Meander
KS
Ab
Abraham
h
CA
Grouping Criteria
While this SQL statement returns the
data we want, it isnt very clear and is
sloppy
When using compound criteria in a
where
h
clause,
l
you should
h ld always
l
group the criteria to make it plain
exactly what you want.
You group by using parenthesis
The proper SQL statement is as
follows:
select * from authors where (state =
'KS' and lname = 'Smith') or state =
'CA'
CA
Comparisons
Besides using an =, you can also use
any of the other comparison
operators: >,
> <,
< <=,
<= >=.
>=
Suppose we want to return all of the
b k with
books
ith a price
i greater
t th
than
$10.00
select title_id, price from titles where price > 10
Comparisons
Range Output
IN
Instead of using multiple ORs, we
can use an IN operator
select au_lname, state from authors where
state in ('CA','KS','MI','UT')
Smith
White
...
Straight
Smith
Bennet
...
Yokomoto
del Castillo
Stringer
...
McBadden
Ringer
Ringer
(20 row(s) affected)
CA
CA
CA
KS
CA
CA
MI
CA
CA
UT
UT
Range Output
But,
But there is a much simpler way
SQL has given us a between
operator
select title_id, price from titles where price
between 10 and 20
Wildcards
Sometimes we do not know exactly
what we are looking for
Or we are looking for the group of
data that match a certain pattern
In these cases we would use
wildcards within our where clause
SQL has two wildcard characters
The percent (%) symbol designates any
string of zero or more characters
The underscore (_) designates a single
character
Wildcards
Wildcards
Maybe we want to select all of the
authors whose first name is Carl.
We have to be careful here, because
it could be spelled Carl or Karl
select au_fname, au_lname from authors where
au_fname like '_arl'
au fname
-------------------Carl
Karl
(2 row(s) affected)
au lname
---------------------------------------Burns
Johnson
Wildcards
You can combine wildcards to
retrieve exactly what you need
Suppose we needed to retrieve all of
the Smiths in the database
The last name could be spelled
Smith, Smithe, or Smythe. We want
to retrieve all of the spellings
select au_fname,
_
au_lname
_
from authors where
au_lname like 'Sm_th%'
au_fname
-------------------Meander
Jim
P tti
Patti
(3 row(s) affected)
au_lname
---------------------------------------Smith
Smithe
Smythe
S th
Escape characters
Pattern Matching
Pattern Matching
Suppose we wanted to retrieve all of
the authors whose last names
started with either an L
L, M
M, or S
select au_lname, au_fname from authors where
au lname like '[LMS]%'
au_lname
[LMS]%
au_lname
---------------------------------------Locksley
MacFeather
McBadden
Smith
Smith
Smithe
Smythe
Straight
Stringer
(9 row(s) affected)
au_fname
-------------------Charlene
Stearns
Heather
George
Meander
Jim
Patti
Dean
Dirk
Pattern Matching
Pattern Matching
We want to retrieve all books with a
title of Life Without Fear, but don't
know how the word without was
stored (uppercase, lowercase, or
mixed case)
select title_id, titles from titles where title
like '%[Ww][Ii][Tt][Hh][Oo][Uu][Tt]%'
title id title
-------- -------------------------------------------------------PS2106
Life Without Fear
(1 row(s) affected)
Pattern Matching
We now want to retrieve just those
authors whose first name is four
characters long
select au_lname, au_fname from authors where
au fname like '____' (That
au_fname
(That'ss four
underscore characters)
au_lname
au_fname
---------------------------------------- -------------------Burns
Carl
Gringlesby
g
y
Burt
Johnson
Karl
Ringer
Ann
Straight
Dean
Stringer
Dirk
(6 row(s) affected)
Pattern Matching
Pattern Matching
To get around this we exclude the
space
select * from authors where au_fname
like '[^ ] [^ ] [^ ] [^ ]'
au_id
------------111-11-1112
111-11-1113
274-80-9391
472-27-2349
724 08 9931
724-08-9931
au_lname
au_fname
---------------------------------------- ----------------Burns
Johnson
Straight
Gringlesby
S
Stringer
i
Carl
Karl
Dean
Burt
Di
Dirk
k
(5 row(s) affected)
Pattern Matching
Granted, in most real world situations
you will not go to these lengths when
retrieving data
data.
But constructs like this are used
extensively
t
i l tto ensure only
l valid
lid d
data
t
is entered into tables
Rules and constraints are beyond the
scope of this unit, but the examples
below are for demonstrative
purposes to give an idea of further
applications to pattern matching
Pattern Matching
Suppose you have a column that will
accept 6 characters
You have to be careful, because
numbers and special characters like
# @ & will
#,@,&
ill also
l go iin thi
this column
l
To restrict this to just characters, use
the following
[A-z]
[A
z] [A
[A-z]
z] [A
[A-z]
z] [A
[A-z]
z] [A
[A-z]
z] [A
[A-z]
z]
Negation
Negation
Negation
state
----MA
MA
MA
MA
KS
MI
MD
UT
UT
Review
Unit 2 Exercises
Time allotted is 30 minutes
Introduction To SQL
UnitIntroduction
3
To TSQL
Unit 3
Modern Business
Technology
Unit 3
Goals
Nulls
Group by
Order by
Distinct
Aggregates
Aggregates with grouping
Having
Compute
Unions
Null
Null
Null
For example take the authors table
If we were to leave out the state data
for an author, this could bring up a
few questions
Is the author from CA?
Is the author not from CA?
Is
I the
th author
th from
f
some other
th state?
t t ?
Any or none of these questions could
be true
Null
Nulls cont.
Nulls Applied
Nulls Applied
Order by
or
select au_fname,au_lname from authors order
by 2,1
Order by
Sort Order
Order by
Order by / Nulls
Distinct
Distinct
Sometimes we do not want to see
these duplicate rows
We can eliminate them by use of the
distinct keyword
The distinct is placed immediately
after the select
There can also be only one distinct
per SQL statement
The distinct applies to all columns in
the select list
Distinct
select au_id from titleauthor
au_id
----------172-32-1176
213-46-8915
213-46-8915
238-95-7766
267-41-2394
267-41-2394
...
899-46-2035
899-46-2035
998-72-3567
998-72-3567
(25 row(s) affected)
select distinct au_id from titleauthor
au_id
----------172 32 1176
172-32-1176
213-46-8915
238-95-7766
267-41-2394
...
899 46 2035
899-46-2035
998-72-3567
(19 row(s) affected)
Aggregates
Count(*)
Count will return exactly what it's
name implies
It returns a count of the number of
rows in a table that match a certain
criteria
it i
select count(*) from authors will return the
number
b off rows iin th
the authors
th
ttable
bl
----------27
(1 row(s) affected)
Sum
The sum is used to add up all of the
values in a column
select sum(advance) from titles will return the
total amount advanced to all authors
--------------------------
95,400.00
(1 row(s) affected)
Avg
Group by
Data in a table is essentially stored
randomly
We can impose one type of order on
the result set with an order by
We can impose another type of order
on a result set by using a group by
clause
Group by
Group by
select type from titles group by type
type
-----------(null)
UNDECIDED
popular_comp
business
mod_cook
trad_cook
psychology
(7 row(s) affected)
select type from titles group by type order by 1
type
yp
-----------(null)
UNDECIDED
business
mod_cook
popular_comp
psychology
trad_cook
(7 row(s) affected)
Group by
The true power of a group by comes
from using it in conjunction with an
aggregate
Suppose we wanted a count of each
t
type
off book
b k
At first thought you might be tempted
to do this:
select type,count(*)
yp
( ) from titles
Msg 8118, Level 16, State 1
Column 'titles.type' is invalid in the select list because it is not
contained in an aggregate function and there is no GROUP BY
clause.
Group by
----------2
1
2
2
3
5
3
(7 row(s)
( ) affected)
ff
d)
Group by
state
----MA
MI
CA
OR
CA
IN
----------4
1
2
1
1
1
Group by
You can not specify an aggregate in
the group by clause
select count(*) from authors group by count(*)
will return a syntax error
Msg 144, Level 15, State 1
Cannot use an aggregate or a subquery in an expression used for the
by-list of a GROUP BY clause.
Having
The having clause works just like a
where clause
There is a fundamental difference
The where clause defines the set of
data the grouping is done on
The having defines which groups are
going to be returned to the user
Having
-------------------------24,400.00
41,000.00
30,000.00
(3 row(s) affected)
Having/Where
select type
type,count(advance)
count(advance) from titles where
advance > 10000 group by type,advance
Having/Where
In both queries we want to know the
types of those books with an
advance > 10000
10000, so why the
different results
Thi
This iis d
due tto th
the way th
the where
h
and
d
having are applied
What happens is the data is selected
based on the result set
It is then p
passed to the g
group
p by
y for
grouping
Finally it goes to the having which
returns the data requested.
q
Having/Where
Having/Where
Where/Having
The concepts of where and having
clauses can get confusing very
quickly
The best way to get comfortable with
th
them
iis tto perform
f
a few
f
and
d observe
b
the results
Then draw out each of the steps on
paper until you can duplicate the
result set
The book "The Practical SQL
Handbook" has a g
good explanation
p
on pages 180 - 185
Compute
type
-----------mod_cook
mod_cook
trad_cook
trad_cook
trad_cook
price
-------------------------19.99
2.99
20.95
11.95
14.99
avg
==========================
14.17
(6 row(s) affected)
Compute by
A compute by is used to
subsummaries
This construct must be used with an
order by
select title_id, type, price from titles where type
lik '%cook%'
like
'%
k%' order
d b
by ttype compute
t
avg(price) by type
title_id
-------MC2222
MC3021
type
-----------mod cook
mod_cook
price
-------------------------19.99
2.99
avg
==========================
11.49
title_id
-------TC3218
TC4203
TC7777
type
-----------trad_cook
trad_cook
trad cook
price
-------------------------20.95
11.95
14.99
avg
==========================
15.96
(7 row(s) affected)
Compute/Compute by
These can be used in the same
query
select title
title_id,type,price
id type price from titles where type in
('business','mod_cook') order by type
compute sum(price) by type compute
sum(price)
title id
-------BU2075
BU7832
type
-----------business
business
price
-------------------------2.99
19.99
sum
==========================
22.98
title_id
-------MC2222
MC3021
type
-----------mod_cook
mod_cook
price
-------------------------19.99
2.99
sum
==========================
22.98
sum
==========================
45.96
(7 row(s) affected)
Compute/Compute by
Restrictions
With a compute/computed
p
p
by,
y yyou
can only use columns in the select
list
select title_id,type from titlescompute
sum(price) would return a syntax error
Compute/Compute by
Restrictions
Columns listed after the compute by
must be in the identical order to or a
subset of those listed after the order
by
Expressions must be in the same left
- right order
Compute by must start with the same
expressions
p
as listed after order by
y
and not skip any expressions
Compute/Compute by
Legal
order by a,b,c
compute by a,b,c
compute by a,b
compute
p
avg(price)
g(p
) by
ya
Illegal
order by a
a,b,c
bc
compute by b,a,c
compute by c,a
compute avg(price) by b
Unions
Unions
select * from authors where state = 'CA' union select * from authors where state
= 'MA'
au lname
state
---------------------------------------- ----Bennet
CA
Carson
CA
Dull
CA
Green
CA
Gringlesby
CA
Hunter
CA
Karsen
CA
Locksley
CA
MacFeather
CA
McBadden
CA
O'Leary
CA
Straight
CA
Stringer
CA
White
CA
Yokomoto
CA
Burns
MA
Johnson
MA
Smithe
MA
Smythe
MA
(19 row(s) affected)
Unions
Unit 3 Review
Unit 3 Exercises
Introduction To SQL
Introduction
Unit
4
To TSQL
Unit 4
Modern Business
Technology
Unit 4
Goals
Primaryy keys
y
Foreign keys
Joining tables
S b selects
Sub-selects
Advantages/disadvantages of joins
and sub-selects
Relationships
Relationships
Relationships
One to many
One row in a table is related to one or
more rows in another table
Many to many
Many rows in a table are related to one
or more rows in another table
Relationships
A many to many relationship is
extremely poor database design
This type of relationship can cause a
large amount of confusion
The problem is that many to many
relationships do exist and must be
stored in a database
This is usually resolved into multiple
one to many relationships also
known as an intersection table
Relationships
Relationships
Primary Key
Primary Key
pub_id is the primary key for the
publishers table
This will uniquely identify each
publisher in the table
We do not use the publisher's name,
because this could be the same as
another publisher
Also, it is easy to control data input to
ensure it is valid
It is much easier to check 4 digits
than 40 characters. Also a name can
be null.
Foreign Key
Composite Keys
Indexes
Joins
Joins
You will notice that there is no such
thing as a join clause in our SQL
syntax
A join is simply a where clause
A join is generally constructed
between one primary key and
another primary key or between a
primary key and a foreign key
(Discussion of PK/FK symbols on
the ER Diagram)
Joins
Suppose we want to view a list of
sales for each store
We could simply do the following:
select * from sales
stor_id ord_num
------- -----------6380
6871
6380
722a
7066
A2976
7066
QA7442.3
7067
D4482
7067
P2121
7067
P2121
7067
P2121
7131
N914008
7131
N914014
7131
P3087a
...
(22 row(s) affected)
ord_date
qty
payterms...
---------------------- ------ -------Sep 14 1994 12:00AM
5
Net 60...
Sep 13 1994 12:00AM
3
Net 60...
May 24 1993 12:00AM
50
Net 30...
Sep
p 13 1994 12:00AM
75
ON invoice
Sep 14 1994 12:00AM
10
Net 60...
Jun 15 1992 12:00AM
40
Net 30...
Jun 15 1992 12:00AM
20
Net 30...
Jun 15 1992 12:00AM
20
Net 30...
Sep 14 1994 12:00AM
20
Net 30...
Sep 14 1994 12:00AM
25
Net 30...
May 29 1993 12:00AM
20
Net 60...
Joins
ord_num
-------------------6871
722a
A2976
QA7442.3
D4482
P2121
P2121
P2121
2121
N914008
N914014
P3087a
P3087a
P3087a
P3087a
QQ2299
TQ456
X999
423LL922
qty
-----5
3
50
75
10
40
20
20
20
25
20
25
15
25
15
10
35
15
Joins
What does this mean?
The select clause simply designates
which columns we want to see. If we
were retrieving a column that had the
same name in
i th
the ttwo tables,
t bl
we
would have to specify which table the
data was coming from
select stores.stor_id,stor_name, ord_num, qty
from stores,sales
where
h
stores.stor_id
t
t id = sales.stor_id
l
t id
Joins
From clause
We are retrieving data from more
than one table, so each table must
be specified in the from clause
The from clause can be seen as the
main driver of a SQL statement
If the table isnt in the from clause,
none of itit'ss columns can be used in
any other clause
Joins
The where clause
where
h
stores.stor_id
t
t id = sales.stor_id
l
t id
Joins
A join can be seen as a special type
of selection criteria.
If there is a stor_id in the stores table
that does not exist in the sales table,
th data
the
d t for
f that
th t particular
ti l store
t
will
ill
not be returned
You can also add additional selection
criteria
select stores.stor_id,stor_name,city,
state,ord_num,qty
from stores,sales
where stores.stor_id = sales.stor_id and state =
'CA'
Joins
Joins
Outer Joins
ord_num
d
-------------------6871
722a
A2976
QA7442.3
D4482
P2121
P2121
P2121
N914008
N914014
P3087a
P3087a
P3087a
P3087a
QQ2299
TQ456
X999
423LL922
423LL930
756756
P723
QA879.1
qty
t
---5
3
50
75
10
40
20
20
20
25
20
25
15
25
15
10
35
15
10
5
25
30
Outer Joins
Notice the use of the asterisk (*)
where
h
stores.stor_id
t
t id **= sales.stor_id
l
t id
Outer Joins
Outer joins come in three different
flavors
Left
Right
Full
Subqueries
Subqueries
Subqueries
correlated:
select pub_name from publishers p
where 'business'
business in (select type from titles
where oub_id = p.pub_id)
Subqueries
Noncorrelated Subqueries
It th
then passes itits results
lt back
b k to
t the
th outer
t
query which then finds the rows that match
the list passed back
Correlated Subqueries
Correlated Subqueries
Joins or Subqueries
AND
select pub_name from publishers where city in
(select city from authors)
Joins or Subqueries
Joins or Subqueries
Common Restrictions
=1
1
Exists
Additional Restrictions
Nesting Subqueries
Unit 4 Review
Unit 4 Review
Unit 4 Exercises
Time allotted for exercises is 1 hour
Introduction
To SQL
Introduction
Unit 9
To TSQL
Unit 5
Modern Business
Technology
Data Manipulation
Up until this point we have covered
numerous ways to get data out of
tables
But, this is only a quarter of the basic
SQL picture
i t
We must have also have a way to
add new data to a table, modify
existing data, and delete data
To accomplish this, we will use the
insert, update, and delete statements
These statements are also referred
to as DML, data manipulation
language
Insert
Partial syntax:
insert [into] table_name [(column_list)] {values
(expression [[,expression]}|
expression] }| {select
statement}
Insert
insert into authors
values('409-56-7008', 'Bennet', 'Abraham',
'415
415 658-9932'
658 9932 , '6223
6223 Bateman St
St.', 'Berkeley'
Berkeley ,
'CA', '94705')
Insert
Because the previous statement
does not have a column_list, the data
is inserted into the table in the order
of the columns
F
For example
l the
th result
lt off this
thi
statement would be a new row in the
table that had the following:
au_id
id = 409
409-56-7008
56 7008
au_lname = Bennet
au_fname = Abraham
phone = 415 658
658-9932
9932
address = 6223 Bateman St.
city = Berkeley
state = CA
zip = 94705
Insert
If you did not have a value for the
address, the insert statement would
be as follows:
insert into authors
values ('409-56-7008', 'Bennet', 'Abraham',
'415
415 658-9932'
658 9932 ,null,
null 'Berkeley'
Berkeley , 'CA'
CA , '94705')
94705 )
Insert
Thi
This will
ill produce
d
the
th sett result
lt as th
the
previous insert statement
Insert
You also must use a column list if
you do not specify all of the values
In the authors table, au_id,
au_lname, and au_fname are the
only columns that require a value
(not null)
We
W could
ld also
l write:
it
insert into authors (au_id,au_lname, au_fname)
values ('409-56-7008', 'Bennet', 'Abraham')
Insert
Finally, the values clause can be
replaced by a select statement
The way this works is that the first
column of the result set from the
select
l t statement
t t
t is
i placed
l
d iin th
the fifirstt
column of the column list in the insert
The second to the second, etc.
insert into authors ((au_id,au_lname,
_
_
au_fname)
_
)
select ID,LastName,FirstName from
authors_tmp
Insert
You can also do this same type of
insert without specifying a column list
The result set from the select
statement must match the table you
are inserting
i
ti iinto
t iin th
the number
b off
columns, and datatype of columns
The column names do not have to
match
insert into authors select * from authors_tmp
Insert
The select statement that you use for
inserting data can be of any variety
You can use a subquery(s), group
by, order by, where, having, multiple
t bl
tables,
etc.
t
You can not use a compute or
compute by
Update
update table_name set column_name1 =
{expression1/null | (select statement)}
[,column_name2 = {{expression2/null
[,
p
| (select
(
statement)}]
from table_name [where search_conditions]
Update
You use the where clause to restrict
which rows are updated
If you only wanted to discount those
books published before 1/1/87:
update titles set price = price * .9
where pubdate < '1/1/87'
Update
You can also change multiple
columns at the same time
update authors set city = 'Oakland West', zip =
'94611' where city = 'Oakland' and address
like
e '%College%'
%Co ege%
Update
When you need to restrict the update
to a set of rows that are based upon
more than one table
table, you must use
the from clause
W
We wantt to
t discount
di
t only
l those
th
books that are from publishers in CA
update titles set price = price * .9 from titles t,
publishers p where t.pub_id = p.pub_id and
p.state = 'CA'
Delete
Delete
To restrict the rows you delete use a
where clause
delete from authors where state = 'CA'
Transaction Logs
The full discussion of transaction
logs is beyond the scope of this class
Every change to data (insert, update,
and delete) is logged to a special file
called
ll d a ttransaction
ti llog.
This is why insert, update, and delete
are referred to as logged operations
Truncate
You can also delete all of the data in
a table without using a delete.
This is accomplished via a truncate
command
truncate table table_name
truncate table authors
is the same as
delete authors
Truncate
The difference is in how these two
commands are handled
Delete is a logged operation
Truncate is a nonlogged operation
This becomes important in
recovering a server from a crash
Truncate
Generally you should not use a
truncate command
In some client sites, this is a
command that is reserved for the
DBA (d
(database
t b
administrator)
d i i t t )
The truncate will perform faster,
because it does not write to the
transaction log, but this command
should be avoided at all costs by
anyone other than a DBA
It is included here for completeness
p
Unit 9 Review
Unit 9 Exercises
Time allotted for exercises is 1/2
hour