96
Accelerated Computer Training for Working Professionals Bookstore Case Orange Coast Database Associates Course PowerPoint Slides (800)355-9855 or http://www.dhdursoassociates.com Orange Coast Database Associates Specializing in Microsoft Office, Access, SQL, and related technologies Classes custom designed forWorking Professionals http://www.dhdursoassociates.com San Juan Capistrano, CA (800)355-9855 SQL302 Intermediate SQL Using Microsoft SQL Server

SQL302 Intermediate SQL

Embed Size (px)

DESCRIPTION

SQL302 Intermediate SQL using Microsoft SQL Server. Covers additional uses of subqueries, set functions, table expressions, with clause, new SQL window functions.

Citation preview

Page 1: SQL302 Intermediate SQL

Accelerated Computer Training for Working Professionals Bookstore Case

Orange Coast Database Associates Course PowerPoint Slides (800)355-9855 or http://www.dhdursoassociates.com

Orange CoastDatabase Associates

Specializing in Microsoft Office,

Access, SQL, and related technologiesClasses custom designed forWorking Professionals

http://www.dhdursoassociates.com

San Juan Capistrano, CA

(800)355-9855

SQL302 Intermediate SQL UsingMicrosoft SQL Server

Page 2: SQL302 Intermediate SQL

1

Bookstore SQL302 1

An accelerated course in intermediate SQL forexperienced SQL users.

P.O. Box 6142Laguna Niguel, CA 92607949-489-1472http://www.d2associates.com

Welcome to SQL302 –

Intermediate SQLUsing MS SQL Server

Bookstore SQL302 2

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

Page 3: SQL302 Intermediate SQL

2

Bookstore2 SQL302 Module 2 3

SQL302 Contact Information

P.O. Box 6142Laguna Niguel, CA 92607949-489-1472http://[email protected]

Copyright 2001-2012. All rights reserved.

SQL302 Resources

• Bookstore database scripts found onbox.com at

http://tinyurl.com/SQLScripts

• Slides can be viewed on SlideShare…

http://www.slideshare.net/OCDatabases

• Follow up questions?

[email protected]

Bookstore SQL302 Module 1 4

Page 4: SQL302 Intermediate SQL

3

About Us 5

Bookstore SQL302 6

Intermediate SQL Curriculum

SQL3xxS*

SQL312Oracle**

SQL302Transact-SQL

SQL322WMySQL**

•*= first day only•**=underdevelopment

Page 5: SQL302 Intermediate SQL

4

Bookstore SQL302 7

Intermediate SQL

• Assumes prior knowledge of SQLequivalent 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 8

Intermediate SQL

• Select– More filters & operators– Case, cast, convert– Subqueries– Table expressions– Joins– Set operations– Window functions

SQL Covered (Day 1: All Day):

Page 6: SQL302 Intermediate SQL

5

Bookstore SQL302 9

Intermediate SQL

• Data Updates– Select into– Update from, using subqueries– Delete from

• Data structures– Alter– Synonyms– Views

SQL Covered (Day 2: AM Only):

Bookstore SQL302 10

Intermediate SQL

• 3 Sessions

• Lecture

• Demo

• Student “hands-on”

• Many exercises are cumulative –later examples build on queriescreated earlier

Course Format:

Page 7: SQL302 Intermediate SQL

6

Bookstore SQL302 11

Intermediate SQL

• Session 1 – IntermediateSQL

• Session 2 – Multi-tableRetrieval

• Session 3 – Modifying dataand data structures

Course Schedule (“1/2” day sessions):

Notes

Bookstore SQL302 12

Page 8: SQL302 Intermediate SQL

1

Bookstore SQL302 Module 1 1

SQL302

Intermediate SQL ProgrammingBased 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

Note on SQL302 Slides

• Many of these slides were originally designed tosupport a single SQL course which was used for anyof MS Access, MySQL, Oracle and SQL Server.

• As such you may see here slides developed in anyone of the above products.

• We are in the process of migrating the vendorspecific slides out into their own slide sets.

Bookstore2 SQL302 Module 2 2

Page 9: SQL302 Intermediate SQL

2

Bookstore2 SQL302 Module 2 3

Warning!

• Below are some table name changes to beaware of in doing queries. We have createdsynonyms so either name should work.

New Name Old Name

Orders Order_filled

