SQL302 Intermediate SQL Workshop 2


Published on

SQL302 Intermediate SQL Course - Workshop 2. Covers cast, convert and case, intermediate joins, rollup, cube, union, except, intersect and window functions.

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

SQL302 Intermediate SQL Workshop 2

  1. 1. 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 FunctionsBookstore SQL302 Module 2 1
  2. 2. 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
  3. 3. 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 OrderlinesBookstore SQL302 Module 2 3
  4. 4. 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
  5. 5. 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.comBookstore SQL302 Module 2 5
  6. 6. Relational Database with constraints (from text)Bookstore SQL302 Module 2 6
  7. 7. Sample Employees DatabaseBookstore2 & SQL204 Module 1 7Employees
  8. 8. 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
  9. 9. SQL302 SQL Programming Part 1 – Joins: Natural, Self and OuterBookstore SQL302 Module 2 9
  10. 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 subtle aspects of joins in this classBookstore SQL302 Module 2 10
  11. 11. 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 ServerBookstore SQL302 Module 2 11
  12. 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;Bookstore SQL302 Module 2 12
  13. 13. Self Joins• Implements a recursive relationship• Important in various applications – Parts lists/assemblies – HR – Etc. – Table joined to itself using correlation namesBookstore SQL302 Module 2 13
  14. 14. Self Joins SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employeeid;Bookstore SQL302 Module 2 14
  15. 15. Bookstore SQL302 Module 2 15
  16. 16. 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 setBookstore SQL302 Module 2 16
  17. 17. Rollup• Example: calculate average salaries by job_title_code and managerBookstore SQL302 Module 2 17
  18. 18. Rollup resultsBookstore SQL302 Module 2 18
  19. 19. cube• Similar to rollup but computes summary rows in all dimensionsBookstore SQL302 Module 2 19
  20. 20. Cube results• Add a new set of rows which total by yearBookstore SQL302 Module 2 20
  21. 21. Bookstore SQL302 Module 2 21
  22. 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 tablesBookstore SQL302 Module 2 22
  23. 23. Left Outer Join Basic SQL 92 Syntax: Select <column-list> From <table1> Left join <table2> On <join condition>Bookstore SQL302 Module 2 23
  24. 24. Left Outer Join• List all customers with their orders• Include customers with no orders as wellBookstore SQL302 Module 2 24
  25. 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_numbBookstore SQL302 Module 2 25
  26. 26. Left Join with ResultsBookstore SQL302 Module 2 26
  27. 27. Negative Left Join• List all the customers who have not placed any orders• This is an example of a query which finds unmatched recordsBookstore SQL302 Module 2 27
  28. 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;Bookstore SQL302 Module 2 28
  29. 29. Bookstore SQL302 Module 2 29
  30. 30. 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 printoutBookstore SQL302 Module 2 30
  31. 31. 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
  32. 32. Own Your Own• List all books and their order totals for 1999• Show the book even if there were no orders placed in 1999Bookstore SQL302 Module 2 32
  33. 33. 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 matchingsBookstore SQL302 Module 2 33
  34. 34. Theta join• Find all customers that live at the same address – Requires a self join of the customers table on address fieldBookstore SQL302 Module 2 34
  35. 35. Theta join results • Can be further processed with a union query to consolidate names into a single listBookstore SQL302 Module 2 35
  36. 36. SQL302 SQL Programming Part 3– Set OperationsBookstore SQL302 Module 2 36
  37. 37. Set Operations• More on unions• Intersect• ExceptBookstore SQL302 Module 2 37
  38. 38. Unions• Combines two or more tables• Tables must be union compatibleBookstore SQL302 Module 2 38
  39. 39. Unions Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2>Bookstore SQL302 Module 2 39
  40. 40. Unions• Example: consolidate two columns into one columnBookstore SQL302 Module 2 40
  41. 41. Union consolidation result• Customers in same cityBookstore SQL302 Module 2 41
  42. 42. 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
  43. 43. unions• Example: add an element to a pick listBookstore SQL302 Module 2 43
  44. 44. 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
  45. 45. 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 2Bookstore 45
  46. 46. 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
  47. 47. 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 2Bookstore 47
  48. 48. SQL302 SQL Programming Part 4 – Window FunctionsBookstore SQL302 Module 2 48
  49. 49. Aggregate Functions• Count• Sum• Min• Max• Avg• Often used in conjunction with grouping and window functionsBookstore SQL302 Module 2 49
  50. 50. 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
  51. 51. Window Functions Basic syntax: Select …, window function(column) partition by <column> From <table> where <predicate>Bookstore SQL302 Module 2 51
  52. 52. 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
  53. 53. 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 linesBookstore SQL302 Module 2 53
  54. 54. NotesBookstore SQL302 Module 2 54
  55. 55. NotesBookstore SQL302 Module 2 55