SQL200.2 Module 2


Published on

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

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

SQL200.2 Module 2

  1. 1. SQL200 SQL Programming Workshop 2 – Joins, Subqueries, Unions, Calculations and Grouping
  2. 2. 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.
  3. 3. SQL200 SQL Programming Part 1 – Joins, Subqueries
  4. 4. Relational Database with constraints (from text)
  5. 5. More conventions <ul><li>Names can be surrounded with [] as in [order details]. Better practice is to use an underscore as in order_details. </li></ul><ul><li>MS Access often adds the brackets. Some of the PowerPoint slides have this convention, but it works equally as well in SQL Server. </li></ul>
  6. 6. Warning! <ul><li>Some slides may show queries using a table called… </li></ul><ul><ul><li>Order_filled </li></ul></ul><ul><li>The current database uses a better name… </li></ul><ul><ul><li>Orders </li></ul></ul><ul><ul><li>Construct your queries with this latter table name </li></ul></ul>
  7. 7. Joins <ul><li>Inner </li></ul><ul><li>Outer </li></ul><ul><ul><li>Left </li></ul></ul><ul><ul><li>Right </li></ul></ul><ul><ul><li>Full </li></ul></ul><ul><li>Cross </li></ul><ul><li>Self </li></ul><ul><li>Theta </li></ul><ul><li>We will cover the most important; others as time and interest permit </li></ul>
  8. 8. Inner Join <ul><li>Pairs each row from first table with corresponding row from second table over the “join column” </li></ul><ul><li>The result set only contains rows where there is a match over the join column in both tables </li></ul><ul><li>Equi-join is the common inner join </li></ul>
  9. 9. Inner Join Older Syntax: Select <column-list> From <tablelist> Where <predicate> Still very commonly used
  10. 10. 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
  11. 11. Inner Join with Result
  12. 12. Inner Join (New Syntax) Basic SQL 92 Syntax: Select <column-list> From <table1> Inner join <table2> On <join condition>
  13. 13. 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
  14. 14. Inner Join with Result
  15. 15. Inner Join over Multiple columns <ul><li>Note that that the join condition can apply to multiple columns if desired </li></ul><ul><li>Used with composite keys </li></ul>
  16. 16. Inner Join Result in MS Access
  17. 17. Inner Join <ul><li>In the last example… </li></ul><ul><ul><li>What was the cardinality of the relationship between customers and orders? </li></ul></ul><ul><ul><li>Which table was the parent? </li></ul></ul><ul><ul><li>What was it’s primary key? </li></ul></ul><ul><ul><li>In which table did we employ a foreign key and what was it? </li></ul></ul>
  18. 18. Cross Join <ul><li>What happens when you omit a join expression? </li></ul><ul><li>Get the cartesian product of the tables – all possible combinations of the two tables </li></ul><ul><li>For large tables this will run a long time! </li></ul>
  19. 19. Cross Join Result Set in MS Access
  20. 20. Additional SQL92 Syntax <ul><li>Table1 natural join table3 – automatically uses columns with same name </li></ul><ul><li>Table 1 natural join table2 using(<column-list> </li></ul><ul><li>Not yet widely available in commercial implementations </li></ul>
  21. 21. Joining More than Two Tables <ul><li>Can join several tables in one select </li></ul><ul><li>Try to limit to three or four </li></ul><ul><li>Join order can be important for performance (although optimizers will usually handle this for you) </li></ul><ul><li>Use parentheses to force order of evaluation (also vendor extensions, often called “hints”) </li></ul>
  22. 22. Joining More than Two Tables <ul><li>Add orderlines detail to previous queries </li></ul>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
  23. 23. Multi-table Join with Results
  24. 24. MS Access Multi-table Join Result Set
  25. 25. Sample Database <ul><li>Before we continue (Access classes only)… </li></ul><ul><li>Create a new employees table </li></ul>
  26. 26. Correlation Names (Table Aliases) <ul><li>Can abbreviate references to tables </li></ul><ul><li>For example: </li></ul><ul><ul><li>Select e .name , j .payrange </li></ul></ul><ul><ul><li>From employees as e </li></ul></ul><ul><ul><li>Inner join job_information as j </li></ul></ul><ul><ul><li>On e .jobcode = j .jobcode; </li></ul></ul>
  27. 27. Self Joins <ul><li>Implements a recursive relationship </li></ul><ul><li>Important in various applications </li></ul><ul><ul><li>Parts lists/assemblies </li></ul></ul><ul><ul><li>HR </li></ul></ul><ul><ul><li>Etc. </li></ul></ul><ul><ul><li>Table joined to itself using correlation names </li></ul></ul>
  28. 28. Self Joins SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employeeid;
  29. 30. Outer Joins <ul><li>Left – selects all rows from the left or first table, even if no match exists in the other table </li></ul><ul><ul><li>Widely used in commercial practice </li></ul></ul><ul><ul><li>Especially useful for reporting </li></ul></ul><ul><ul><li>Can be slower and interfere with optimizer </li></ul></ul><ul><li>Right – same idea but all rows from right table </li></ul><ul><li>Full – all rows form both tables </li></ul>
  30. 31. Left Outer Join Basic SQL 92 Syntax: Select <column-list> From <table1> Left join <table2> On <join condition>
  31. 32. 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
  32. 34. Left Join with Results
  33. 35. SQL200 SQL Programming Part 2– Subqueries, Unions
  34. 36. Subqueries <ul><li>One select statement embedded in another </li></ul><ul><li>Can be nested multiple levels deep </li></ul><ul><li>Two types: </li></ul><ul><ul><li>Uncorrelated – executes inner query then outer </li></ul></ul><ul><ul><li>Correlated – executes inner query once for each outer query row </li></ul></ul>
  35. 37. 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#)
  36. 38. Uncorrelated Subquery with Results
  37. 39. Negative Subquery <ul><li>A type of subquery that matches “not found” conditions </li></ul>
  38. 40. 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#)
  39. 41. Negative Subquery with Results
  40. 42. Correlated Subquery with Exists <ul><li>Inner subquery executed once for each outer row </li></ul><ul><li>Exists will return true or false depending on whether the result will have any rows or not </li></ul><ul><li>Can be a quick way to test for existence of records (parent records, say) as used in application enforcement of referential integrity </li></ul>
  41. 43. 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
  42. 44. Unions <ul><li>Combines two tables </li></ul><ul><li>Tables must be union compatible </li></ul>
  43. 45. Unions Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2>
  44. 46. Unions select * from employees union all select * from employees_copy
  45. 47. Results of Union query
  46. 48. SQL200 SQL Programming Part 3 – Calculations, Aggregates
  47. 49. Calculated Fields <ul><li>Can add a column calculated from others </li></ul>SELECT order_numb, quantity, cost_each, quantity*cost_each as extension FROM orderlines
  48. 50. Calculated field in the Result
  49. 52. String Manipulation <ul><li>Concatenation </li></ul><ul><li>Trim </li></ul><ul><li>Substring </li></ul><ul><li>Upper, Lower </li></ul><ul><li>Etc. (various vendor extensions) </li></ul>
  50. 53. Concatenation <ul><li>Used for concatenated keys </li></ul><ul><li>Useful to format reports </li></ul>Basic syntax: (Access) Field1 & Field2 (Oracle, std) Field1 || Field2 (Sql Server) Field1 + Field2
  51. 54. Concatenation select customer_first_name & &quot; &quot; & trim(customer_last_name) as Name from customers
  52. 56. Date Functions <ul><li>Numerous date functions </li></ul><ul><li>Often vendor specific </li></ul><ul><li>Often used: </li></ul><ul><ul><li>year </li></ul></ul><ul><ul><li>month </li></ul></ul><ul><ul><li>DateAdd, DateDiff, DatePart </li></ul></ul><ul><ul><li>getdate() </li></ul></ul><ul><li>Ex: where year(order_date) = 1999 </li></ul>
  53. 57. Aggregate Functions <ul><li>Count </li></ul><ul><li>Sum </li></ul><ul><li>Min </li></ul><ul><li>Max </li></ul><ul><li>Avg </li></ul><ul><li>Often used in conjunction with grouping </li></ul>
  54. 58. 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
  55. 59. 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
  56. 61. Having vs. Where <ul><li>Having and Where clauses are similar but not the same </li></ul><ul><li>Having removes groups after they are formed </li></ul><ul><li>Where removes rows before groups are formed </li></ul>
  57. 62. Exercise <ul><li>List all customers and their orders </li></ul><ul><ul><li>Name nicely formatted </li></ul></ul><ul><ul><li>With orders in the year of 1999 (do not use between, etc.) </li></ul></ul><ul><ul><li>Show total order quantities and amounts </li></ul></ul><ul><ul><li>Only include orders with more than three order lines </li></ul></ul>
  58. 63. Exercise Result [end module]