1. SQL302
Intermediate SQL Programming
Based on SQL Clearly Explained by Jan Harrington and
Microsoft SQL Server2008 T-SQL Fundamentals by Itzik Ben-gan
Module 1 – Relational Database Background, CASE,
Cast & Convert, Subqueries, Table Expressions
Bookstore SQL302 Module 1 1
2. Note on SQL302 Slides
• Many of these slides were originally designed to
support a single SQL 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 vendor
specific slides out into their own slide sets.
Bookstore2 SQL302 Module 2 2
3. 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
Bookstore2 SQL302 Module 2 3
4. SQL302 Contact Information
P.O. Box 6142
Laguna Niguel, CA 92607
949-489-1472
http://www.d2associates.com
slides.1@dhdursoassociates.com
Copyright 2001-2012. All rights reserved.
Bookstore2 SQL302 Module 2 4
5. SQL302 Resources
• Bookstore database scripts found on
box.com at
http://tinyurl.com/SQLScripts
• Slides can be viewed on SlideShare…
http://www.slideshare.net/OCDatabases
• Follow up questions?
sql.support@dhdursoassociates.com
Bookstore SQL302 Module 1 5
6. 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
Bookstore SQL302 Module 1 6
7. SQL302
• Students should have taken SQL202 or
have equivalent experience. It is assumed
students know basic SQL.
• We will use the Management Studio in this
class, but the focus will be on SQL
scripting
Bookstore SQL302 Module 1 7
8. 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
Bookstore SQL302 Module 1 8
18. SQL Standardization
ANSI standardization
– First standard in 1986
– SQL 89
– SQL 92
– SQL 99
• Various vendor extensions
– Microsoft/Sybase: T-SQL
– Oracle: PL/SQL
Bookstore SQL302 Module 1 18
19. SQL Conformance
• Entry
• Intermediate
• Advanced
• Most are at least entry level
Bookstore SQL302 Module 1 19
20. SQL Statements
• Data Manipulation Language (DML)
• Data Control Language (DCL)
• Data Definition Language (DDL)
• Note: SQL 99 changes these to seven types
including DQL Data Query Language
Bookstore SQL302 Module 1 20
21. 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
Bookstore SQL302 Module 1 21
22. SQL DCL
• Data Control Language (DDL)
– Grant
– Revoke
– Deny
– Constraints
Bookstore SQL302 Module 1 22
23. SQL DQL
• Data Manipulation Language (DML)
– Select
Bookstore SQL302 Module 1 23
24. SQL DML
• Data Manipulation Language (DML)
– Insert
– Update
– Delete
Bookstore SQL302 Module 1 24
26. Sample Database(s)
• Before we continue (note: instructor may have
already done this)…
• Load the sample database(s) if not already loaded
– Use supplied SQL Script (after class this script may be
found on Box.com).
Bookstore SQL302 Module 1 26
27. Text Conventions
• In Access character strings are normally
surrounded by double quotes
– “Jones”
• In an enterprise database such as Oracle or
SQL Sever enclose text strings in single
quotes
– ‘Jones’
Bookstore SQL302 Module 1 27
28. Date Conventions
• In an enterprise database such as Oracle or
SQL Sever, enclose dates in single quotes
– ‘2004-12-23’ MySQL
– ’12-23-2004’ SQL Server
– ’23-DEC-04’ Oracle
Bookstore SQL302 Module 1 28
29. Select statement clauses
SELECT…
INTO…
FROM…
WHERE…
GROUP BY…
HAVING…
ORDER BY…
Bookstore SQL302 Module 1 29
30. SELECT
See SQL202 for syntax and
semantics of basic SELECT
statement
Bookstore SQL302 Module 1 30
31. On Your Own
• Find books written by Mark Twain
• Show title, publisher, year
Bookstore SQL302 Module 1 31
32. Complex Predicates
Follow normal boolean logic
Select customer_last_name,
customer_street
From customers
Where (customer_last_name =
‘Jones’ or customer_last_name =
‘Smith’)and customer_state=‘NY’
Bookstore SQL302 Module 1 32
35. Special Operators
• Can be used in where clause
• Covered in this class (SQL302)
– Exists (Covered in section on Joins)
– Like extensions
– Any, some, all
• Previously Covered in SQL202
– LIKE
– IN
– BETWEEN
– IS NULL
Bookstore SQL302 Module 1 35
36. Like Extensions
• ANSI wildcards
• Where
customer_last_name
like ‘[JK]o%’
like ‘[J-M]%’
like [^abc]%
Bookstore SQL302 Module 1 36
37. Any, some, All
• Any, some • All
• Modifies comparison • Modifies comparison
operator operator
• Ex: expr > any (1,2,3) • Ex: expr > all(1,2,3)
means expr would would have to be
have to be greater greater than 3
than the minimum
which is 1
Bookstore SQL302 Module 1 37
38. On Your Own
• Find all customers with a last name that starts
with a through m
• Find all customers that live in a state that does
not start with m
Bookstore SQL302 Module 1 38
39. Case
• Used to return a choice from two or more
alternatives
• Two forms
– Searched case
– Unsearched case
Bookstore SQL302 Module 1 39
40. Unsearched (Simple) CASE
• This form of case has a selector which
takes on a value used to select an
alternative
• Syntax:
Select case <selector>
When <value1> then <expr1>,
When <value2> then <expr2>,
…
Else
<statement>
End
Bookstore SQL302 Module 1 40
41. Unsearched (Simple Case)
• Example: expand the order filled status
columns in the orders table
Bookstore SQL302 Module 1 41
42. Searched CASE
• This form of the Case statement does not
have a selector
• Syntax:
Select case
When <condition1> then <expr1>,
When <condition2> then <expr2>,
…
Else
<statement>
End
Bookstore SQL302 Module 1 42
43. Searched CASE
• Example: list names of referring
customers, self in no referrer
Bookstore SQL302 Module 1 43
44. CAST
• Function to cast a column to a different
data type; same idea as cast in c
programming
• Syntax:
CAST ( expression AS data_type [ ( length ) ] )
Bookstore SQL302 Module 1 44
45. CAST
• Example: combine author name and
publication year into one column
Bookstore SQL302 Module 1 45
47. Convert
• Function to convert from one data type to
another; mostly replaced by cast
• Syntax
CONVERT ( data_type [ ( length ) ] , expression
[ , style ] )
Bookstore SQL302 Module 1 47
48. Convert
• Example:
– Remove time from display of a datetime
column
Bookstore SQL302 Module 1 48
50. 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
Bookstore SQL302 Module 2 50
51. Uncorrelated Subquery
• In list (covered in sql202 basic class)
• Single valued
Bookstore SQL302 Module 2 51
52. 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’);
Bookstore SQL302 Module 2 52
53. Single-valued Subquery
• Subqueries can be used where an
expression returns a scalar or single value
– calculations
– comparisons
• Can be used in select list, from clause and
where clause
Bookstore SQL302 Module 2 53
54. Single-valued Subquery
• Example
– Show all orderlines with an order total greater
than the average for all orderlines
• Code
use bookstore;
SELECT isbn, quantity
, (select avg(quantity) from orderlines) as
[Average Quantity]
FROM orderlines AS ol
WHERE quantity >
(select avg(quantity) from orderlines)
Bookstore SQL302 Module 2 54
55. 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
Bookstore SQL302 Module 2 55
56. Correlated subquery with Exists
SELECT isbn, quantity
FROM orderlines AS ol
WHERE exists
(select * from orders o where
ol.order_numb = o.order_numb
and o.order_date between ‘1/1/99’
and ‘12/31/99’);
Bookstore SQL302 Module 2 56
57. Derived Tables
• Sort of a named subquery
• Allows you to access columns inside the
subquery from the containing outer query
• Syntax
<select statement> as derivedtablename
Bookstore SQL302 Module 2 57
58. Derived Tables
• Example: List the number of orders per
year
• Code
use bookstore;
select order_year, count(order_numb)
from(
select YEAR(order_date) as order_year,
order_numb
from orders) as d
group by order_year;
Bookstore SQL302 Module 2 58
59. Common Table Expressions
• Can be used to define a subquery that can
be reused within an SQL statement
• Syntax
With CTE_name (column list)
As (
Select statement
)
<outer query that uses the CTE>
Bookstore SQL302 Module 2 59
60. Common Table Expressions
• Example: show order_lines with cost more
than the average. Demonstrate two
techniques:
– Technique 1 - Using subqueries w/out a CTE
– Technique 2 - With CTE’s
Bookstore SQL302 Module 2 60
61. Technique 1 – w/out CTE
select isbn, cost_each, (select
AVG(cost_each)from orderlines)
from orderlines
where cost_each > (select AVG(cost_each) from
orderlines)
order by isbn;
Bookstore SQL302 Module 2 61
62. Technique 2 – using a CTE
with average_cost_cte(average_cost)
as
(select AVG(cost_each)
from orderlines)
select isbn, cost_each, average_cost
from orderlines, average_cost_cte
where cost_each > average_cost
order by isbn;
Bookstore SQL302 Module 2 62
63. SQL Exercises
• List all customers whose last name does not
end with s or t.
• Find all customers who have not placed an
order.
• Find all order lines with an amount less than
the average. Include the order date without the
time.
• List all books with a price greater than the
average price for all books. Show the variance
from the average, too. Use a CTE.
Bookstore SQL302 Module 1 [end module] 63