Order_Lines Orderlines

Bookstore2 SQL302 Module 2 4

SQL302 Contact Information

P.O. Box 6142Laguna Niguel, CA 92607949-489-1472http://[email protected]

Copyright 2001-2012. All rights reserved.

Page 10: SQL302 Intermediate SQL

3

SQL302 Resources

• Bookstore database scripts found onbox.com at

http://tinyurl.com/SQLScripts

• Slides can be viewed on SlideShare…

http://www.slideshare.net/OCDatabases

• Follow up questions?

[email protected]

Bookstore SQL302 Module 1 5

Bookstore SQL302 Module 1 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 andalmost all major business applications thatuse relational databases

Page 11: SQL302 Intermediate SQL

4

Bookstore SQL302 Module 1 7

SQL302

• Students should have taken SQL202 orhave equivalent experience. It is assumedstudents know basic SQL.

• We will use the Management Studio in thisclass, but the focus will be on SQLscripting

Bookstore SQL302 Module 1 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 byOracle

Page 12: SQL302 Intermediate SQL

5

Bookstore SQL302 Module 1 9

Relational Database Basics

• Storage

• Databases

• Tables

• Rows

• Columns

• Indexes

• Views

• Cursors

• Application interfaces

Bookstore SQL302 Module 1 10

Relational Database Table

Page 13: SQL302 Intermediate SQL

6

Bookstore SQL302 Module 1 11

Constraints

• Database

– Domain

– Uniqueness

– RelationshipCardinality

• 1 to 1

• 1 to N

• Other Business Rule

– Triggers

– Stored Procedures

Bookstore SQL302 Module 1 12

Relational Database with constraints

Page 14: SQL302 Intermediate SQL

7

Bookstore SQL302 Module 1 13

Database Management Systems

Positioning Chart

VLDB

Enterprise

Workgroup

Single user

Spreadsheet

# Users

Cost

Bookstore SQL302 Module 1 14

System Architecture

AccessMDB

File ServerArchitecture

Access

Page 15: SQL302 Intermediate SQL

8

Bookstore SQL302 Module 1 15

System Architecture

OracleDB

VisualBasic App

Client/ServerArchitecture

Access

SQL

Bookstore SQL302 Module 1 16

System Architecture

OracleDB

Browser

WebArchitecture

WebServer

SQL

Page 16: SQL302 Intermediate SQL

9

Bookstore SQL302 Module 1 17

Approaching SQL

• Relatively simple

• Two main environments

– Interactive (This course)

– Embedded

• Static (Compiled)

• Dynamic

Bookstore SQL302 Module 1 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

Page 17: SQL302 Intermediate SQL

10

Bookstore SQL302 Module 1 19

SQL Conformance

• Entry

• Intermediate

• Advanced

• Most are at least entry level

Bookstore SQL302 Module 1 20

SQL Statements

• Data Manipulation Language (DML)

• Data Control Language (DCL)

• Data Definition Language (DDL)

• Note: SQL 99 changes these to seven typesincluding DQL Data Query Language

Page 18: SQL302 Intermediate SQL

11

Bookstore SQL302 Module 1 21

SQL DDL

• Data definition language (DDL)

– Create, alter, drop, etc.

– Frequently implemented via various CASEtools: Visio, Embarcadero, ERWin, etc.

– But very useful for database administration

Bookstore SQL302 Module 1 22

SQL DCL

• Data Control Language (DDL)

– Grant

– Revoke

– Deny

– Constraints

Page 19: SQL302 Intermediate SQL

12

Bookstore SQL302 Module 1 23

SQL DQL

• Data Manipulation Language (DML)

– Select

Bookstore SQL302 Module 1 24

SQL DML

• Data Manipulation Language (DML)

– Insert

– Update

– Delete

Page 20: SQL302 Intermediate SQL

13

Bookstore SQL302 Module 1 25

SQL Statement Processing

Parse

Validate

Optimize

Access Plan

Execute

Bookstore SQL302 Module 1 26

Sample Database(s)

• Before we continue (note: instructor may havealready 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).

Page 21: SQL302 Intermediate SQL

14

Bookstore SQL302 Module 1 27

Text Conventions

• In Access character strings are normallysurrounded by double quotes

– “Jones”

• In an enterprise database such as Oracle orSQL Sever enclose text strings in singlequotes

