SQL212.2 Introduction to SQL using Oracle Module 2

472 views

Published on

Joins, Subqueries, Unions, Calculations and Grouping

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
472
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
17
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

SQL212.2 Introduction to SQL using Oracle Module 2

  1. 1. SQL212 SQL Programming Workshop 2 – Joins, Subqueries, Unions, Calculations and Grouping Bookstore2 SQL212 Module 2
  2. 2. SQL212 Contact Information Bookstore2 SQL212 Module 2 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. SQL212 SQL Programming Part 1 – Joins, Subqueries Bookstore2 SQL212 Module 2
  4. 4. Bookstore2 SQL212 Module 2 Relational Database with constraints (from text)
  5. 5. 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>Bookstore2 SQL212 Module 2
  6. 6. 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>Bookstore2 SQL212 Module 2
  7. 7. 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>Bookstore2 SQL212 Module 2
  8. 8. Inner Join Bookstore2 SQL212 Module 2 Older Syntax: Select <column-list> From <tablelist> Where <predicate> Still very commonly used
  9. 9. Inner Join Examples <ul><li>Show customers and their orders </li></ul><ul><li>Join the customers table to the orders table where the customer number in each table matches </li></ul>Bookstore2 SQL212 Module 2
  10. 10. Inner Join Bookstore2 SQL212 Module 2 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 Bookstore2 SQL212 Module 2
  12. 12. Inner Join (New Syntax) Bookstore2 SQL212 Module 2 Basic SQL 92 Syntax: Select <column-list> From <table1> Inner join <table2> On <join condition>
  13. 13. Inner Join Bookstore2 SQL212 Module 2 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 Bookstore2 SQL212 Module 2
  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>Bookstore2 SQL212 Module 2
  16. 16. Bookstore2 SQL212 Module 2 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>Bookstore2 SQL212 Module 2
  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>Bookstore2 SQL212 Module 2
  19. 19. Dual <ul><li>Sometimes we want to generate an expression without actually referring to a real table. </li></ul><ul><li>A trivial example would show the date. </li></ul><ul><li>Oracle has a 1 row, 1 column built in table called Dual to handle this. </li></ul><ul><li>Ex: select sysdate from dual; </li></ul>Bookstore2 SQL212 Module 2
  20. 20. Bookstore2 SQL212 Module 2 Cross Join Result Set in MS Access
  21. 21. Additional SQL92 Syntax <ul><li>Table1 natural join table2 – automatically uses columns with same name </li></ul><ul><li>Table1 natural join table2 using(<column-list>) </li></ul><ul><li>Not yet widely available in commercial implementations </li></ul>Bookstore2 SQL212 Module 2
  22. 22. Natural Join Bookstore2 SQL212 Module 2
  23. 23. 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>Bookstore2 SQL212 Module 2
  24. 24. Joining More than Two Tables <ul><li>Add orderlines detail to previous queries </li></ul>Bookstore2 SQL212 Module 2 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
  25. 25. Multi-table Join with Results Bookstore2 SQL212 Module 2
  26. 26. Bookstore2 SQL212 Module 2 MS Access Multi-table Join Result Set
  27. 27. Own Your Own <ul><li>Add the book title to the previous query </li></ul>Bookstore2 SQL212 Module 2
  28. 28. Sample Database <ul><li>Before we continue (Access classes only)… </li></ul><ul><li>Create a new employees table </li></ul>Bookstore2 SQL212 Module 2
  29. 29. 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>Bookstore2 SQL212 Module 2
  30. 30. 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>Bookstore2 SQL212 Module 2
  31. 31. Self Joins Bookstore2 SQL212 Module 2 SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employeeid;
  32. 32. Bookstore2 SQL212 Module 2
  33. 33. 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>Bookstore2 SQL212 Module 2
  34. 34. Left Outer Join Bookstore2 SQL212 Module 2 Basic SQL 92 Syntax: Select <column-list> From <table1> Left [outer] join <table2> On <join condition>
  35. 35. Outer Join Example <ul><li>Show all customers and their orders. </li></ul><ul><li>Include customers with no orders as well. </li></ul>Bookstore2 SQL212 Module 2
  36. 36. Left-Join Bookstore2 SQL212 Module 2 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
  37. 37. Bookstore2 SQL212 Module 2
  38. 38. Left Join with Results Bookstore2 SQL212 Module 2
  39. 39. SQL200 SQL Programming Part 2– Subqueries, Unions Bookstore2 SQL212 Module 2
  40. 40. Subqueries <ul><li>One select statement embedded in another. </li></ul><ul><li>Can be paced in select list, from clause or where clause. </li></ul><ul><ul><li>We will study the latter in this class </li></ul></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>Bookstore2 SQL212 Module 2
  41. 41. Subquery Example <ul><li>Show all the orderline information for orders places in 1999 </li></ul><ul><li>Note that orderlines table does not have order date. Thus must filter on a different table (orders). </li></ul>Bookstore2 SQL212 Module 2
  42. 42. Uncorrelated Subquery Bookstore2 SQL212 Module 2 select isbn, quantity from orderlines ol where ol.order_numb in (select o.order_numb from orders o where order_date between ‘1-JAN-99’ and ’31-DEC-99’)
  43. 43. Uncorrelated Subquery with Results Bookstore2 SQL212 Module 2
  44. 44. Negative Subquery <ul><li>A type of subquery that matches “not found” conditions </li></ul>Bookstore2 SQL212 Module 2
  45. 45. Negative Subquery Bookstore2 SQL212 Module 2 select isbn, quantity from orderlines ol where ol.order_numb not in (select o.order_numb from orders o where order_date between ‘1-JAN-99’ and 31-DEC-99’)
  46. 46. Negative Subquery with Results Bookstore2 SQL212 Module 2
  47. 47. 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>Bookstore2 SQL212 Module 2
  48. 48. Correlated subquery with Exists Bookstore2 SQL212 Module 2 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-JAN-99’ and ‘31-DEC-99’); This type of query covered in intermediate SQL class
  49. 49. Unions <ul><li>Combines two tables </li></ul><ul><li>Tables must be union compatible </li></ul><ul><li>Uses: </li></ul><ul><ul><li>Combine current tables with history </li></ul></ul><ul><ul><li>Combine information from tables with no common join column </li></ul></ul>Bookstore2 SQL212 Module 2
  50. 50. Unions Bookstore2 SQL212 Module 2 Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2>
  51. 51. Union Example <ul><li>Create a mailing list of customers and sources </li></ul><ul><li>Use a union of the two tables, making sure the columns match </li></ul>Bookstore2 SQL212 Module 2
  52. 52. Unions Bookstore2 SQL212 Module 2
  53. 53. Union Results Bookstore2 SQL212 Module 2
  54. 54. SQL200 SQL Programming Part 3 – Calculations, Aggregates Bookstore2 SQL212 Module 2
  55. 55. Calculated Fields <ul><li>Can add a column calculated from others </li></ul>Bookstore2 SQL212 Module 2 SELECT order_numb, quantity, cost_each, quantity*cost_each as extension FROM orderlines
  56. 56. Calculated field in the Result Bookstore2 SQL212 Module 2
  57. 57. Bookstore2 SQL212 Module 2
  58. 58. 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>Bookstore2 SQL212 Module 2
  59. 59. Concatenation <ul><li>Used for concatenated keys </li></ul><ul><li>Useful to format reports </li></ul>Bookstore2 SQL212 Module 2 Basic syntax: (Oracle, std) Field1 || Field2
  60. 60. Concatenation Bookstore2 SQL212 Module 2 select customer_first_name || ‘ ‘ || trim(customer_last_name) as Name from customers
  61. 61. Bookstore2 SQL212 Module 2
  62. 62. 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>Take the year of a date </li></ul></ul><ul><ul><li>Take the month of a date </li></ul></ul><ul><ul><li>Add a month (not 30 days) </li></ul></ul><ul><ul><li>Etc. </li></ul></ul>Bookstore2 SQL212 Module 2
  63. 63. 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>Bookstore2 SQL212 Module 2
  64. 64. Aggregate Functions Bookstore2 SQL212 Module 2 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
  65. 65. Aggregate Functions Bookstore2 SQL212 Module 2 SELECT orderlines.order_numb, Count(*) AS “Number of Order Lines” , Sum(orderlines.quantity) AS SumOfquantity, Sum(quantity * cost_each) AS extension FROM orderlines GROUP BY orderlines.order_numb having count(*) > 1
  66. 66. Bookstore2 SQL212 Module 2
  67. 67. 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>Bookstore2 SQL212 Module 2
  68. 68. 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 </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>Bookstore2 SQL212 Module 2
  69. 69. Exercise Result Bookstore2 SQL212 Module 2 [end module]
  70. 70. Notes Bookstore2 SQL212 Module 2
  71. 71. Notes Bookstore2 SQL212 Module 2
  72. 72. Notes Bookstore2 SQL212 Module 2

×