• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
SQL200.2 Module 2

SQL200.2 Module 2



Workshop 2 – Joins, Subqueries, Unions, Calculations and Grouping

Workshop 2 – Joins, Subqueries, Unions, Calculations and Grouping



Total Views
Views on SlideShare
Embed Views



1 Embed 2

http://www.slideshare.net 2



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.

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

    SQL200.2 Module 2 SQL200.2 Module 2 Presentation Transcript

    • SQL200 SQL Programming Workshop 2 – Joins, Subqueries, Unions, Calculations and Grouping
    • SQL200 Contact Information P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com [email_address] Copyright 2001-2009. All rights reserved.
    • SQL200 SQL Programming Part 1 – Joins, Subqueries
    • Relational Database with constraints (from text)
    • More conventions
      • Names can be surrounded with [] as in [order details]. Better practice is to use an underscore as in order_details.
      • MS Access often adds the brackets. Some of the PowerPoint slides have this convention, but it works equally as well in SQL Server.
    • Warning!
      • Some slides may show queries using a table called…
        • Order_filled
      • The current database uses a better name…
        • Orders
        • Construct your queries with this latter table name
    • Joins
      • Inner
      • Outer
        • Left
        • Right
        • Full
      • Cross
      • Self
      • Theta
      • We will cover the most important; others as time and interest permit
    • Inner Join
      • Pairs each row from first table with corresponding row from second table over the “join column”
      • The result set only contains rows where there is a match over the join column in both tables
      • Equi-join is the common inner join
    • Inner Join Older Syntax: Select <column-list> From <tablelist> Where <predicate> Still very commonly used
    • Inner Join Example using older syntax: SELECT customer_first_name, customer_street, order_numb, order_date from customers, orders Where customers.customer_numb = orders.customer_numb
    • Inner Join with Result
    • Inner Join (New Syntax) Basic SQL 92 Syntax: Select <column-list> From <table1> Inner join <table2> On <join condition>
    • Inner Join Basic Example: SELECT customer_first_name, customer_street, order_numb, order_date from customers inner join orders on customers.customer_numb = orders.customer_numb
    • Inner Join with Result
    • Inner Join over Multiple columns
      • Note that that the join condition can apply to multiple columns if desired
      • Used with composite keys
    • Inner Join Result in MS Access
    • Inner Join
      • In the last example…
        • What was the cardinality of the relationship between customers and orders?
        • Which table was the parent?
        • What was it’s primary key?
        • In which table did we employ a foreign key and what was it?
    • Cross Join
      • What happens when you omit a join expression?
      • Get the cartesian product of the tables – all possible combinations of the two tables
      • For large tables this will run a long time!
    • Cross Join Result Set in MS Access
    • Additional SQL92 Syntax
      • Table1 natural join table3 – automatically uses columns with same name
      • Table 1 natural join table2 using(<column-list>
      • Not yet widely available in commercial implementations
    • Joining More than Two Tables
      • Can join several tables in one select
      • Try to limit to three or four
      • Join order can be important for performance (although optimizers will usually handle this for you)
      • Use parentheses to force order of evaluation (also vendor extensions, often called “hints”)
    • Joining More than Two Tables
      • Add orderlines detail to previous queries
      SELECT [customer_first_name], [customer_street], [orders.order_numb], [orders.order_date], orderlines.isbn, orderlines.quantity FROM ( customers INNER JOIN orders ON [customers].[customer_numb]=[orders].[customer_numb] ) INNER JOIN orderlines on orders.order_numb = orderlines.order_numb
    • Multi-table Join with Results
    • MS Access Multi-table Join Result Set
    • Sample Database
      • Before we continue (Access classes only)…
      • Create a new employees table
    • 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;
    • Self Joins
      • Implements a recursive relationship
      • Important in various applications
        • Parts lists/assemblies
        • HR
        • Etc.
        • Table joined to itself using correlation names
    • Self Joins SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employeeid;
    • 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
    • Left Outer Join Basic SQL 92 Syntax: Select <column-list> From <table1> Left join <table2> On <join condition>
    • 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
    • Left Join with Results
    • SQL200 SQL Programming Part 2– Subqueries, Unions
    • Subqueries
      • One select statement embedded in another
      • Can be nested multiple levels deep
      • Two types:
        • Uncorrelated – executes inner query then outer
        • Correlated – executes inner query once for each outer query row
    • Uncorrelated Subquery select isbn, quantity from orderlines ol where ol.order_numb in (select o.order_numb from orders o where order_date between #1/1/99# and #12/31/99#)
    • Uncorrelated Subquery with Results
    • Negative Subquery
      • A type of subquery that matches “not found” conditions
    • Negative Subquery select isbn, quantity from orderlines ol where ol.order_numb not in (select o.order_numb from orders o where order_date between #1/1/99# and #12/31/99#)
    • Negative Subquery with Results
    • 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
    • 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#); This type of query covered in intermediate SQL class
    • Unions
      • Combines two tables
      • Tables must be union compatible
    • Unions Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2>
    • Unions select * from employees union all select * from employees_copy
    • Results of Union query
    • SQL200 SQL Programming Part 3 – Calculations, Aggregates
    • Calculated Fields
      • Can add a column calculated from others
      SELECT order_numb, quantity, cost_each, quantity*cost_each as extension FROM orderlines
    • Calculated field in the Result
    • String Manipulation
      • Concatenation
      • Trim
      • Substring
      • Upper, Lower
      • Etc. (various vendor extensions)
    • Concatenation
      • Used for concatenated keys
      • Useful to format reports
      Basic syntax: (Access) Field1 & Field2 (Oracle, std) Field1 || Field2 (Sql Server) Field1 + Field2
    • Concatenation select customer_first_name & &quot; &quot; & trim(customer_last_name) as Name from customers
    • Date Functions
      • Numerous date functions
      • Often vendor specific
      • Often used:
        • year
        • month
        • DateAdd, DateDiff, DatePart
        • getdate()
      • Ex: where year(order_date) = 1999
    • Aggregate Functions
      • Count
      • Sum
      • Min
      • Max
      • Avg
      • Often used in conjunction with grouping
    • Aggregate Functions Basic syntax: Select <function>(<column>) From <table> Group by <column-list> Having <predicate> Group by all columns to left of one(s) you want to aggregate
    • Aggregate Functions SELECT orderlines.order_numb, Count(*) AS &quot;Number of Order Lines &quot;, Sum(orderlines.quantity) AS SumOfquantity, Sum([quantity]*[cost_each]) AS extension FROM orderlines GROUP BY orderlines.order_numb having count(*) > 1
    • Having vs. Where
      • Having and Where clauses are similar but not the same
      • Having removes groups after they are formed
      • Where removes rows before groups are formed
    • 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
    • Exercise Result [end module]