– ‘Jones’

Bookstore SQL302 Module 1 28

Date Conventions

• In an enterprise database such as Oracle orSQL Sever, enclose dates in single quotes

– ‘2004-12-23’ MySQL

– ’12-23-2004’ SQL Server

– ’23-DEC-04’ Oracle

Page 22: SQL302 Intermediate SQL

15

Select statement clauses

SELECT…

INTO…

FROM…

WHERE…

GROUP BY…

HAVING…

ORDER BY…

Bookstore SQL302 Module 1 29

Bookstore SQL302 Module 1 30

SELECT

See SQL202 for syntax andsemantics of basic SELECTstatement

Page 23: SQL302 Intermediate SQL

16

Bookstore SQL302 Module 1 31

On Your Own

• Find books written by Mark Twain

• Show title, publisher, year

Bookstore SQL302 Module 1 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’

Page 24: SQL302 Intermediate SQL

17

Bookstore SQL302 Module 1 33

Select with Complex Where

Bookstore SQL302 Module 1 34

Complex Where Result

Page 25: SQL302 Intermediate SQL

18

Bookstore SQL302 Module 1 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 36

Like Extensions

• ANSI wildcards

• Wherecustomer_last_namelike ‘[JK]o%’

like ‘[J-M]%’

like [^abc]%

Page 26: SQL302 Intermediate SQL

19

Any, some, All

• Any, some

• Modifies comparisonoperator

• Ex: expr > any (1,2,3)means expr wouldhave to be greaterthan the minimumwhich is 1

• All

• Modifies comparisonoperator

• Ex: expr > all(1,2,3)would have to begreater than 3

Bookstore SQL302 Module 1 37

Bookstore SQL302 Module 1 38

On Your Own

• Find all customers with a last name that startswith a through m

• Find all customers that live in a state that doesnot start with m

Page 27: SQL302 Intermediate SQL

20

Case

• Used to return a choice from two or morealternatives

• Two forms

– Searched case

– Unsearched case

Bookstore SQL302 Module 1 39

Unsearched (Simple) CASE

• This form of case has a selector whichtakes on a value used to select analternative

• Syntax:Select case <selector>

When <value1> then <expr1>,

When <value2> then <expr2>,

Else

<statement>

EndBookstore SQL302 Module 1 40

Page 28: SQL302 Intermediate SQL

21

Unsearched (Simple Case)

• Example: expand the order filled statuscolumns in the orders table

Bookstore SQL302 Module 1 41

Searched CASE

• This form of the Case statement does nothave a selector

• Syntax:Select case

When <condition1> then <expr1>,

When <condition2> then <expr2>,

Else

<statement>

End

Bookstore SQL302 Module 1 42

Page 29: SQL302 Intermediate SQL

22

Searched CASE

• Example: list names of referringcustomers, self in no referrer

Bookstore SQL302 Module 1 43

CAST

• Function to cast a column to a differentdata type; same idea as cast in cprogramming

• Syntax:

CAST ( expression AS data_type [ ( length ) ] )

Bookstore SQL302 Module 1 44

Page 30: SQL302 Intermediate SQL

23

CAST

• Example: combine author name andpublication year into one column

Bookstore SQL302 Module 1 45

CAST results

Bookstore SQL302 Module 1 46

Page 31: SQL302 Intermediate SQL

24

Convert

• Function to convert from one data type toanother; mostly replaced by cast

• Syntax

CONVERT ( data_type [ ( length ) ] , expression[ , style ] )

Bookstore SQL302 Module 1 47

Convert

• Example:

– Remove time from display of a datetimecolumn

Bookstore SQL302 Module 1 48

Page 32: SQL302 Intermediate SQL

25

Convert results

Bookstore SQL302 Module 1 49

Bookstore SQL302 Module 2 50

Subqueries

• One select statement embedded in another

• Can be nested multiple levels deep

• Can be used in select, from and whereclauses

• Two types:– Uncorrelated – executes inner query then outer

– Correlated – executes inner query once foreach outer query row

Page 33: SQL302 Intermediate SQL

26

Uncorrelated Subquery

• In list (covered in sql202 basic class)

• Single valued

Bookstore SQL302 Module 2 51

Bookstore SQL302 Module 2 52

Uncorrelated Subquery

select isbn, quantity

from orderlines

where order_numb in

