SQL200 SQL Programming Workshop 2 – Joins, Subqueries, Unions, Calculations and Grouping Bookstore SQL200  Module 2 Based ...
Note on SQL200 Slides <ul><li>These slides were originally designed to support the single SQL200 course which was used for...
Warning! <ul><li>Below are some table name changes to be aware of in doing queries. We have created synonyms so either nam...
SQL200 Contact Information Bookstore SQL200  Module 2 P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2asso...
SQL200 Resources <ul><li>Bookstore database scripts found on box.net at </li></ul><ul><ul><li>http://tinyurl.com/SQLScript...
SQL200 SQL Programming Part 1 – Joins Bookstore SQL200  Module 2
Bookstore SQL200  Module 2 Relational Database with constraints (from text)
More conventions <ul><li>Names can be surrounded with “ “ or [ ] as in [order details].  </li></ul><ul><li>Some of the Pow...
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...
Bookstore SQL200  Module 2
Inner Join <ul><li>Pairs each row from first table with corresponding row from second table over the “join column” </li></...
Inner Join Bookstore SQL200  Module 2 Older Syntax: Select <column-list> From <tablelist> Where <predicate> Still very com...
Inner Join Bookstore SQL200  Module 2 Example using older syntax: SELECT  customer_first_name, customer_street, order_numb...
Inner Join with Result Bookstore SQL200  Module 2
Inner Join (New Syntax) Bookstore SQL200  Module 2 Basic SQL 92 Syntax: Select <column-list> From <table1> Inner join <tab...
Inner Join Bookstore SQL200  Module 2 Basic Example: SELECT  customer_first_name, customer_street, order_numb, order_date ...
Inner Join with Result Bookstore SQL200  Module 2
Inner Join over Multiple columns <ul><li>Note that that the join condition can apply to multiple columns if desired </li><...
Bookstore SQL200  Module 2 Inner Join Result in MS Access
Inner Join <ul><li>In the last example… </li></ul><ul><ul><li>What was the cardinality of the relationship between custome...
Cross Join <ul><li>What happens when you omit a join expression? </li></ul><ul><li>Get the cartesian product of the tables...
Bookstore SQL200  Module 2 Cross Join Result Set in MS Access
Additional SQL92 Syntax <ul><li>Table1 natural join table3 – automatically uses columns with same name </li></ul><ul><li>T...
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...
Joining More than Two Tables <ul><li>Add orderlines detail to previous queries </li></ul>Bookstore SQL200  Module 2 SELECT...
Multi-table Join with Results Bookstore SQL200  Module 2
On Your Own <ul><li>Add the book title to the previous query results </li></ul><ul><li>Hint: add another join to books tab...
Sample Database <ul><li>Before we continue (Access classes only)… </li></ul><ul><li>Create a new employees table </li></ul...
Correlation Names (Table Aliases) <ul><li>Can abbreviate references to tables </li></ul><ul><li>For example: </li></ul><ul...
Self Joins <ul><li>Implements a recursive relationship </li></ul><ul><li>Important in various applications </li></ul><ul><...
Self Joins Bookstore SQL200  Module 2 SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employe...
Bookstore SQL200  Module 2
Outer Joins <ul><li>Left – selects all rows from the left or first table, even if no match exists in the other table </li>...
Left Outer Join Bookstore SQL200  Module 2 Basic SQL 92 Syntax: Select <column-list> From <table1> Left join <table2> On <...
Left-Join Bookstore SQL200  Module 2 Basic Example: SELECT customer_first_name, customer_street, order_numb, order_date fr...
Bookstore SQL200  Module 2
Left Join with Results Bookstore SQL200  Module 2
SQL200 SQL Programming Part 2– Subqueries, Unions Bookstore SQL200  Module 2
Subqueries <ul><li>One select statement embedded in another </li></ul><ul><li>Can be nested multiple levels deep </li></ul...
Uncorrelated Subquery Bookstore SQL200  Module 2 select isbn, quantity from orderlines where order_numb in  (select order_...
Uncorrelated Subquery with Results Bookstore SQL200  Module 2
Negative Subquery <ul><li>A type of subquery that matches “not found” conditions </li></ul>Bookstore SQL200  Module 2
Negative Subquery Bookstore SQL200  Module 2 select isbn, quantity from orderlines where order_numb not in  (select order_...
Negative Subquery with Results Bookstore SQL200  Module 2
Correlated Subquery with Exists <ul><li>Inner subquery executed once for each outer row </li></ul><ul><li>Exists will retu...
Correlated subquery with Exists Bookstore SQL200  Module 2 SELECT isbn, quantity FROM orderlines AS ol WHERE exists  (sele...
Unions <ul><li>Combines two or more tables </li></ul><ul><li>Tables must be union compatible </li></ul>Bookstore SQL200  M...
Unions Bookstore SQL200  Module 2 Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2>
Unions Bookstore SQL200  Module 2 select * from employees union all select * from employees_copy
Bookstore SQL200  Module 2 Results of Union query
SQL200 SQL Programming Part 3 – Calculations, Aggregates Bookstore SQL200  Module 2
Calculated Fields <ul><li>Can add a column calculated from others </li></ul>Bookstore SQL200  Module 2 SELECT order_numb, ...
Calculated field in the Result Bookstore SQL200  Module 2
Bookstore SQL200  Module 2
String Manipulation <ul><li>Concatenation </li></ul><ul><li>Trim </li></ul><ul><li>Substring </li></ul><ul><li>Upper, Lowe...
Concatenation <ul><li>Used for concatenated keys </li></ul><ul><li>Useful to format reports </li></ul>Bookstore SQL200  Mo...
Concatenation Bookstore SQL200  Module 2 select customer_first_name + ‘ ‘ + trim(customer_last_name) as Name from customers
Bookstore SQL200  Module 2
Date Functions <ul><li>Numerous date functions </li></ul><ul><li>Often vendor specific </li></ul><ul><li>Often used: </li>...
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 ...
Aggregate Functions Bookstore SQL200  Module 2 Basic syntax: Select <function>(<column>) From <table> Group by <column-lis...
Aggregate Functions Bookstore SQL200  Module 2 SELECT order_numb, Count(*) AS [Number of Order Lines] , Sum(quantity) AS [...
Bookstore SQL200  Module 2
Having vs. Where <ul><li>Having and Where clauses are similar but not the same </li></ul><ul><li>Having removes groups  af...
Exercise <ul><li>List all customers and their orders </li></ul><ul><ul><li>Name nicely formatted </li></ul></ul><ul><ul><l...
Exercise Result Bookstore SQL200  Module 2 [end module]
Notes Bookstore SQL200  Module 2
Notes Bookstore SQL200  Module 2
Upcoming SlideShare
Loading in …5
×

SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2

514 views

Published on

Accelerated Introduction to SQL Using Microsoft SQL Server Module 2. Covers inner, outer and self joins, correlated and uncorrelated subqueries, unions, aggregate functions, calculated fields 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
514
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2

  1. 1. SQL200 SQL Programming Workshop 2 – Joins, Subqueries, Unions, Calculations and Grouping Bookstore SQL200 Module 2 Based on SQL Clearly Explained by Jan Harrington
  2. 2. Note on SQL200 Slides <ul><li>These slides were originally designed to support the single SQL200 course which was used for any of MS Access, MySQL, Oracle and SQL Server. </li></ul><ul><li>As such you may see here slides developed in any one of the above products. </li></ul><ul><li>We are in the process of migrating the Oracle slides and the MS Access slides out into their own slide sets. The SQL200 slides will cover MySQL and SQL Server which are virtually identical for purposes of this course. </li></ul>Bookstore SQL200 Module 2
  3. 3. Warning! <ul><li>Below are some table name changes to be aware of in doing queries. We have created synonyms so either name should work. </li></ul>Bookstore SQL200 Module 2 New Name Old Name Orders Order_filled Order_Lines Orderlines
  4. 4. SQL200 Contact Information Bookstore SQL200 Module 2 P.O. Box 6142 Laguna Niguel, CA 92607 949-489-1472 http://www.d2associates.com [email_address] Copyright 2001-20011 All rights reserved.
  5. 5. SQL200 Resources <ul><li>Bookstore database scripts found on box.net at </li></ul><ul><ul><li>http://tinyurl.com/SQLScripts </li></ul></ul><ul><li>Slides can be viewed on SlideShare… </li></ul><ul><ul><li>http://www.slideshare.net/OCDatabases </li></ul></ul><ul><li>Follow up questions? </li></ul><ul><ul><li>[email_address] </li></ul></ul>Bookstore SQL200 Module 2
  6. 6. SQL200 SQL Programming Part 1 – Joins Bookstore SQL200 Module 2
  7. 7. Bookstore SQL200 Module 2 Relational Database with constraints (from text)
  8. 8. More conventions <ul><li>Names can be surrounded with “ “ or [ ] as in [order details]. </li></ul><ul><li>Some of the PowerPoint slides may have this convention. </li></ul><ul><li>Better practice is to use an underscore as in order_details. </li></ul>Bookstore SQL200 Module 2
  9. 9. 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>Bookstore SQL200 Module 2
  10. 10. Bookstore SQL200 Module 2
  11. 11. 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>Bookstore SQL200 Module 2
  12. 12. Inner Join Bookstore SQL200 Module 2 Older Syntax: Select <column-list> From <tablelist> Where <predicate> Still very commonly used
  13. 13. Inner Join Bookstore SQL200 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
  14. 14. Inner Join with Result Bookstore SQL200 Module 2
  15. 15. Inner Join (New Syntax) Bookstore SQL200 Module 2 Basic SQL 92 Syntax: Select <column-list> From <table1> Inner join <table2> On <join condition>
  16. 16. Inner Join Bookstore SQL200 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
  17. 17. Inner Join with Result Bookstore SQL200 Module 2
  18. 18. 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>Bookstore SQL200 Module 2
  19. 19. Bookstore SQL200 Module 2 Inner Join Result in MS Access
  20. 20. 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>Bookstore SQL200 Module 2
  21. 21. 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>Bookstore SQL200 Module 2
  22. 22. Bookstore SQL200 Module 2 Cross Join Result Set in MS Access
  23. 23. 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>Bookstore SQL200 Module 2
  24. 24. 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>Bookstore SQL200 Module 2
  25. 25. Joining More than Two Tables <ul><li>Add orderlines detail to previous queries </li></ul>Bookstore SQL200 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
  26. 26. Multi-table Join with Results Bookstore SQL200 Module 2
  27. 27. On Your Own <ul><li>Add the book title to the previous query results </li></ul><ul><li>Hint: add another join to books table </li></ul>Bookstore SQL200 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>Bookstore SQL200 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>Bookstore SQL200 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>Bookstore SQL200 Module 2
  31. 31. Self Joins Bookstore SQL200 Module 2 SELECT e.*, m.name FROM employees AS e, employees AS m WHERE e.managerid = m.employeeid;
  32. 32. Bookstore SQL200 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>Bookstore SQL200 Module 2
  34. 34. Left Outer Join Bookstore SQL200 Module 2 Basic SQL 92 Syntax: Select <column-list> From <table1> Left join <table2> On <join condition>
  35. 35. Left-Join Bookstore SQL200 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
  36. 36. Bookstore SQL200 Module 2
  37. 37. Left Join with Results Bookstore SQL200 Module 2
  38. 38. SQL200 SQL Programming Part 2– Subqueries, Unions Bookstore SQL200 Module 2
  39. 39. Subqueries <ul><li>One select statement embedded in another </li></ul><ul><li>Can be nested multiple levels deep </li></ul><ul><li>Can be used in select, from and where clauses </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>Bookstore SQL200 Module 2
  40. 40. Uncorrelated Subquery Bookstore SQL200 Module 2 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’);
  41. 41. Uncorrelated Subquery with Results Bookstore SQL200 Module 2
  42. 42. Negative Subquery <ul><li>A type of subquery that matches “not found” conditions </li></ul>Bookstore SQL200 Module 2
  43. 43. Negative Subquery Bookstore SQL200 Module 2 select isbn, quantity from orderlines where order_numb not in (select order_numb from orders where order_date between ‘1/1/99’ and ‘12/31/99’);
  44. 44. Negative Subquery with Results Bookstore SQL200 Module 2
  45. 45. 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>Bookstore SQL200 Module 2
  46. 46. Correlated subquery with Exists Bookstore SQL200 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/1/99’ and ‘12/31/99’); This type of query covered in intermediate SQL class
  47. 47. Unions <ul><li>Combines two or more tables </li></ul><ul><li>Tables must be union compatible </li></ul>Bookstore SQL200 Module 2
  48. 48. Unions Bookstore SQL200 Module 2 Select <column-list> from <table1> Union [ALL] Select <same-columns> from <table2>
  49. 49. Unions Bookstore SQL200 Module 2 select * from employees union all select * from employees_copy
  50. 50. Bookstore SQL200 Module 2 Results of Union query
  51. 51. SQL200 SQL Programming Part 3 – Calculations, Aggregates Bookstore SQL200 Module 2
  52. 52. Calculated Fields <ul><li>Can add a column calculated from others </li></ul>Bookstore SQL200 Module 2 SELECT order_numb, quantity, cost_each, quantity*cost_each as extension FROM orderlines
  53. 53. Calculated field in the Result Bookstore SQL200 Module 2
  54. 54. Bookstore SQL200 Module 2
  55. 55. 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>Bookstore SQL200 Module 2
  56. 56. Concatenation <ul><li>Used for concatenated keys </li></ul><ul><li>Useful to format reports </li></ul>Bookstore SQL200 Module 2 Basic syntax: (Access) Field1 & Field2 (Oracle, std) Field1 || Field2 (Sql Server) Field1 + Field2
  57. 57. Concatenation Bookstore SQL200 Module 2 select customer_first_name + ‘ ‘ + trim(customer_last_name) as Name from customers
  58. 58. Bookstore SQL200 Module 2
  59. 59. 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>Bookstore SQL200 Module 2
  60. 60. 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>Bookstore SQL200 Module 2
  61. 61. Aggregate Functions Bookstore SQL200 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
  62. 62. Aggregate Functions Bookstore SQL200 Module 2 SELECT order_numb, Count(*) AS [Number of Order Lines] , Sum(quantity) AS [Total Quantity], Sum(quantity * cost_each) AS [Total Amount] FROM order_lines GROUP BY order_numb having count(*) > 1;
  63. 63. Bookstore SQL200 Module 2
  64. 64. 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>Bookstore SQL200 Module 2
  65. 65. 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>Bookstore SQL200 Module 2
  66. 66. Exercise Result Bookstore SQL200 Module 2 [end module]
  67. 67. Notes Bookstore SQL200 Module 2
  68. 68. Notes Bookstore SQL200 Module 2

×