1. Bookstore SQL201S 1
An accelerated introduction to SQL for non-
programmers
P.O. Box 6142
Laguna Niguel, CA 92607
949-489-1472
http://www.ocdatabases.com
Welcome to SQL201S –
Accelerated Introduction to
SQL Queries Using MySQL
2. Bookstore SQL201S 2
Accelerated Introduction to
SQL
• Introduction (s)
• Facilities
• Course Packet (contents may vary)
– Student questionnaire (may be onleine)
– Collaterals (Maps, Catalogs, Etc.)
– PowerPoint handouts for all sessions
– Evaluation form (may be online)
– Training certificate
3. Bookstore SQL201S 3
SQL Curriculum
SQL200*
SQL200S*
SQL212
Oracle
SQL202
Transact-SQL
SQL201W
MySQL
* = included in
above courses
4. Bookstore SQL201S 4
Accelerated Introduction to SQL
• Assumes no prior knowledge of SQL
• Quick pace for experienced computer users
• End-user, not programmer, oriented
• Focus is on SQL, not Workbench
• SQL201S is first two modules of SQL201,
otherwise identical.
9. Bookstore SQL201 Module 1 9
SQL201
MySQL Programming
Based on SQL Clearly Explained by Jan Harrington
Module 1 – Relational Database Background,
Basic Single Table Retrieval Operations
10. Note on SQL201 Slides
• These slides were originally designed to support the
single SQL200 course which was used for any of
MS Access, MySQL, Oracle and SQL Server.
• As such you may see here slides developed in any
one of the above products.
• We are in the process of migrating the slides out into
their own slide sets.
Bookstore SQL201 Module 1 10
11. Bookstore SQL201 Module 1 11
Warning!
• Below are some table name changes to be
aware of in doing queries. We have created
synonyms so either name should work.
New Name Old Name
Orders Order_filled
Order_Lines Orderlines
12. Bookstore SQL201 Module 1 12
SQL201 Contact Information
P.O. Box 6142
Laguna Niguel, CA 92607
949-489-1472
http://www.d2associates.com
slides.1@dhdursoassociates.com
Copyright 2001-2015. All rights reserved.
13. SQL201 Resources
• Bookstore database scripts found on
box.net at
http://tinyurl.com/SQLScripts
• Slides can be viewed on SlideShare…
http://www.slideshare.net/OCDatabases
• Follow up questions?
support@ocdatabases.com
Bookstore SQL201 Module 1 13
14. Bookstore SQL201 Module 1 14
SQL Programming
• Course focus is SQL language
• Widely used for:
– Database administration
– Enterprise application development
– Data driven web sites
• A foundation skill for eBusiness and
almost all major business applications that
use relational databases
15. Bookstore SQL201 Module 1 15
SQL Programming
• A basic knowledge of query systems,
perhaps via MS Access, or some
programming knowledge, is desirable
• We will use GUI tools such as MySQL
workbench in this class. But we will be
typing up the scripts directly in SQL code.
16. Bookstore SQL201 Module 1 16
Relational Database Evolution
• Based on Codd’s paper
• Early commercial efforts focused on Unix
• First mainframe implementation by IBM -
precursor to today’s DB2
• First PC implementation in early 80’s by
Oracle
26. Bookstore SQL201 Module 1 26
SQL Standardization
ANSI standardization
– First standard in 1986
– SQL 89
– SQL 92
– SQL 99
• Various vendor extensions
– Microsoft/Sybase: T-SQL
– Oracle: PL/SQL
27. Bookstore SQL201 Module 1 27
SQL Conformance
• Entry
• Intermediate
• Advanced
• Most are at least entry level
28. Bookstore SQL201 Module 1 28
SQL Statements
• Data Manipulation Language (DML)
• Data Control Language (DCL)
• Data Definition Language (DDL)
• Note: SQL 99 changes these to seven types
29. Bookstore SQL201 Module 1 29
SQL DDL
• Data definition language (DDL)
– Create, alter, drop, etc.
– Frequently implemented via various CASE
tools: Visio, Embarcadero, ERWin, etc.
– But very useful for database administration
30. Bookstore SQL201 Module 1 30
SQL DCL
• Data Control Language (DDL)
– Grant
– Revoke
– Deny
– Constraints
33. Bookstore SQL201 Module 1 33
Bookstore Sample Database
• Before we continue (note: instructor may have
already done this)…
• Load the sample database if you haven’t already
– Run the supplied SQL script
34. Bookstore SQL201 Module 1 34
Text Conventions
• In an enterprise database such as Oracle or
MySQL enclose text strings in single
quotes
– ‘Jones’
35. Bookstore SQL201 Module 1 35
Date Conventions
• In an enterprise database enclose dates in
single quotes
– ‘2004-12-23’ MySQL
– ’12-23-2004’ SQL Server
– ’23-DEC-04’ Oracle
36. Select statement clauses
SELECT columns
FROM tables
WHERE condition
GROUP BY columns
HAVING condition
ORDER BY columns
Bookstore SQL201 Module 1 36
37. Bookstore SQL201 Module 1 37
SELECT
Basic Syntax (Projection):
Select <column-list> or <*>
From <table-list>
38. Bookstore SQL201 Module 1 38
SELECT
Basic Example (Projection):
select
customer_last_name,
customer_street
from customers
40. Bookstore SQL201 Module 1 40
SELECT with Where Clause
Example (Restriction plus Projection):
Select <column-list> or *
From <table-list>
Where <selection-criteria>;
41. Bookstore SQL201 Module 1 41
Comparison Operators
• < less than
• > greater than
• <= less than or equal to
• >= greater than or equal to
• = equal to
• <> or != two forms for not equal
42. Bookstore SQL201 Module 1 42
SELECT with Where
Basic Example (Restriction plus Projection):
select customer_last_name,
customer_first_name,
customer_street
from customers
where customer_last_name =
‘Jones’
48. Bookstore SQL201 Module 1 48
Special Operators
• Can be used in where clause
• LIKE
• IN
• BETWEEN
• IS NULL
• EXISTS
49. Bookstore SQL201 Module 1 49
Like (“Wild Card Matches”)
• Use ANSI wildcard
characters: % _
• Where
customer_last_name
like ‘Jo%’
like ‘Jo_’
There are also additional regular
expression search patterns
50. Bookstore SQL201 Module 1 50
IN
Select *
From customers
Where customer_last_name in
(‘Rizzo’, ‘Jones’, ‘Garcia’);
The list in parentheses can be replaced by a
subquery. We will study this later.
53. Bookstore SQL201 Module 1 53
IS NULL
SQL uses three valued logic. A null is NOT the
same as blank or empty. It means missing or
unknown.
54. Bookstore SQL201 Module 1 54
IS NULL
Select *
From customers
Where customer_street IS
NULL;
Must use IS NULL to test for NULL values.
Cannot even use = NULL.
55. Bookstore SQL201 Module 1 55
On Your Own
• Find all customers with an address not equal to
4592 Maple Lane
• Was Peter Johnson selected?
• Why or why not?
56. Bookstore SQL201 Module 1 56
BETWEEN
List all orders placed in 1999.
select *
from orders
where order_date BETWEEN
‘1999-01-01’ and ‘1999-12-
31’;
Note: date formats vary from product to product; recent
versions tend to be pretty flexible.
58. Bookstore SQL201 Module 1 58
Removing Duplicates
Select DISTINCT
customer_city
From customers;
List once each city in which there are
customers
Removes duplicate rows from result set
60. Bookstore SQL201 Module 1 60
Sorting – ORDER BY
DESC will sort in descending order
Basic syntax:
Select <column list> or *
From <table list>
Where <selection criteria>
Order by <column list> [DESC]
61. Bookstore SQL201 Module 1 61
Sorting – ORDER BY
select *
from orderlines
order by cost_line desc,
isbn;
List all orderlines sorted by cost
descending
63. Bookstore SQL201 Module 1 63
Limiting Record Selection
Select order_numb, isbn,
cost_line
From orderlines
Order by cost_line desc, isbn
limit 5;
List largest 5 orderlines…
65. Bookstore SQL201 Module 1 65
SQL Exercises
• List all books whose publisher name begins
with “H” or “T”; sort by title [hint: use LIKE]
• List all customers whose last name ends with
“S”; sort by state, city, last name
• Find the order numbers of orders with order
dates in 1999; sort by order #. [Hint: use
BETWEEN]
• Find the order numbers and order dates of all
orders with a “2” in character position 2 of the
credit card #; sort by order date descending
[end module]
69. Bookstore SQL201 Module 2 69
SQL201
SQL Programming
Workshop 2 – Joins, Subqueries, Unions,
Calculations and Grouping
Based on SQL Clearly Explained by Jan Harrington
70. Note on SQL201 Slides
Bookstore SQL201 Module 2 70
• These slides were originally designed to support the
single SQL201 course which was used for any of MS
Access, MySQL, Oracle and SQL Server.
• As such you may see here slides developed in any one of
the above products.
• We are in the process of migrating the slides out into their
own slide sets.
71. Bookstore SQL201 Module 2 71
Warning!
• Below are some table name changes to be
aware of in doing queries. We have created
synonyms so either name should work.
New Name Old Name
Orders Order_filled
Order_Lines Orderlines
72. Bookstore SQL201 Module 2 72
SQL201 Contact Information
P.O. Box 6142
Laguna Niguel, CA 92607
949-489-1472
http://www.d2associates.com
slides.1@dhdursoassociates.com
Copyright 2018 All rights reserved.
73. SQL201 Resources
• Bookstore database scripts found on
box.net at
http://tinyurl.com/SQLScripts
• Slides can be viewed on SlideShare…
http://www.slideshare.net/OCDatabases
• Follow up questions?
support@ocdatabases.com
Bookstore SQL201 Module 2 73
76. Bookstore SQL201 Module 2 76
Joins
• Inner
• Outer
– Left
– Right
– Full
• Cross
• Self
• Theta
• We will cover the most important; others as time
and interest permit
78. Bookstore SQL201 Module 2 78
Inner Join
• Pairs each row from first table
with corresponding row from
second table over the “join
column”
• The result set only contains
rows where there is a match
over the join column in both
tables
• Equi-join is the common inner
join
79. Bookstore SQL201 Module 2 79
Inner Join
Older Syntax:
Select <column-list>
From <tablelist>
Where <predicate>
Still very commonly used
80. Bookstore SQL201 Module 2 80
Inner Join
Example using older syntax:
SELECT customer_first_name,
customer_street, order_numb,
order_date
from customers, orders
Where customers.customer_numb =
orders.customer_numb
85. Bookstore SQL201 Module 2 85
Inner Join over Multiple columns
• Note that that the join condition can apply
to multiple columns if desired
• Used with composite keys
86. Bookstore SQL201 Module 2 86
Inner Join
• In the last example…
– What was the cardinality of the relationship
between customers and orders?
– Which table was the parent?
– What was it’s primary key?
– In which table did we employ a foreign key
and what was it?
87. Bookstore SQL201 Module 2 87
Cross Join
• What happens when you omit a join
expression?
• Get the cartesian product of the tables – all
possible combinations of the two tables
• For large tables this will run a long time!
• There are uses for these which we will
save for an advanced class
88. Bookstore SQL201 Module 2 88
Joining More than Two Tables
• Can join several tables in one select
• Try to limit to three or four
• Join order can be important for
performance (although optimizers will
usually handle this for you)
• Use parentheses to force order of
evaluation (also vendor extensions, often
called “hints”)
89. Bookstore SQL201 Module 2 89
Joining More than Two Tables
• Add orderlines detail to previous queries
SELECT customer_first_name, customer_street,
orders.order_numb, orders.order_date,
orderlines.isbn, orderlines.quantity
FROM customers
INNER JOIN orders ON
customers.customer_numb=orders.customer_numb
INNER JOIN orderlines
on orders.order_numb = orderlines.order_numb
90. Bookstore SQL201 Module 2 90
Correlation Names (Table Aliases)
Basic Example:
SELECT customer_first_name,
customer_street, order_numb,
order_date
from customers as c
inner join orders as o
on c.customer_numb = o.customer_numb
alias
92. On Your Own
• Add the book title to the previous query
results
• Hint: add another join to books table
Bookstore 92SQL201 Module 2
93. Bookstore SQL201 Module 2 93
Outer Joins
• Left – selects all rows from the left or first table,
even if no match exists in the other table
– Widely used in commercial practice
– Especially useful for reporting
– Can be slower and interfere with optimizer
• Right – same idea but all rows from right table
• Full – all rows form both tables
94. Bookstore SQL201 Module 2 94
Left Outer Join
Basic SQL 92 Syntax:
Select <column-list>
From <table1>
Left [outer] join
<table2>
On <join condition>
95. Bookstore SQL201 Module 2 95
Left-Join
Basic Example:
SELECT customer_first_name,
customer_street, order_numb,
order_date
from customers as c
left join orders as o
on c.customer_numb =
o.customer_numb
97. Negative query
• Add where clause to outer join
• Restrict to nulls on a column from the
child table that cannot be null in the actual
table
– This implies there is no child record
• This is a classic “forensics” query. It finds
unmatched or missing information.
Bookstore SQL201 Module 2 97
98. Negative Join Example
• Find customers that have not placed any orders
Bookstore SQL201 Module 2 98
99. Bookstore SQL201 Module 2 99
Self Joins
• Implements a recursive relationship
• Important in various applications
– Parts lists/assemblies
– HR
– Etc.
– Table joined to itself using correlation names
100. Bookstore SQL201 Module 2 100
Self Joins
SELECT e.name, m.name as manager
FROM employees AS e
left join employees AS m
on e.mgr_soc_sec_no = m.soc_sec_no;
103. Bookstore SQL201 Module 2 103
Subqueries
• One select statement embedded in another
• Can be nested multiple levels deep
• Can be used in select, from and where
clauses
• Two types:
– Uncorrelated – executes inner query then outer
– Correlated – executes inner query once for
each outer query row
104. Bookstore SQL201 Module 2 104
Uncorrelated Subquery
select isbn, quantity
from orderlines
where order_numb in
(select order_numb from
orders where order_date
between ‘1/1/99’ and
‘12/31/99’);
106. Bookstore SQL201 Module 2 106
Negative Subquery
• A type of subquery that matches “not
found” conditions
107. Bookstore SQL201 Module 2 107
Negative Subquery
select isbn, quantity
from orderlines
where order_numb not in
(select order_numb from
orders where order_date
between ‘1/1/99’ and
‘12/31/99’);
109. Bookstore SQL201 Module 2 109
Correlated Subquery with Exists
• Inner subquery executed once for each outer row
• Exists will return true or false depending on
whether the result will have any rows or not
• Can be a quick way to test for existence of
records (parent records, say) as used in
application enforcement of referential integrity
This type of query covered in intermediate SQL class
110. Bookstore SQL201 Module 2 110
Unions
• Combines two or more tables
• Tables must be union compatible
111. Bookstore SQL201 Module 2 111
Unions
Select <column-list> from
<table1>
Union [ALL]
Select <same-columns> from
<table2>
112. Bookstore SQL201 Module 2 112
Unions Mailing List Script
select <sources table columns>
from sources
union
select <customers table
columns>
from customers
115. Bookstore SQL201 Module 2 115
Calculated Fields
• Can add a column calculated from others
SELECT order_numb, quantity,
cost_each,
quantity*cost_each as
extension
FROM orderlines
121. Bookstore SQL201 Module 2 121
Date Functions
• Numerous date functions
• Often vendor specific
• Often used:
– year
– month
– Date_Add(…), DateDiff(…)
– Current_date(), Date_Format
• Ex: where year(order_date) = 1999
123. Bookstore SQL201 Module 2 123
Aggregate Functions
• Count
• Sum
• Min
• Max
• Avg
• Often used in conjunction with grouping
124. Bookstore SQL201 Module 2 124
Aggregate Functions
Basic syntax:
Select <function>(<column>)
From <table>
Group by <column-list>
Having <predicate>
Group by all columns to left of one(s)
you want to aggregate
125. Bookstore SQL201 Module 2 125
Aggregate Functions
SELECT order_numb, Count(*) AS
’Number of Order Lines’ ,
Sum(quantity) AS ‘Total Quantity’,
Sum(quantity * cost_each) AS ‘Total
Amount’
FROM order_lines
GROUP BY order_numb
having count(*) > 1;
127. Bookstore SQL201 Module 2 127
Having vs. Where
• Having and Where clauses are similar but
not the same
• Having removes groups after they are
formed
• Where removes rows before groups are
formed
128. Bookstore SQL201 Module 2 128
Exercise
• List all customers and their orders
– Name nicely formatted
– With orders in the year of 1999 (do not use
between, etc.)
– Show total order quantities and amounts
– Only include orders with more than three
order lines