• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
SQL302 Intermediate SQL Workshop 1
 

SQL302 Intermediate SQL Workshop 1

on

  • 502 views

SQL302 Intermediate SQL using Microsoft SQL Server. Includes cast, convert, case, and table expressions.

SQL302 Intermediate SQL using Microsoft SQL Server. Includes cast, convert, case, and table expressions.

Statistics

Views

Total Views
502
Views on SlideShare
502
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    SQL302 Intermediate SQL Workshop 1 SQL302 Intermediate SQL Workshop 1 Presentation Transcript

    • 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 ExpressionsBookstore 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
    • 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 OrderlinesBookstore2 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
    • 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.comBookstore 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 databasesBookstore SQL302 Module 1 6
    • 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 scriptingBookstore 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 OracleBookstore SQL302 Module 1 8
    • Relational Database Basics• Storage • Indexes• Databases • Views• Tables • Cursors• Rows • Application interfaces• ColumnsBookstore SQL302 Module 1 9
    • Relational Database TableBookstore SQL302 Module 1 10
    • Constraints• Database • Other Business Rule – Domain – Triggers – Uniqueness – Stored Procedures – Relationship Cardinality • 1 to 1 • 1 to NBookstore SQL302 Module 1 11
    • Relational Database with constraintsBookstore SQL302 Module 1 12
    • Database Management Systems Positioning Chart Cost VLDB Enterprise Workgroup Single user Spreadsheet # UsersBookstore SQL302 Module 1 13
    • System Architecture File Server Architecture Access MDB AccessBookstore SQL302 Module 1 14
    • System Architecture Client/Server Architecture Oracle SQL DB Visual Access Basic AppBookstore SQL302 Module 1 15
    • System Architecture Web Architecture Web Oracle Server DB SQL BrowserBookstore SQL302 Module 1 16
    • Approaching SQL• Relatively simple• Two main environments – Interactive (This course) – Embedded • Static (Compiled) • DynamicBookstore SQL302 Module 1 17
    • SQL StandardizationANSI standardization – First standard in 1986 – SQL 89 – SQL 92 – SQL 99• Various vendor extensions – Microsoft/Sybase: T-SQL – Oracle: PL/SQLBookstore SQL302 Module 1 18
    • SQL Conformance• Entry• Intermediate• Advanced• Most are at least entry levelBookstore 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 LanguageBookstore SQL302 Module 1 20
    • 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 administrationBookstore SQL302 Module 1 21
    • SQL DCL• Data Control Language (DDL) – Grant – Revoke – Deny – ConstraintsBookstore SQL302 Module 1 22
    • SQL DQL• Data Manipulation Language (DML) – SelectBookstore SQL302 Module 1 23
    • SQL DML• Data Manipulation Language (DML) – Insert – Update – DeleteBookstore SQL302 Module 1 24
    • SQL Statement Processing Parse Validate Optimize Access Plan ExecuteBookstore 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
    • 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’ OracleBookstore SQL302 Module 1 28
    • 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 statementBookstore SQL302 Module 1 30
    • On Your Own• Find books written by Mark Twain• Show title, publisher, yearBookstore 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
    • Select with Complex WhereBookstore SQL302 Module 1 33
    • Complex Where ResultBookstore SQL302 Module 1 34
    • 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 NULLBookstore 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
    • 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 1Bookstore 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 mBookstore SQL302 Module 1 38
    • Case• Used to return a choice from two or more alternatives• Two forms – Searched case – Unsearched caseBookstore 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> EndBookstore SQL302 Module 1 40
    • Unsearched (Simple Case)• Example: expand the order filled status columns in the orders tableBookstore 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> EndBookstore SQL302 Module 1 42
    • Searched CASE• Example: list names of referring customers, self in no referrerBookstore 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
    • CAST• Example: combine author name and publication year into one columnBookstore SQL302 Module 1 45
    • CAST resultsBookstore SQL302 Module 1 46
    • 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 columnBookstore SQL302 Module 1 48
    • Convert resultsBookstore 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 rowBookstore SQL302 Module 2 50
    • Uncorrelated Subquery• In list (covered in sql202 basic class)• Single valuedBookstore 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
    • 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 clauseBookstore 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
    • 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 integrityBookstore 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
    • Derived Tables• Sort of a named subquery• Allows you to access columns inside the subquery from the containing outer query• Syntax <select statement> as derivedtablenameBookstore 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
    • 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’sBookstore SQL302 Module 2 60
    • Technique 1 – w/out CTEselect isbn, cost_each, (select AVG(cost_each)from orderlines)from orderlineswhere cost_each > (select AVG(cost_each) from orderlines)order by isbn;Bookstore SQL302 Module 2 61
    • Technique 2 – using a CTEwith average_cost_cte(average_cost)as(select AVG(cost_each)from orderlines)select isbn, cost_each, average_costfrom orderlines, average_cost_ctewhere cost_each > average_costorder by isbn;Bookstore SQL302 Module 2 62
    • 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
    • NotesBookstore SQL302 Module 1 64