Intro to tsql unit 3


Published on

  • Be the first to comment

  • Be the first to like this

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

No notes for slide

Intro to tsql unit 3

  1. 1. Introduction To SQL Unit 3 Modern Business Technology Introduction To TSQL Unit 3 Developed by Michael Hotek
  2. 2. Unit 3 <ul><li>Goals </li></ul><ul><li>Nulls </li></ul><ul><li>Group by </li></ul><ul><li>Order by </li></ul><ul><li>Distinct </li></ul><ul><li>Aggregates </li></ul><ul><li>Aggregates with grouping </li></ul><ul><li>Having </li></ul><ul><li>Compute </li></ul><ul><li>Unions </li></ul>
  3. 3. <ul><li>There are times when data is missing or incomplete </li></ul><ul><li>To handle this missing data, most DBMSs use the concept of a null </li></ul><ul><li>A null does not mean zero </li></ul><ul><li>A null also does not mean a blank </li></ul><ul><li>A null indicates that a value is missing, unavailable, incomplete, and inapplicable </li></ul>Null
  4. 4. Null <ul><li>Nulls represent an unknown quantity or value </li></ul><ul><li>You can't guarantee that a null does equal some other value </li></ul><ul><li>You also can't guarantee that a null doesn't equal another value </li></ul><ul><li>A null also might or might not equal another value </li></ul>
  5. 5. Null <ul><li>For example take the authors table </li></ul><ul><li>If we were to leave out the state data for an author, this could bring up a few questions </li></ul><ul><li>Is the author from CA? </li></ul><ul><li>Is the author not from CA? </li></ul><ul><li>Is the author from some other state? </li></ul><ul><li>Any or none of these questions could be true </li></ul>
  6. 6. Null <ul><li>Any question about a null could provide three answers: yes, no, or maybe </li></ul><ul><li>This could mean that using nulls gives us a very serious problem, since rows are selected based on a criteria being true </li></ul><ul><li>Fortunately the DBMS manufacturers have given us some relief </li></ul>
  7. 7. Rules for Nulls <ul><li>A null does not designate an unknown value </li></ul><ul><li>A null does not equal another distinct value </li></ul><ul><li>A null does not equal another null </li></ul><ul><li>WAIT A MINUTE!!! </li></ul>
  8. 8. Nulls cont. <ul><li>I can obviously test for a null and I can place a null into a column </li></ul><ul><li>Since I am placing the same &quot;value&quot; (a null) into a column, how can a null not equal a null </li></ul><ul><li>A null represents the nonexistence of data </li></ul><ul><li>Something that doesn't exist can't be compared with something else that doesn't exist. </li></ul><ul><li>If it could then, this would imply that the values being compared actually do exist. This violates the definition of a null </li></ul>
  9. 9. Nulls (theory aside) <ul><li>All of this appears to be rather deep and theoretical. In fact entire books have been written about nulls. </li></ul><ul><li>This class is based on the practical application of SQL theory </li></ul><ul><li>To that end the only things you need to remember are the following: </li></ul><ul><ul><li>You can select rows that have a null value </li></ul></ul><ul><ul><li>A null does not equal a null </li></ul></ul>
  10. 10. Nulls Applied <ul><li>Suppose we want to get the titles that do not have an assigned royalty </li></ul><ul><li>Based on our previous experience we would probably do the following: </li></ul><ul><ul><li>select * from titles where royalty = null </li></ul></ul><ul><li>Paradoxically, this would work in most DBMSs </li></ul><ul><li>This is because most DBMS manufacturers recognize the problems with null and seek to protect you from yourself. The DBMS will convert this into it's proper form and return what you asked for </li></ul>
  11. 11. Nulls Applied <ul><li>The proper way is to be explicit in what you are asking. </li></ul><ul><li>We want to know where the values are null </li></ul><ul><li>select title, royalty from titles where royalty is null </li></ul><ul><li>title royalty </li></ul><ul><li>------------------------------------------------------------ ----------- </li></ul><ul><li>The Psychology of Computer Cooking (null) </li></ul><ul><li>Net Etiquette (null) </li></ul><ul><li>(2 row(s) affected) </li></ul>
  12. 12. The Basics recap <ul><li>This completes all of the basics of selecting data </li></ul><ul><li>To quickly recap </li></ul><ul><li>The select clause specifies what columns we want to see </li></ul><ul><li>The from clause tells what table we want to see data from </li></ul><ul><li>The where clause restricts the data we will see </li></ul>
  13. 13. Order by <ul><li>The order by clause is used to specify a sorting order of the result set </li></ul><ul><li>The sorting can be performed by column name or by column number </li></ul><ul><li>select au_fname,au_lname from authors order by au_lname,au_fname </li></ul><ul><li>or </li></ul><ul><li>select au_fname,au_lname from authors order by 2,1 </li></ul>
  14. 14. Order by <ul><li>Depending upon the DBMS, the column you are ordering by does not need to be specified in the select clause </li></ul><ul><li>select au_fname, au_lname from authors order by state </li></ul><ul><li>While this does work on some DBMSs, it is generally not advisable </li></ul><ul><li>The default sort order is ascending (a-z), but you can specify a descending order by using the keyword desc </li></ul><ul><li>… order by au_lname desc, au_fname </li></ul>
  15. 15. Sort Order <ul><li>If order by sorts the data, how do I know what that order it is sorted in? </li></ul><ul><li>The sort order is determined by a character set which is defined for a database </li></ul><ul><li>In Sybase and MS SQL Server, this character map can be retrieved by executing sp_helpsort </li></ul><ul><li>exec sp_helpsort </li></ul>
  16. 16. Order by <ul><li>An order by is not limited to actual data columns </li></ul><ul><li>We can order by a calculation if we wish </li></ul><ul><li>select au_fname + ' ' + au_lname name from authors order by name </li></ul><ul><li>name </li></ul><ul><li>------------------------------------------------------------- </li></ul><ul><li>Abraham Bennet </li></ul><ul><li>Akiko Yokomoto </li></ul><ul><li>Albert Ringer </li></ul><ul><li>Ann Dull </li></ul><ul><li>... </li></ul><ul><li>Meander Smith </li></ul><ul><li>Michael O'Leary </li></ul><ul><li>Michel DeFrance </li></ul><ul><li>Morningstar Greene </li></ul><ul><li>Patti Smythe </li></ul><ul><li>Reginald Blotchet-Halls </li></ul><ul><li>Sheryl Hunter </li></ul><ul><li>Stearns MacFeather </li></ul><ul><li>Sylvia Panteley </li></ul><ul><li>(27 row(s) affected) </li></ul>
  17. 17. Order by / Nulls <ul><li>An order by is based upon a sort order specified by a character set </li></ul><ul><li>Since nulls aren't characters, where do these fit in? </li></ul><ul><li>Depending on the DBMS, you will find the nulls at either the beginning or the end of the result set. </li></ul><ul><li>Where they are depends on the way the DBMS manufacturer has specified </li></ul>
  18. 18. Distinct <ul><li>As you have seen from some of the queries we have run, you can get what appear to be duplicate rows in the result set </li></ul><ul><li>From the scope of the result set, they are duplicates </li></ul><ul><li>From the scope of the database they are not </li></ul><ul><li>This is because the select statements we have performed up to this point returned the row of data for every row in a table that matched a specific criteria </li></ul>
  19. 19. Distinct <ul><li>Sometimes we do not want to see these duplicate rows </li></ul><ul><li>We can eliminate them by use of the distinct keyword </li></ul><ul><li>The distinct is placed immediately after the select </li></ul><ul><li>There can also be only one distinct per SQL statement </li></ul><ul><li>The distinct applies to all columns in the select list </li></ul>
  20. 20. Distinct <ul><li>select au_id from titleauthor </li></ul><ul><li>au_id </li></ul><ul><li>----------- </li></ul><ul><li>172-32-1176 </li></ul><ul><li>213-46-8915 </li></ul><ul><li>213-46-8915 </li></ul><ul><li>238-95-7766 </li></ul><ul><li>267-41-2394 </li></ul><ul><li>267-41-2394 </li></ul><ul><li>... </li></ul><ul><li>899-46-2035 </li></ul><ul><li>899-46-2035 </li></ul><ul><li>998-72-3567 </li></ul><ul><li>998-72-3567 </li></ul><ul><li>(25 row(s) affected) </li></ul><ul><li>select distinct au_id from titleauthor </li></ul><ul><li>au_id </li></ul><ul><li>----------- </li></ul><ul><li>172-32-1176 </li></ul><ul><li>213-46-8915 </li></ul><ul><li>238-95-7766 </li></ul><ul><li>267-41-2394 </li></ul><ul><li>... </li></ul><ul><li>899-46-2035 </li></ul><ul><li>998-72-3567 </li></ul><ul><li>(19 row(s) affected) </li></ul>
  21. 21. Aggregates <ul><li>There are times when we want to perform calculations on all of the values in a column or table </li></ul><ul><li>We accomplish this through the use of aggregates </li></ul><ul><li>The three we will explore are count, sum, and average </li></ul>
  22. 22. Count(*) <ul><li>Count will return exactly what it's name implies </li></ul><ul><li>It returns a count of the number of rows in a table that match a certain criteria </li></ul><ul><li>select count(*) from authors will return the number of rows in the authors table </li></ul><ul><li>----------- </li></ul><ul><li>27 </li></ul><ul><li>(1 row(s) affected) </li></ul><ul><li>select count(*) from authors where state = 'CA' will return the number of authors living in CA </li></ul><ul><li>----------- </li></ul><ul><li>15 </li></ul><ul><li>(1 row(s) affected) </li></ul>
  23. 23. Sum <ul><li>The sum is used to add up all of the values in a column </li></ul><ul><li>select sum(advance) from titles will return the total amount advanced to all authors </li></ul><ul><li>-------------------------- </li></ul><ul><li>95,400.00 </li></ul><ul><li>(1 row(s) affected ) </li></ul>
  24. 24. Avg <ul><li>Avg will return the average value in a column </li></ul><ul><li>select avg(price) from titles will return the average price of all books </li></ul><ul><li>-------------------------- </li></ul><ul><li>14.77 </li></ul><ul><li>(1 row(s) affected) </li></ul><ul><li>select avg(price) from titles where price > 10 will return the average price of the books over $10 </li></ul><ul><li>-------------------------- </li></ul><ul><li>17.94 </li></ul><ul><li>(1 row(s) affected) </li></ul>
  25. 25. Group by <ul><li>Data in a table is essentially stored randomly </li></ul><ul><li>We can impose one type of order on the result set with an order by </li></ul><ul><li>We can impose another type of order on a result set by using a group by clause </li></ul>
  26. 26. Group by <ul><li>The group by will order the data into groups that you specified and then return the set of rows that determine the groups </li></ul><ul><li>Duplicates are removed from this result set </li></ul><ul><li>In this way, a group by performs a similar operation to distinct </li></ul><ul><li>The distinct does not sort the data though </li></ul><ul><li>You still need to specify an order by clause to perform sorting </li></ul>
  27. 27. Group by <ul><li>select type from titles group by type </li></ul><ul><li>type </li></ul><ul><li>------------ </li></ul><ul><li>(null) </li></ul><ul><li>UNDECIDED </li></ul><ul><li>popular_comp </li></ul><ul><li>business </li></ul><ul><li>mod_cook </li></ul><ul><li>trad_cook </li></ul><ul><li>psychology </li></ul><ul><li>(7 row(s) affected) </li></ul><ul><li>select type from titles group by type order by 1 </li></ul><ul><li>type </li></ul><ul><li>------------ </li></ul><ul><li>(null) </li></ul><ul><li>UNDECIDED </li></ul><ul><li>business </li></ul><ul><li>mod_cook </li></ul><ul><li>popular_comp </li></ul><ul><li>psychology </li></ul><ul><li>trad_cook </li></ul><ul><li>(7 row(s) affected) </li></ul>
  28. 28. Group by and Nulls <ul><li>Nulls are treated specially by a group by clause </li></ul><ul><li>When a group by is being evaluated, all nulls are put in the same group </li></ul><ul><li>select type from titles group by type </li></ul><ul><li>type </li></ul><ul><li>------------ </li></ul><ul><li>(null) </li></ul><ul><li>UNDECIDED </li></ul><ul><li>business </li></ul><ul><li>mod_cook </li></ul><ul><li>popular_comp </li></ul><ul><li>psychology </li></ul><ul><li>trad_cook </li></ul><ul><li>(7 row(s) affected) </li></ul>
  29. 29. Group by and where <ul><li>You can use a where clause to limit the set of data that the group by will consider </li></ul><ul><li>select type from titles where advance > 5000 group by type </li></ul><ul><li>type </li></ul><ul><li>------------ </li></ul><ul><li>business </li></ul><ul><li>mod_cook </li></ul><ul><li>popular_comp </li></ul><ul><li>psychology </li></ul><ul><li>trad_cook </li></ul><ul><li>(5 row(s) affected) </li></ul>
  30. 30. Group by <ul><li>The true power of a group by comes from using it in conjunction with an aggregate </li></ul><ul><li>Suppose we wanted a count of each type of book </li></ul><ul><li>At first thought you might be tempted to do this: </li></ul><ul><li>select type,count(*) from titles </li></ul><ul><li>Msg 8118, Level 16, State 1 </li></ul><ul><li>Column 'titles.type' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause. </li></ul>
  31. 31. Group by <ul><li>This doesn’t quite get what we need </li></ul><ul><li>select type,count(*) from titles group by type </li></ul><ul><li>type </li></ul><ul><li>------------ ----------- </li></ul><ul><li>(null) 2 </li></ul><ul><li>UNDECIDED 1 </li></ul><ul><li>business 2 </li></ul><ul><li>mod_cook 2 </li></ul><ul><li>popular_comp 3 </li></ul><ul><li>psychology 5 </li></ul><ul><li>trad_cook 3 </li></ul><ul><li>(7 row(s) affected) </li></ul>
  32. 32. Group by <ul><li>One thing to remember is that if you use a group by with an aggregate, you must specify all nonaggregate columns in the group by clause </li></ul><ul><li>select city,state,count(*) from authors group by state will return a syntax error </li></ul><ul><li>Msg 8120, Level 16, State 1 </li></ul><ul><li>Column '' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. </li></ul><ul><li>select city,state,count(*) from authors group by state,city will return a result set </li></ul><ul><li>city state </li></ul><ul><li>-------------------- ----- ----------- </li></ul><ul><li>(null) MA 4 </li></ul><ul><li>Ann Arbor MI 1 </li></ul><ul><li>Berkeley CA 2 </li></ul><ul><li>Corvallis OR 1 </li></ul><ul><li>Covelo CA 1 </li></ul><ul><li>Gary IN 1 </li></ul><ul><li>... </li></ul><ul><li>(17 row(s) affected) </li></ul>
  33. 33. Group by <ul><li>You can not specify an aggregate in the group by clause </li></ul><ul><li>select count(*) from authors group by count(*) will return a syntax error </li></ul><ul><li>Msg 144, Level 15, State 1 </li></ul><ul><li>Cannot use an aggregate or a subquery in an expression used for the by-list of a GROUP BY clause. </li></ul>
  34. 34. Having <ul><li>The having clause works just like a where clause </li></ul><ul><li>There is a fundamental difference </li></ul><ul><li>The where clause defines the set of data the grouping is done on </li></ul><ul><li>The having defines which groups are going to be returned to the user </li></ul>
  35. 35. Having <ul><li>Having clause generally contain aggregates as part of the selection criteria </li></ul><ul><li>select pub_id,sum(advance) from titles group by pub_id having sum(advance) > 10000 </li></ul><ul><li>pub_id </li></ul><ul><li>------ -------------------------- </li></ul><ul><li>0736 24,400.00 </li></ul><ul><li>0877 41,000.00 </li></ul><ul><li>1389 30,000.00 </li></ul><ul><li>(3 row(s) affected) </li></ul><ul><li>This will return only the set of pub_ids that had an advance of more then $10000. </li></ul>
  36. 36. Having/Where <ul><li>select type,count(advance) from titles where advance > 10000 group by type,advance </li></ul><ul><li>select type,count(advance) from titles group by type,advance having advance > 10000 </li></ul>
  37. 37. Having/Where <ul><li>In both queries we want to know the types of those books with an advance > 10000, so why the different results </li></ul><ul><li>This is due to the way the where and having are applied </li></ul><ul><li>What happens is the data is selected based on the result set </li></ul><ul><li>It is then passed to the group by for grouping </li></ul><ul><li>Finally it goes to the having which returns the data requested. </li></ul>
  38. 38. Having/Where <ul><li>In the first query, only those rows that had an advance of > $10000 </li></ul><ul><li>The grouping is then applied to these rows </li></ul><ul><li>This was only 1 book for each of two groups (the where criteria) </li></ul>
  39. 39. Having/Where <ul><li>The having processes the aggregates and grouping first instead of the selection like where does </li></ul><ul><li>The having clause says give me the groups that have one or more books with an advance of > 10000 </li></ul>
  40. 40. Where/Having <ul><li>The concepts of where and having clauses can get confusing very quickly </li></ul><ul><li>The best way to get comfortable with them is to perform a few and observe the results </li></ul><ul><li>Then draw out each of the steps on paper until you can duplicate the result set </li></ul><ul><li>The book &quot;The Practical SQL Handbook&quot; has a good explanation on pages 180 - 185 </li></ul>
  41. 41. Compute <ul><li>Now that everything is about as clear as mud, we are going to introduce another clause that can be employed (compute) </li></ul><ul><li>In a nutshell, a compute is used to calculate grand summaries </li></ul><ul><li>select title_id,type,price from titles where type like '%cook%' compute avg(price) </li></ul><ul><li>title_id type price </li></ul><ul><li>-------- ------------ -------------------------- </li></ul><ul><li>MC2222 mod_cook 19.99 </li></ul><ul><li>MC3021 mod_cook 2.99 </li></ul><ul><li>TC3218 trad_cook 20.95 </li></ul><ul><li>TC4203 trad_cook 11.95 </li></ul><ul><li>TC7777 trad_cook 14.99 </li></ul><ul><li>avg </li></ul><ul><li>========================== </li></ul><ul><li>14.17 </li></ul><ul><li>(6 row(s) affected) </li></ul>
  42. 42. Compute by <ul><li>A compute by is used to subsummaries </li></ul><ul><li>This construct must be used with an order by </li></ul><ul><li>select title_id, type, price from titles where type like '%cook%' order by type compute avg(price) by type </li></ul><ul><li>title_id type price </li></ul><ul><li>-------- ------------ -------------------------- </li></ul><ul><li>MC2222 mod_cook 19.99 </li></ul><ul><li>MC3021 mod_cook 2.99 </li></ul><ul><li>avg </li></ul><ul><li>========================== </li></ul><ul><li>11.49 </li></ul><ul><li>title_id type price </li></ul><ul><li>-------- ------------ -------------------------- </li></ul><ul><li>TC3218 trad_cook 20.95 </li></ul><ul><li>TC4203 trad_cook 11.95 </li></ul><ul><li>TC7777 trad_cook 14.99 </li></ul><ul><li>avg </li></ul><ul><li>========================== </li></ul><ul><li>15.96 </li></ul><ul><li>(7 row(s) affected) </li></ul>
  43. 43. Compute/Compute by <ul><li>These can be used in the same query </li></ul><ul><li>select title_id,type,price from titles where type in ('business','mod_cook') order by type compute sum(price) by type compute sum(price) </li></ul><ul><li>title_id type price </li></ul><ul><li>-------- ------------ -------------------------- </li></ul><ul><li>BU2075 business 2.99 </li></ul><ul><li>BU7832 business 19.99 </li></ul><ul><li>sum </li></ul><ul><li>========================== </li></ul><ul><li>22.98 </li></ul><ul><li>title_id type price </li></ul><ul><li>-------- ------------ -------------------------- </li></ul><ul><li>MC2222 mod_cook 19.99 </li></ul><ul><li>MC3021 mod_cook 2.99 </li></ul><ul><li>sum </li></ul><ul><li>========================== </li></ul><ul><li>22.98 </li></ul><ul><li>sum </li></ul><ul><li>========================== </li></ul><ul><li>45.96 </li></ul><ul><li>(7 row(s) affected) </li></ul>
  44. 44. Compute/Compute by <ul><li>Restrictions </li></ul><ul><li>With a compute/computed by, you can only use columns in the select list </li></ul><ul><li>select title_id,type from titles…compute sum(price) would return a syntax error </li></ul><ul><li>You must order by the compute by column </li></ul><ul><li>You can use any aggregate except count(*) </li></ul>
  45. 45. Compute/Compute by <ul><li>Restrictions </li></ul><ul><li>Columns listed after the compute by must be in the identical order to or a subset of those listed after the order by </li></ul><ul><li>Expressions must be in the same left - right order </li></ul><ul><li>Compute by must start with the same expressions as listed after order by and not skip any expressions </li></ul>
  46. 46. Compute/Compute by <ul><li>Legal </li></ul><ul><li>order by a,b,c </li></ul><ul><li>compute by a,b,c </li></ul><ul><li>compute by a,b </li></ul><ul><li>compute avg(price) by a </li></ul><ul><li>Illegal </li></ul><ul><li>order by a,b,c </li></ul><ul><li>compute by b,a,c </li></ul><ul><li>compute by c,a </li></ul><ul><li>compute avg(price) by b </li></ul>
  47. 47. Unions <ul><li>There are times when we want to return two or more sets of data within a single select statement </li></ul><ul><li>Examples of this are combining data from two different tables when they have mutually exclusive criteria </li></ul><ul><li>To do this we use a union </li></ul>
  48. 48. <ul><li>select * from authors where state = 'CA' union select * from authors where state = 'MA' </li></ul><ul><li>au_lname state </li></ul><ul><li>---------------------------------------- ----- </li></ul><ul><li>Bennet CA </li></ul><ul><li>Carson CA </li></ul><ul><li>Dull CA </li></ul><ul><li>Green CA </li></ul><ul><li>Gringlesby CA </li></ul><ul><li>Hunter CA </li></ul><ul><li>Karsen CA </li></ul><ul><li>Locksley CA </li></ul><ul><li>MacFeather CA </li></ul><ul><li>McBadden CA </li></ul><ul><li>O'Leary CA </li></ul><ul><li>Straight CA </li></ul><ul><li>Stringer CA </li></ul><ul><li>White CA </li></ul><ul><li>Yokomoto CA </li></ul><ul><li>Burns MA </li></ul><ul><li>Johnson MA </li></ul><ul><li>Smithe MA </li></ul><ul><li>Smythe MA </li></ul><ul><li>(19 row(s) affected) </li></ul>Unions
  49. 49. Unions <ul><li>The only restrictions on unions are that the same number of columns must be in each separate result set and the datatypes must match </li></ul><ul><li>You can not union a select statement that returns 2 columns with a select that returns 3 columns </li></ul><ul><li>You also can't union a result set where the first column of one select is character data and the first column of another select is numeric data </li></ul>
  50. 50. <ul><li>Nulls are used to represent the nonexistence of data </li></ul><ul><li>A null doesn't equal another null </li></ul><ul><li>An order by can be used to sort the result set </li></ul><ul><li>The sort order is determined by the database's character set </li></ul><ul><li>To remove duplicate rows from a result set use distinct </li></ul><ul><li>You can perform calculations using aggregates count(*), sum,avg are the most common </li></ul><ul><li>You can group data together by using a group by </li></ul><ul><li>Group by can be combined with aggregates to perform sophisticated calculations </li></ul><ul><li>A having clause performs a restriction on a group by </li></ul><ul><li>Having and where behave differently due to the order they process the row selection </li></ul><ul><li>Compute can be used to calculate grand summaries </li></ul>Unit 3 Review
  51. 51. Unit 3 Review cont. <ul><li>Compute by can be used to calculate sub summaries </li></ul><ul><li>Unions allow us to combine multiple results sets and return them to the user in a group </li></ul>
  52. 52. Unit 3 Exercises <ul><li>Time allotted for exercises is 1 hour </li></ul>