SQL302 Intermediate SQL using Microsoft SQL Server. Covers additional uses of subqueries, set functions, table expressions, with clause, new SQL window functions.
The Codex of Business Writing Software for Real-World Solutions 2.pptx
SQL302 Intermediate SQL
1. Orange Coast Database Associates Course PowerPoint Slides (800)355-9855 or http://www.dhdursoassociates.com
SQL302 Intermediate SQL Using
Microsoft SQL Server
Orange Coast
Database Associates
Specializing in Microsoft Office,
Access, SQL, and related technologies
Classes custom designed for Working Professionals
http://www.dhdursoassociates.com
San Juan Capistrano, CA
(800)355-9855
Accelerated Computer Training for Working Professionals Bookstore Case
2. Welcome to SQL302 –
Intermediate SQL
Using MS SQL Server
An accelerated course in intermediate SQL for
experienced SQL users.
P.O. Box 6142
Laguna Niguel, CA 92607
949-489-1472
http://www.d2associates.com
Bookstore SQL302 1
Intermediate SQL
• Introduction (s)
• Facilities
• Course Packet (contents may vary)
– Student questionnaire
– Collaterals (Maps, Catalogs, Etc.)
– PowerPoint handouts for all sessions
– Evaluation form
– Training certificate
Bookstore SQL302 2
1
3. 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 3
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 4
2
4. About Us 5
Intermediate SQL Curriculum
SQL322W SQL302 SQL312
MySQL** Transact-SQL Oracle**
•*= first day only
•**=under
SQL3xxS* development
Bookstore SQL302 6
3
5. Intermediate SQL
• Assumes prior knowledge of SQL
equivalent to SQL202.
• Quick pace for experienced computer users
• End-user, not programmer, oriented
• Focus is on SQL, not Management Studio
• SQL302s is first two modules of SQL302.
Bookstore SQL302 7
Intermediate SQL
SQL Covered (Day 1: All Day):
• Select
– More filters & operators
– Case, cast, convert
– Subqueries
– Table expressions
– Joins
– Set operations
– Window functions
Bookstore SQL302 8
4
6. Intermediate SQL
SQL Covered (Day 2: AM Only):
• Data Updates
– Select into
– Update from, using subqueries
– Delete from
• Data structures
– Alter
– Synonyms
– Views
Bookstore SQL302 9
Intermediate SQL
Course Format:
• 3 Sessions
• Lecture
• Demo
• Student “hands-on”
• Many exercises are cumulative –
later examples build on queries
created earlier
Bookstore SQL302 10
5
7. Intermediate SQL
Course Schedule (“1/2” day sessions):
• Session 1 – Intermediate
SQL
• Session 2 – Multi-table
Retrieval
• Session 3 – Modifying data
and data structures
Bookstore SQL302 11
Notes
Bookstore SQL302 12
6
8. 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
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
1
9. 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
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
2
10. 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
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
3
11. 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
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
4
13. Constraints
• Database • Other Business Rule
– Domain – Triggers
– Uniqueness – Stored Procedures
– Relationship
Cardinality
• 1 to 1
• 1 to N
Bookstore SQL302 Module 1 11
Relational Database with constraints
Bookstore SQL302 Module 1 12
6
14. Database Management Systems
Positioning Chart
Cost VLDB
Enterprise
Workgroup
Single user
Spreadsheet
# Users
Bookstore SQL302 Module 1 13
System Architecture
File Server
Architecture
Access
MDB
Access
Bookstore SQL302 Module 1 14
7
15. System Architecture
Client/Server
Architecture
Oracle
SQL DB
Visual Access
Basic App
Bookstore SQL302 Module 1 15
System Architecture
Web
Architecture
Web Oracle
Server DB
SQL
Browser
Bookstore SQL302 Module 1 16
8
16. Approaching SQL
• Relatively simple
• Two main environments
– Interactive (This course)
– Embedded
• Static (Compiled)
• Dynamic
Bookstore SQL302 Module 1 17
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
9
17. SQL Conformance
• Entry
• Intermediate
• Advanced
• Most are at least entry level
Bookstore SQL302 Module 1 19
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
10
18. 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
SQL DCL
• Data Control Language (DDL)
– Grant
– Revoke
– Deny
– Constraints
Bookstore SQL302 Module 1 22
11
19. SQL DQL
• Data Manipulation Language (DML)
– Select
Bookstore SQL302 Module 1 23
SQL DML
• Data Manipulation Language (DML)
– Insert
– Update
– Delete
Bookstore SQL302 Module 1 24
12
20. SQL Statement Processing
Parse
Validate
Optimize
Access Plan
Execute
Bookstore SQL302 Module 1 25
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
13
21. 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
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
14
22. Select statement clauses
SELECT…
INTO…
FROM…
WHERE…
GROUP BY…
HAVING…
ORDER BY…
Bookstore SQL302 Module 1 29
SELECT
See SQL202 for syntax and
semantics of basic SELECT
statement
Bookstore SQL302 Module 1 30
15
23. On Your Own
• Find books written by Mark Twain
• Show title, publisher, year
Bookstore SQL302 Module 1 31
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
16
24. Select with Complex Where
Bookstore SQL302 Module 1 33
Complex Where Result
Bookstore SQL302 Module 1 34
17
25. 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
Like Extensions
• ANSI wildcards
• Where
customer_last_name
like ‘[JK]o%’
like ‘[J-M]%’
like [^abc]%
Bookstore SQL302 Module 1 36
18
26. 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
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
19
27. Case
• Used to return a choice from two or more
alternatives
• Two forms
– Searched case
– Unsearched case
Bookstore SQL302 Module 1 39
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
20
28. Unsearched (Simple Case)
• Example: expand the order filled status
columns in the orders table
Bookstore SQL302 Module 1 41
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
21
29. Searched CASE
• Example: list names of referring
customers, self in no referrer
Bookstore SQL302 Module 1 43
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
22
30. CAST
• Example: combine author name and
publication year into one column
Bookstore SQL302 Module 1 45
CAST results
Bookstore SQL302 Module 1 46
23
31. 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
Convert
• Example:
– Remove time from display of a datetime
column
Bookstore SQL302 Module 1 48
24
32. Convert results
Bookstore SQL302 Module 1 49
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
25
33. Uncorrelated Subquery
• In list (covered in sql202 basic class)
• Single valued
Bookstore SQL302 Module 2 51
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
26
34. 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
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
27
35. 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
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
28
36. 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
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
29
37. 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
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
30
38. 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
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
31
39. 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
Notes
Bookstore SQL302 Module 1 64
32
40. SQL302
Intermediate SQL Programming
Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T-
SQL Fundamentals by Itzki Ben-gan
Workshop 2 – Joins, Set Operations, Window
Functions
Bookstore SQL302 Module 2 1
Note on SQL302 Slides
• 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 Oracle,
Access, and MySQL slides out into their own slide
sets. The SQL302 slides will cover Microsoft SQL
Server.
Bookstore SQL302 Module 2 2
1
41. 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
Bookstore SQL302 Module 2 3
SQL302 Contact Information
P.O. Box 6142
Laguna Niguel, CA 92607
949-489-1472
http://www.d2associates.com
slides.1@dhdursoassociates.com
Copyright 2001-2012All rights reserved.
Bookstore SQL302 Module 2 4
2
42. SQL302 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?
sql.support@dhdursoassociates.com
Bookstore SQL302 Module 2 5
Relational Database with constraints (from text)
Bookstore SQL302 Module 2 6
3
43. Sample Employees Database
Bookstore2 & SQL204 Module 1 7
Employees
More conventions
• Names can be surrounded with “ “ or [ ] as
in [order details].
• Some of the PowerPoint slides may have
this convention.
• Better practice is to use an underscore as in
order_details.
Bookstore SQL302 Module 2 8
4
44. SQL302
SQL Programming
Part 1 – Joins: Natural, Self and Outer
Bookstore SQL302 Module 2 9
Joins
• Inner (Covered in SQL202 course)
• Natural Join
• Self
• Data Warehouse operators
• Outer
– Left
– Right
– Full
• Cross
• Theta
• We will cover some of the more advanced or subtle
aspects of joins in this class
Bookstore SQL302 Module 2 10
5
45. Natural Joins
• Table1 natural join table3 – automatically
uses columns with same name
• Table 1 natural join table2 using(<column-
list>
• Not yet available in SQL Server
Bookstore SQL302 Module 2 11
Correlation Names (Table Aliases)
• Can abbreviate references to tables
• For example:
Select e.name, j.payrange
From employees as e
Inner join job_information as j
On e.jobcode = j.jobcode;
Bookstore SQL302 Module 2 12
6
46. Self Joins
• Implements a recursive relationship
• Important in various applications
– Parts lists/assemblies
– HR
– Etc.
– Table joined to itself using correlation names
Bookstore SQL302 Module 2 13
Self Joins
SELECT e.*, m.name
FROM employees AS e, employees
AS m
WHERE e.managerid =
m.employeeid;
Bookstore SQL302 Module 2 14
7
47. Bookstore SQL302 Module 2 15
Datawarehouse clauses
• Two keywords that can be added to a
grouped query
– Rollup
– Cube
• Places additional summary rows in the
result set
• Result set is a true relational result set
Bookstore SQL302 Module 2 16
8
48. Rollup
• Example: calculate average salaries by
job_title_code and manager
Bookstore SQL302 Module 2 17
Rollup results
Bookstore SQL302 Module 2 18
9
49. cube
• Similar to rollup but computes summary
rows in all dimensions
Bookstore SQL302 Module 2 19
Cube results
• Add a new set of rows which total by year
Bookstore SQL302 Module 2 20
10
50. Bookstore SQL302 Module 2 21
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
Bookstore SQL302 Module 2 22
11
51. Left Outer Join
Basic SQL 92 Syntax:
Select <column-list>
From <table1>
Left join <table2>
On <join condition>
Bookstore SQL302 Module 2 23
Left Outer Join
• List all customers with their orders
• Include customers with no orders as well
Bookstore SQL302 Module 2 24
12
52. 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
Bookstore SQL302 Module 2 25
Left Join with Results
Bookstore SQL302 Module 2 26
13
53. Negative Left Join
• List all the customers who have not placed
any orders
• This is an example of a query which finds
unmatched records
Bookstore SQL302 Module 2 27
Negative Left-Join (Unmatched)
Basic Example:
SELECT customer_first_name,
customer_last_name, order_numb,
order_date
from customers as c
left join orders as o
on c.customer_numb =
o.customer_numb
Where order_numb is null;
Bookstore SQL302 Module 2 28
14
54. Bookstore SQL302 Module 2 29
Left Join w/ Partial Match
• List all customers along with any orders
placed in 1999
• If they did not place 1999 orders we still
want to include them in the printout
Bookstore SQL302 Module 2 30
15
55. Left Join w/ Partial Match
Example:
SELECT customer_first_name,
customer_last_name, order_numb, order_date
from customers as c
Left join
(select customer_numb, order_numb,
order_date
From orders
Where year(order_date) = 1999) as d
on c.customer_numb = d.customer_numb;
Bookstore SQL302 Module 2 31
Own Your Own
• List all books and their order totals for
1999
• Show the book even if there were no orders
placed in 1999
Bookstore SQL302 Module 2 32
16
56. Theta Joins
• Theta joins involve inequalities in the
matching conditions
• Can be used for some interesting queries
which do not involve the usual primary key
to foreign key matchings
Bookstore SQL302 Module 2 33
Theta join
• Find all customers that live at the same address
– Requires a self join of the customers table on address
field
Bookstore SQL302 Module 2 34
17
57. Theta join results
• Can be further processed with a union query to
consolidate names into a single list
Bookstore SQL302 Module 2 35
SQL302
SQL Programming
Part 3– Set Operations
Bookstore SQL302 Module 2 36
18
58. Set Operations
• More on unions
• Intersect
• Except
Bookstore SQL302 Module 2 37
Unions
• Combines two or more tables
• Tables must be union compatible
Bookstore SQL302 Module 2 38
19
59. Unions
Select <column-list> from
<table1>
Union [ALL]
Select <same-columns> from
<table2>
Bookstore SQL302 Module 2 39
Unions
• Example: consolidate two columns into one
column
Bookstore SQL302 Module 2 40
20
60. Union consolidation result
• Customers in same city
Bookstore SQL302 Module 2 41
Unions
• Example: add a total row to a query result
• Code:
use bookstore;
select order_numb
, sum(quantity) as "Quantity"
, sum(cost_line)as "Total Cost"
from orderlines
group by order_numb
union
select NULL, sum(quantity),
sum(cost_line)
from orderlines;
Bookstore SQL302 Module 2 42
21
61. unions
• Example: add an element to a pick list
Bookstore SQL302 Module 2 43
intersect
• The intersect operator finds rows in
common between two tables
• Syntax
Select <column-list> from <table1>
intersect
Select <same-columns> from <table2>
Bookstore SQL302 Module 2 44
22
62. intersect
• Example: find cities in common between
sources and customers
• Code
select customer_city, customer_state,
customer_zip
from customers
intersect
select source_city, source_state,
source_zip
from sources; SQL302 Module 2
Bookstore 45
Except
• Finds all rows from first table that are not
found in the second table
• Syntax:
Select <column-list> from <table1>
except
Select <same-columns> from <table2>
Bookstore SQL302 Module 2 46
23
63. except
• Example: find sources that are not located
in any of our customer’s cities
• Code
select source_city, source_state,
source_zip
from sources
except
select customer_city, customer_state,
customer_zip
from customers;SQL302 Module 2
Bookstore 47
SQL302
SQL Programming
Part 4 – Window Functions
Bookstore SQL302 Module 2 48
24
64. Aggregate Functions
• Count
• Sum
• Min
• Max
• Avg
• Often used in conjunction with grouping
and window functions
Bookstore SQL302 Module 2 49
Window Functions
• Sort of like grouping, but aggregates can
be taken along with straight columns in the
select list
• The function is applied over a window
– Partition by column
– Partition by ()
Bookstore SQL302 Module 2 50
25
65. Window Functions
Basic syntax:
Select …, aggregate function(<column>)
over (partition by <column>)
From <table>
where <predicate>
Bookstore SQL302 Module 2 51
Window Functions
Example: Show salary along with average for the
job_title and overall
Code:
use employeedb;
select soc_sec_no, name, salary
, SUM(salary) over(partition
by job_title_code) as [Job Code
Average]
, SUM(salary) over() as
[Average]
from employees;
Bookstore SQL302 Module 2 52
26
66. 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
Bookstore SQL302 Module 2 53
Notes
Bookstore SQL302 Module 2 54
27
68. SQL302
Intermediate SQL Programming
Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T-
SQL Fundamentals by Itzki Ben-gan
Workshop 3 – Modifying Data, Managing the
Database
SQL Server/Employees SQL302 Module 3 1
Note on SQL302 Slides
• These slides were originally designed to support the
single SQL302 course which was used for any of
MS Access, 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 Oracle
MySQL, and MS Access slides out into their own
slide sets. These SQL302 slides will focus on
Microsoft SQL Server.
SQL Server/Employees SQL302 Module 3 2
1
69. 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
SQL Server/Employees SQL302 Module 3 3
SQL302 Contact Information
P.O. Box 6142
Laguna Niguel, CA 92607
949-489-1472
http://www.d2associates.com
slides.1@dhdursoassociates.com
Copyright 2001-2011. All rights reserved.
SQL Server/Employees SQL302 Module 3 4
2
70. SQL302 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?
sql.support@dhdursoassociates.com
SQL Server/Employees SQL302 Module 3 5
SQL302 Module 3
• Part 1 – Modifying Data
• Part 2 – Managing Database Structures
SQL Server/Employees SQL302 Module 3 6
3
71. SQL302
SQL Programming
Part 1 – Modifying Data
SQL Server/Employees SQL302 Module 3 7
Relational Database with constraints (from text)
SQL Server/Employees SQL302 Module 3 8
4
72. Sample Employees Database
Bookstore2 & SQL204 Module 1 9
Employees
Transactions
• Statements can be grouped
into transactions
• All must succeed
• If so they are all
committed
• If not they are all rolled
back
• Helps guarantee data is
consistent
SQL Server/Employees POS/410 Workshop 3 10
5
73. SQL Server Transactions Syntax
begin transaction
Statements
…
…
if @@error = 0
Commit transaction
else
Rollback error
SQL Server/Employees POS/410 Workshop 3 11
Data Modification Statements
• End-user rarely sees these
statements
• Application developer prepares
these statements “behind the
scenes” based on forms or web
pages filled out by user
SQL Server/Employees SQL302 Module 3 12
6
74. Data Modification Statements
• This course (SQL302)
– Select Into
– Table Valued Constructors (TVCs)
– Update
– Delete
• Basic DML already covered in
SQL202
SQL Server/Employees SQL302 Module 3 13
Select into
• Select….into will copy a table
• Uses a regular SQL statement with into
clause before the from not after
• Syntax:
Select <select list>
Into <tablename>
From <tablename>
SQL Server/Employees SQL302 Module 3 14
7
75. Select into
• Example:
– Copy a subset of the employees table to a
temporary working table
• Code:
SQL Server/Employees SQL302 Module 3 15
Insert with TVC
• Newer form of insert statement long
available in MySQL
• Can shorten your code
• Each element in the insert list can actually
be an expression but we will use literals in
this class
SQL Server/Employees SQL302 Module 3 16
8
76. Insert with TVC
SQL Server/Employees SQL302 Module 3 17
Update and Delete
• Updates and deletes can use
subqueries
• SQL Server allows update and
delete statements to be based on
joins, too
• We will review this in the next few
slides.
SQL Server/Employees SQL302 Module 3 18
9
77. Update
• You can use subqueries in an update.
– In where predicate
– To set the field value
UPDATE table
SET columnname = value from subquery
[WHERE condition with subquery]
SQL Server/Employees SQL302 Module 3 19
UPDATE w/ Subquery in where
• Example: Increase range minimums for unused
job codes
SQL Server/Employees SQL302 Module 3 20
10
78. UPDATE Results
SQL Server/Employees SQL302 Module 3 21
UPDATE FROM Statement
SQL Server allows updates from a table, including joined
tables. As an example one could update quantity on hand
in an inventory table from a transaction table.
UPDATE table
SET columnname = value…
[FROM tablelist]
[WHERE condition]
SQL Server/Employees SQL302 Module 3 22
11
80. Update w/ subquery in set clause
• Update employee temp table – set salaries to the
average for that code
SQL Server/Employees SQL302 Module 3 25
DELETE FROM Statement
SQL Server allows deletes from a table based on a
subquery or a join condition.
Basic syntax:
DELETE [from] table
FROM tablelist
[WHERE condition]
SQL Server/Employees SQL302 Module 3 26
13
82. Delete and Referential Integrity
• Can affect referential integrity when deleting a
“parent” row
• Can do following with child…
– Cascade: delete the child row
– Set null: set the child’s foreign key null
– Set default: as above but to default value
– No action: don’t allow delete of parent row
• Referential integrity can be established when
creating or modifying table structures which we
will look at later in the class
SQL Server/Employees SQL302 Module 3 29
SQL302
SQL Programming
Part 2– Managing Database Structures
SQL Server/Employees SQL302 Module 3 30
15
83. Managing Database Structures
• Create
• Alter
• Synonyms
• Views
SQL Server/Employees SQL302 Module 3 31
Managing Database Structures
• We will first create a table and then use the
alter command to
– Add columns
– Modify columns
– Add constraints
SQL Server/Employees SQL302 Module 3 32
16
85. Create Table
Example 1: SQL202 Create summary table
(we will do this step by step using the alter
statement in succeeding slides)
Create table summary(
isbn varchar(20) primary key,
How_many int check (how_many >= 0),
Constraint isbn_fk
Foreign key (isbn) references books(isbn)
)
SQL Server/Employees SQL302 Module 3 35
Create Table
Example 2: Create summary table
Create table #summary(
isbn varchar(20) primary key);
SQL Server/Employees SQL302 Module 3 36
18
86. Modifying a Table Design
• Applies to tables
• Use ALTER statement
– Add columns
– Delete columns
– Rename columns
– Add column constraints
– Add table constraints
SQL Server/Employees SQL302 Module 3 37
Modifying a Table Design
Basic syntax:
Alter <table-name>
Add <field-name>,
Add <table-constraint>,
Alter <field-name>
Etc.
SQL Server/Employees SQL302 Module 3 38
19
87. Add a column
Example: add a column to hold how
many times a book has been sold
alter table #summary
Add how_many numeric(5,2);
SQL Server/Employees SQL302 Module 3 39
Modify a column
• Example
– Change the how many column to an integer
• Code
alter table #summary
alter column how_many int;
SQL Server/Employees SQL302 Module 3 40
20
89. Add a column constraint
Example: modify the how many column
so there is a check constraint on
how_many
alter table #summary
add constraint check
(how_many >=0);
SQL Server/Employees SQL302 Module 3 43
Table Constraints
• Primary Key
• Foreign Key
• Compare fields against each other. I.e.
ship_date >= order_date
SQL Server/Employees SQL302 Module 3 44
22
90. Add a table constraint
Example: add a foreign key constraint
with cascade options
SQL Server/Employees SQL302 Module 3 45
Constraints on Summary Table
SQL Server/Employees SQL302 Module 3 46
23
91. Synonyms
• Can create another name for an object
– Used to provide a shorthand way to refer a
long, fully qualified table name
– Used where we want scripts to use an old
name as well as the newer name
• Syntax:
– Create <synonym> for <objectname>
SQL Server/Employees SQL302 Module 3 47
Synonyms
• Example:
– create a synonym for the orderlines table
• Code
create synonym orderlines for
order_lines;
SQL Server/Employees SQL302 Module 3 48
24
92. Views
• Think of a view as a named query wherein
the definition is stored in the database
• Can be read like a table
• Some are updateable
SQL Server/Employees SQL302 Module 3 49
Views
Basic syntax:
Create view <view-name> (<column-list>)
As
<select statement>
Column list can be used to name the output columns
instead of using the names in the select list
SQL Server/Employees SQL302 Module 3 50
25
93. Creating a View
SQL Server/Employees SQL302 Module 3 51
Using Views
• Can be used like a table subject to various
limitations
– Cannot insert into grouped queries, etc.
– Etc.
• Sample select from syntax:
select column-list
from employee_view
SQL Server/Employees SQL302 Module 3 52
26
94. Inserting into a view
• Must insert into all required columns in
underlying table
• Sample code:
SQL Server/Employees SQL302 Module 3 53
Using a View
SQL Server/Employees SQL302 Module 3 54
27
96. Orange Coast Database Associates Course Material (800)355-9855 or http://www.dhdursoassociates.com
Accelerated Computer Training
Orange Coast
Database Associates
Specializing in Microsoft Office,
Access, SQL, and related technologies
Computer Training, Programming & Consulting
32422 Alipaz St., Suite A-15
San Juan Capistrano, CA
(800)355-9855 (Toll Free) | (949)489-1472 (Direct) | (949)485-6284 (Fax)
http://www.dhdursoassociates.com | sales@dhdursoassociates.com
Accelerated Computer Training for Working Professionals