(select order_numb fromorders where order_datebetween ‘1/1/99’ and‘12/31/99’);

Page 34: SQL302 Intermediate SQL

27

Single-valued Subquery

• Subqueries can be used where anexpression returns a scalar or single value

– calculations

– comparisons

• Can be used in select list, from clause andwhere clause

Bookstore SQL302 Module 2 53

Single-valued Subquery

• Example

– Show all orderlines with an order total greaterthan the average for all orderlines

• Codeuse 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

Page 35: SQL302 Intermediate SQL

28

Bookstore SQL302 Module 2 55

Correlated Subquery with Exists

• Inner subquery executed once for each outer row

• Exists will return true or false depending onwhether the result will have any rows or not

• Can be a quick way to test for existence ofrecords (parent records, say) as used inapplication enforcement of referential integrity

Bookstore SQL302 Module 2 56

Correlated subquery with Exists

SELECT isbn, quantity

FROM orderlines AS ol

WHERE exists

(select * from orders o whereol.order_numb = o.order_numb

and o.order_date between ‘1/1/99’and ‘12/31/99’);

Page 36: SQL302 Intermediate SQL

29

Derived Tables

• Sort of a named subquery

• Allows you to access columns inside thesubquery from the containing outer query

• Syntax

<select statement> as derivedtablename

Bookstore SQL302 Module 2 57

Derived Tables

• Example: List the number of orders peryear

• Codeuse 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

Page 37: SQL302 Intermediate SQL

30

Common Table Expressions

• Can be used to define a subquery that canbe reused within an SQL statement

• SyntaxWith 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 morethan the average. Demonstrate twotechniques:

– Technique 1 - Using subqueries w/out a CTE

– Technique 2 - With CTE’s

Bookstore SQL302 Module 2 60

Page 38: SQL302 Intermediate SQL

31

Technique 1 – w/out CTE

select isbn, cost_each, (selectAVG(cost_each)from orderlines)

from orderlines

where cost_each > (select AVG(cost_each) fromorderlines)

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

Page 39: SQL302 Intermediate SQL

32

Bookstore SQL302 Module 1 63

SQL Exercises

• List all customers whose last name does notend with s or t.

• Find all customers who have not placed anorder.

• Find all order lines with an amount less thanthe average. Include the order date without thetime.

• List all books with a price greater than theaverage price for all books. Show the variancefrom the average, too. Use a CTE.

[end module]

Notes

Bookstore SQL302 Module 1 64

Page 40: SQL302 Intermediate SQL

1

Bookstore SQL302 Module 2 1

SQL302

Intermediate SQL Programming

Workshop 2 – Joins, Set Operations, WindowFunctions

Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T-SQL Fundamentals by Itzki Ben-gan

Note on SQL302 Slides

• These slides were originally designed to support asingle SQL course which was used for any of MSAccess, MySQL, Oracle and SQL Server.

• As such you may see here slides developed in anyone of the above products.

• We are in the process of migrating the Oracle,Access, and MySQL slides out into their own slidesets. The SQL302 slides will cover Microsoft SQLServer.

Bookstore SQL302 Module 2 2

Page 41: SQL302 Intermediate SQL

2

Bookstore SQL302 Module 2 3

Warning!

• Below are some table name changes to beaware of in doing queries. We have createdsynonyms so either name should work.

New Name Old Name

Orders Order_filled

Order_Lines Orderlines

Bookstore SQL302 Module 2 4

SQL302 Contact Information

P.O. Box 6142Laguna Niguel, CA 92607949-489-1472http://[email protected]

Copyright 2001-2012All rights reserved.

Page 42: SQL302 Intermediate SQL

3

SQL302 Resources

• Bookstore database scripts found onbox.net at

http://tinyurl.com/SQLScripts

• Slides can be viewed on SlideShare…

http://www.slideshare.net/OCDatabases

• Follow up questions?

[email protected]

Bookstore SQL302 Module 2 5

Bookstore SQL302 Module 2 6

Relational Database with constraints (from text)

Page 43: SQL302 Intermediate SQL

4

Bookstore2 &Employees

SQL204 Module 1 7

Sample Employees Database

Bookstore SQL302 Module 2 8

More conventions

• Names can be surrounded with “ “ or [ ] asin [order details].

• Some of the PowerPoint slides may havethis convention.

• Better practice is to use an underscore as inorder_details.

Page 44: SQL302 Intermediate SQL

5

Bookstore SQL302 Module 2 9

SQL302

SQL Programming

Part 1 – Joins: Natural, Self and Outer

Bookstore SQL302 Module 2 10

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 subtleaspects of joins in this class

Page 45: SQL302 Intermediate SQL

6

Bookstore SQL302 Module 2 11

Natural Joins

• Table1 natural join table3 – automaticallyuses columns with same name

• Table 1 natural join table2 using(<column-list>

• Not yet available in SQL Server

Bookstore SQL302 Module 2 12

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;

Page 46: SQL302 Intermediate SQL

7

Bookstore SQL302 Module 2 13

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 14

Self Joins

SELECT e.*, m.name

FROM employees AS e, employeesAS m

WHERE e.managerid =m.employeeid;

Page 47: SQL302 Intermediate SQL

8

Bookstore SQL302 Module 2 15

Datawarehouse clauses

• Two keywords that can be added to agrouped query

– Rollup

– Cube

• Places additional summary rows in theresult set

• Result set is a true relational result set

Bookstore SQL302 Module 2 16

Page 48: SQL302 Intermediate SQL

9

Rollup

• Example: calculate average salaries byjob_title_code and manager

Bookstore SQL302 Module 2 17

Rollup results

Bookstore SQL302 Module 2 18

Page 49: SQL302 Intermediate SQL

10

cube

• Similar to rollup but computes summaryrows 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

Page 50: SQL302 Intermediate SQL

11

Bookstore SQL302 Module 2 21

Bookstore SQL302 Module 2 22

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

Page 51: SQL302 Intermediate SQL

12

Bookstore SQL302 Module 2 23

Left Outer Join

Basic SQL 92 Syntax:

Select <column-list>

From <table1>

Left join <table2>

On <join condition>

Left Outer Join

• List all customers with their orders

• Include customers with no orders as well

Bookstore SQL302 Module 2 24

Page 52: SQL302 Intermediate SQL

13

Bookstore SQL302 Module 2 25

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 26

Left Join with Results

Page 53: SQL302 Intermediate SQL

14

Negative Left Join

• List all the customers who have not placedany orders

• This is an example of a query which findsunmatched records

Bookstore SQL302 Module 2 27

Bookstore SQL302 Module 2 28

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;

Page 54: SQL302 Intermediate SQL

15

Bookstore SQL302 Module 2 29

Left Join w/ Partial Match

• List all customers along with any ordersplaced in 1999

• If they did not place 1999 orders we stillwant to include them in the printout

Bookstore SQL302 Module 2 30

Page 55: SQL302 Intermediate SQL

16

Left Join w/ Partial Match

Bookstore SQL302 Module 2 31

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;

Own Your Own

• List all books and their order totals for1999

• Show the book even if there were no ordersplaced in 1999

Bookstore SQL302 Module 2 32

Page 56: SQL302 Intermediate SQL

17

Theta Joins

• Theta joins involve inequalities in thematching conditions

• Can be used for some interesting querieswhich do not involve the usual primary keyto 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 addressfield

Bookstore SQL302 Module 2 34

Page 57: SQL302 Intermediate SQL

18

Theta join results

• Can be further processed with a union query toconsolidate names into a single list

Bookstore SQL302 Module 2 35

Bookstore SQL302 Module 2 36

SQL302

SQL Programming

Part 3– Set Operations

Page 58: SQL302 Intermediate SQL

19

Set Operations

• More on unions

• Intersect

• Except

Bookstore SQL302 Module 2 37

Bookstore SQL302 Module 2 38

Unions

• Combines two or more tables

• Tables must be union compatible

Page 59: SQL302 Intermediate SQL

20

Bookstore SQL302 Module 2 39

Unions

Select <column-list> from<table1>

Union [ALL]

Select <same-columns> from<table2>

Unions

• Example: consolidate two columns into onecolumn

Bookstore SQL302 Module 2 40

Page 60: SQL302 Intermediate SQL

21

Union consolidation result

• Customers in same city

Bookstore SQL302 Module 2 41

Unions

• Example: add a total row to a query result

• Code:

Bookstore SQL302 Module 2 42

use bookstore;select order_numb

, sum(quantity) as "Quantity", sum(cost_line)as "Total Cost"

from orderlinesgroup by order_numbunionselect NULL, sum(quantity),sum(cost_line)from orderlines;

Page 61: SQL302 Intermediate SQL

22

unions

• Example: add an element to a pick list

Bookstore SQL302 Module 2 43

intersect

• The intersect operator finds rows incommon between two tables

• Syntax

Select <column-list> from <table1>

intersect

Select <same-columns> from <table2>

Bookstore SQL302 Module 2 44

Page 62: SQL302 Intermediate SQL

23

intersect

• Example: find cities in common betweensources and customers

• Codeselect customer_city, customer_state,customer_zip

from customers

intersect

select source_city, source_state,source_zip

from sources;Bookstore SQL302 Module 2 45

Except

• Finds all rows from first table that are notfound in the second table

• Syntax:

Select <column-list> from <table1>

except

Select <same-columns> from <table2>

Bookstore SQL302 Module 2 46

Page 63: SQL302 Intermediate SQL

24

except

• Example: find sources that are not locatedin any of our customer’s cities

• Codeselect source_city, source_state,source_zip

from sources

except

select customer_city, customer_state,customer_zip

from customers;Bookstore SQL302 Module 2 47

Bookstore SQL302 Module 2 48

SQL302

SQL Programming

Part 4 – Window Functions

Page 64: SQL302 Intermediate SQL

25

Bookstore SQL302 Module 2 49

Aggregate Functions

• Count

• Sum

• Min

• Max

• Avg

• Often used in conjunction with groupingand window functions

Window Functions

• Sort of like grouping, but aggregates canbe taken along with straight columns in theselect list

• The function is applied over a window

– Partition by column

– Partition by ()

Bookstore SQL302 Module 2 50

Page 65: SQL302 Intermediate SQL

26

Bookstore SQL302 Module 2 51

Window Functions

Basic syntax:

Select …, aggregate function(<column>)over (partition by <column>)

From <table>where <predicate>

Bookstore SQL302 Module 2 52

Window Functions

Example: Show salary along with average for thejob_title and overall

Code:use employeedb;select soc_sec_no, name, salary

, SUM(salary) over(partitionby job_title_code) as [Job CodeAverage]

, SUM(salary) over() as[Average]from employees;

Page 66: SQL302 Intermediate SQL

27

Bookstore SQL302 Module 2 53

Exercise

• List all customers and their orders

– Name nicely formatted

– With orders in the year of 1999 (do not usebetween, etc.)

– Show total order quantities and amounts

– Only include orders with more than threeorder lines

Notes

Bookstore SQL302 Module 2 54

Page 67: SQL302 Intermediate SQL

28

Notes

Bookstore SQL302 Module 2 55

Notes

Bookstore SQL302 Module 2 56

Page 68: SQL302 Intermediate SQL

1

SQL Server/Employees SQL302 Module 3 1

SQL302

Intermediate SQL Programming

Workshop 3 – Modifying Data, Managing theDatabase

Based on SQL Clearly Explained by Jan Harrington and Microsoft SQL Server T-SQL Fundamentals by Itzki Ben-gan

Note on SQL302 Slides

SQL Server/Employees SQL302 Module 3 2

• These slides were originally designed to support thesingle SQL302 course which was used for any ofMS Access, Oracle and SQL Server.

• As such you may see here slides developed in anyone of the above products.

• We are in the process of migrating the OracleMySQL, and MS Access slides out into their ownslide sets. These SQL302 slides will focus onMicrosoft SQL Server.

Page 69: SQL302 Intermediate SQL

2

SQL Server/Employees SQL302 Module 3 3

Warning!

• Below are some table name changes to beaware of in doing queries. We have createdsynonyms so either name should work.

New Name Old Name

Orders Order_filled

Order_Lines Orderlines

SQL Server/Employees SQL302 Module 3 4

SQL302 Contact Information

P.O. Box 6142Laguna Niguel, CA 92607949-489-1472http://[email protected]

Copyright 2001-2011. All rights reserved.

Page 70: SQL302 Intermediate SQL

3

SQL302 Resources

• Bookstore database scripts found onbox.net at

http://tinyurl.com/SQLScripts

• Slides can be viewed on SlideShare…

http://www.slideshare.net/OCDatabases

• Follow up questions?

[email protected]

SQL Server/Employees SQL302 Module 3 5

SQL Server/Employees SQL302 Module 3 6

SQL302 Module 3

• Part 1 – Modifying Data

• Part 2 – Managing Database Structures

Page 71: SQL302 Intermediate SQL

4

SQL Server/Employees SQL302 Module 3 7

SQL302

SQL Programming

Part 1 – Modifying Data

SQL Server/Employees SQL302 Module 3 8

Relational Database with constraints (from text)

Page 72: SQL302 Intermediate SQL

5

Bookstore2 &Employees

SQL204 Module 1 9

Sample Employees Database

SQL Server/Employees POS/410 Workshop 3 10

Transactions

• Statements can be groupedinto transactions

• All must succeed

• If so they are allcommitted

• If not they are all rolledback

• Helps guarantee data isconsistent

Page 73: SQL302 Intermediate SQL

6

SQL Server/Employees POS/410 Workshop 3 11

SQL Server Transactions Syntax

begin transactionStatements

if @@error = 0Commit transaction

elseRollback error

SQL Server/Employees SQL302 Module 3 12

Data Modification Statements

• End-user rarely sees thesestatements

• Application developer preparesthese statements “behind thescenes” based on forms or webpages filled out by user

Page 74: SQL302 Intermediate SQL

7

SQL Server/Employees SQL302 Module 3 13

Data Modification Statements

• This course (SQL302)

– Select Into

– Table Valued Constructors (TVCs)

– Update

– Delete

• Basic DML already covered inSQL202

Select into

• Select….into will copy a table

• Uses a regular SQL statement with intoclause before the from not after

• Syntax:Select <select list>

Into <tablename>

From <tablename>

SQL Server/Employees SQL302 Module 3 14

Page 75: SQL302 Intermediate SQL

8

Select into

• Example:

– Copy a subset of the employees table to atemporary working table

• Code:

SQL Server/Employees SQL302 Module 3 15

Insert with TVC

• Newer form of insert statement longavailable in MySQL

• Can shorten your code

• Each element in the insert list can actuallybe an expression but we will use literals inthis class

SQL Server/Employees SQL302 Module 3 16

Page 76: SQL302 Intermediate SQL

9

Insert with TVC

SQL Server/Employees SQL302 Module 3 17

SQL Server/Employees SQL302 Module 3 18

Update and Delete

• Updates and deletes can usesubqueries

• SQL Server allows update anddelete statements to be based onjoins, too

• We will review this in the next fewslides.

Page 77: SQL302 Intermediate SQL

10

Update

• You can use subqueries in an update.

– In where predicate

– To set the field value

SQL Server/Employees SQL302 Module 3 19

UPDATE tableSET columnname = value from subquery[WHERE condition with subquery]

• Example: Increase range minimums for unusedjob codes

SQL Server/Employees SQL302 Module 3 20

UPDATE w/ Subquery in where

Page 78: SQL302 Intermediate SQL

11

SQL Server/Employees SQL302 Module 3 21

UPDATE Results

SQL Server/Employees SQL302 Module 3 22

UPDATE FROM Statement

UPDATE tableSET columnname = value…[FROM tablelist][WHERE condition]

SQL Server allows updates from a table, including joinedtables. As an example one could update quantity on handin an inventory table from a transaction table.

Page 79: SQL302 Intermediate SQL

12

Update from

• Example: increase managerial salaries

SQL Server/Employees SQL302 Module 3 23

SQL Server/Employees SQL302 Module 3 24

UPDATE From Results

Page 80: SQL302 Intermediate SQL

13

Update w/ subquery in set clause

• Update employee temp table – set salaries to theaverage for that code

SQL Server/Employees SQL302 Module 3 25

SQL Server/Employees SQL302 Module 3 26

DELETE FROM Statement

DELETE [from] tableFROM tablelist[WHERE condition]

SQL Server allows deletes from a table based on asubquery or a join condition.

Basic syntax:

Page 81: SQL302 Intermediate SQL

14

Delete from

• Example: Delete unused job titles

SQL Server/Employees SQL302 Module 3 27

SQL Server/Employees SQL302 Module 3 28

DELETE FROM Results

Page 82: SQL302 Intermediate SQL

15

SQL Server/Employees SQL302 Module 3 29

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 whencreating or modifying table structures which wewill look at later in the class

SQL Server/Employees SQL302 Module 3 30

SQL302

SQL Programming

Part 2– Managing Database Structures

Page 83: SQL302 Intermediate SQL

16

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 thealter command to

– Add columns

– Modify columns

– Add constraints

SQL Server/Employees SQL302 Module 3 32

Page 84: SQL302 Intermediate SQL

17

SQL Server/Employees SQL302 Module 3 33

Creating Tables

• Use create statement

• Specify:

– Columns with data types and columnconstraints

– Table constraints

• Foreign key references

• Primary key designation

SQL Server/Employees SQL302 Module 3 34

Create Table

Basic syntax:

Create table <table-name>

(

<column1> <datatype> <constraints>

,.. <column1> <datatype> <constraints>

<table constraints>

);

Page 85: SQL302 Intermediate SQL

18

SQL Server/Employees SQL302 Module 3 35

Create Table

Example 1: SQL202 Create summary table(we will do this step by step using the alterstatement 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 36

Create Table

Example 2: Create summary table

Create table #summary(

isbn varchar(20) primary key);

Page 86: SQL302 Intermediate SQL

19

SQL Server/Employees SQL302 Module 3 37

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 38

Modifying a Table Design

Basic syntax:

Alter <table-name>

Add <field-name>,

Add <table-constraint>,

Alter <field-name>

Etc.

Page 87: SQL302 Intermediate SQL

20

SQL Server/Employees SQL302 Module 3 39

Add a column

Example: add a column to hold howmany times a book has been sold

alter table #summary

Add how_many numeric(5,2);

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

Page 88: SQL302 Intermediate SQL

21

New column results

SQL Server/Employees SQL302 Module 3 41

SQL Server/Employees SQL302 Module 3 42

Column Constraints

• Primary key

• Not NULL

• CHECK clause

• Default

• Unique

Page 89: SQL302 Intermediate SQL

22

SQL Server/Employees SQL302 Module 3 43

Add a column constraint

Example: modify the how many columnso there is a check constraint onhow_many

alter table #summary

add constraint check(how_many >=0);

SQL Server/Employees SQL302 Module 3 44

Table Constraints

• Primary Key

• Foreign Key

• Compare fields against each other. I.e.ship_date >= order_date

Page 90: SQL302 Intermediate SQL

23

SQL Server/Employees SQL302 Module 3 45

Add a table constraint

Example: add a foreign key constraintwith cascade options

SQL Server/Employees SQL302 Module 3 46

Constraints on Summary Table

Page 91: SQL302 Intermediate SQL

24

Synonyms

• Can create another name for an object

– Used to provide a shorthand way to refer along, fully qualified table name

– Used where we want scripts to use an oldname 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 fororder_lines;

SQL Server/Employees SQL302 Module 3 48

Page 92: SQL302 Intermediate SQL

25

SQL Server/Employees SQL302 Module 3 49

Views

• Think of a view as a named query whereinthe definition is stored in the database

• Can be read like a table

• Some are updateable

SQL Server/Employees SQL302 Module 3 50

Views

Basic syntax:

Create view <view-name> (<column-list>)

As

<select statement>

Column list can be used to name the output columnsinstead of using the names in the select list

Page 93: SQL302 Intermediate SQL

26

SQL Server/Employees SQL302 Module 3 51

Creating a View

SQL Server/Employees SQL302 Module 3 52

Using Views

• Can be used like a table subject to variouslimitations

– Cannot insert into grouped queries, etc.

– Etc.

• Sample select from syntax:

select column-list

from employee_view

Page 94: SQL302 Intermediate SQL

27

Inserting into a view

• Must insert into all required columns inunderlying table

• Sample code:

SQL Server/Employees SQL302 Module 3 53

SQL Server/Employees SQL302 Module 3 54

Using a View

Page 95: SQL302 Intermediate SQL

28

SQL302

SQL Server/Employees SQL302 Module 3 55

[end of course]

Notes

SQL Server/Employees SQL302 Module 3 56

Page 96: SQL302 Intermediate SQL

Accelerated Computer Training for Working Professionals

Orange Coast Database Associates Course Material (800)355-9855 or http://www.dhdursoassociates.com

Orange CoastDatabase Associates

Specializing in Microsoft Office,

Access, SQL, and related technologiesComputer 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 | [email protected]

Accelerated Computer Training