Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Intro to tsql unit 4


Published on

Published in: Business, Technology
  • Be the first to comment

  • Be the first to like this

Intro to tsql unit 4

  1. 1. Introduction To SQL Unit 4 Modern Business Technology Introduction To TSQL Unit 4 Developed by Michael Hotek
  2. 2. Unit 4 <ul><li>Goals </li></ul><ul><li>Primary keys </li></ul><ul><li>Foreign keys </li></ul><ul><li>Joining tables </li></ul><ul><li>Sub-selects </li></ul><ul><li>Advantages/disadvantages of joins and sub-selects </li></ul>
  3. 3. Relationships <ul><li>A database derives its usefulness from containing a group of tables that have some relationship to each other </li></ul><ul><li>An entity is a person, place, or thing of importance to an organization </li></ul><ul><li>An entity generally becomes a table </li></ul><ul><li>Relationships are the connections between tables </li></ul><ul><li>Relationships are usually implemented as keys in a database design </li></ul>
  4. 4. Relationships <ul><li>For example take the titles and publishers table </li></ul><ul><li>Every publisher publishes a title </li></ul><ul><li>And every title has a publisher </li></ul><ul><li>This relationship is implemented by means of the key pub_id </li></ul>
  5. 5. Relationships <ul><li>Relationships come in three different varieties </li></ul><ul><li>One to one </li></ul><ul><ul><li>One row in a table is related to exactly one row in another table </li></ul></ul><ul><li>One to many </li></ul><ul><ul><li>One row in a table is related to one or more rows in another table </li></ul></ul><ul><li>Many to many </li></ul><ul><ul><li>Many rows in a table are related to one or more rows in another table </li></ul></ul>
  6. 6. Relationships <ul><li>A many to many relationship is extremely poor database design </li></ul><ul><li>This type of relationship can cause a large amount of confusion </li></ul><ul><li>The problem is that many to many relationships do exist and must be stored in a database </li></ul><ul><li>This is usually resolved into multiple one to many relationships also known as an intersection table </li></ul>
  7. 7. Relationships <ul><li>An intersection table is an artificial construct that is commonly used in RDBMSs </li></ul><ul><li>It does not have any physical meaning, but instead serves to break up a many to many relationship </li></ul><ul><li>The titleauthor table is an example of an intersection table </li></ul>
  8. 8. Relationships <ul><li>Relationships are implemented in a database as keys </li></ul><ul><li>Keys are a logical construct; they are not a physical part of the database </li></ul><ul><li>This means that a key does not represent any physically quantifiable item </li></ul><ul><li>You will generally see numbers used as keys in a database (au_id, pub_id, stor_id) </li></ul>
  9. 9. Primary Key <ul><li>A primary key is a special type of key that consists of one or more columns that uniquely identify a row </li></ul><ul><li>Primary keys must be unique and can not contain null values </li></ul><ul><li>A table will only have one primary key </li></ul><ul><li>A primary key will reside on the one side of a 1 - N relationship </li></ul>
  10. 10. Primary Key <ul><li>pub_id is the primary key for the publishers table </li></ul><ul><li>This will uniquely identify each publisher in the table </li></ul><ul><li>We do not use the publisher's name, because this could be the same as another publisher </li></ul><ul><li>Also, it is easy to control data input to ensure it is valid </li></ul><ul><li>It is much easier to check 4 digits than 40 characters. Also a name can be null. </li></ul>
  11. 11. Foreign Key <ul><li>A foreign key is one or more columns that refer to a primary key of another table </li></ul><ul><li>pub_id is the primary key of publishers </li></ul><ul><li>pub_id is a foreign key in titles </li></ul><ul><li>Example: </li></ul><ul><li>A publisher can publish many titles, but a title must have a publisher </li></ul><ul><li>This relationship is shown by the primary key of the publishers table being stored with the title that publisher published. </li></ul>
  12. 12. Composite Keys <ul><li>A primary key and a foreign key can consist of more than one column </li></ul><ul><li>When a key contains more than one column, it is known as a composite key </li></ul><ul><li>The primary key of the titleauthor table is a composite (au_id,title_id) </li></ul>
  13. 13. Indexes <ul><li>A discussion of indexes is well beyond the scope of this course, there are a few naming items that can be noted </li></ul><ul><li>Keys will be implemented in a database as an object called an index </li></ul><ul><li>An index could be a primary key, a foreign key, or neither </li></ul><ul><li>A primary key is the same as a primary index or unique index </li></ul><ul><li>A foreign key is the same as a foreign index </li></ul>
  14. 14. Joins <ul><li>Up to this point we have confined our queries to a single table </li></ul><ul><li>While this is done primarily for retrieving data into transaction processing applications, it doesn't represent a real world application of data querying </li></ul><ul><li>All of the data in a database is segmented into tables and we generally need data from more than one table to show what we need </li></ul><ul><li>To accomplish this, we use a join </li></ul>
  15. 15. Joins <ul><li>You will notice that there is no such thing as a join clause in our SQL syntax </li></ul><ul><li>A join is simply a where clause </li></ul><ul><li>A join is generally constructed between one primary key and another primary key or between a primary key and a foreign key </li></ul><ul><li>( Discussion of PK/FK symbols on the ER Diagram) </li></ul>
  16. 16. Joins <ul><li>Suppose we want to view a list of sales for each store </li></ul><ul><li>We could simply do the following: </li></ul><ul><li>select * from sales </li></ul><ul><li>stor_id ord_num ord_date qty payterms... </li></ul><ul><li>------- ------------ ---------------------- ------ -------- </li></ul><ul><li>6380 6871 Sep 14 1994 12:00AM 5 Net 60... </li></ul><ul><li>6380 722a Sep 13 1994 12:00AM 3 Net 60... </li></ul><ul><li>7066 A2976 May 24 1993 12:00AM 50 Net 30... </li></ul><ul><li>7066 QA7442.3 Sep 13 1994 12:00AM 75 ON invoice </li></ul><ul><li>7067 D4482 Sep 14 1994 12:00AM 10 Net 60... </li></ul><ul><li>7067 P2121 Jun 15 1992 12:00AM 40 Net 30... </li></ul><ul><li>7067 P2121 Jun 15 1992 12:00AM 20 Net 30... </li></ul><ul><li>7067 P2121 Jun 15 1992 12:00AM 20 Net 30... </li></ul><ul><li>7131 N914008 Sep 14 1994 12:00AM 20 Net 30... </li></ul><ul><li>7131 N914014 Sep 14 1994 12:00AM 25 Net 30... </li></ul><ul><li>7131 P3087a May 29 1993 12:00AM 20 Net 60... </li></ul><ul><li>... </li></ul><ul><li>(22 row(s) affected) </li></ul><ul><li>But, the stor_id is meaningless to us </li></ul>
  17. 17. Joins <ul><li>What we want to see is the store name, city, and state along with the sales for each order </li></ul><ul><li>select stor_name,ord_num,qty from stores,sales where stores.stor_id = sales.stor_id </li></ul><ul><li>stor_name ord_num qty </li></ul><ul><li>---------------------------------------- -------------------- ------ </li></ul><ul><li>Eric the Read Books 6871 5 </li></ul><ul><li>Eric the Read Books 722a 3 </li></ul><ul><li>Barnum's A2976 50 </li></ul><ul><li>Barnum's QA7442.3 75 </li></ul><ul><li>News & Brews D4482 10 </li></ul><ul><li>News & Brews P2121 40 </li></ul><ul><li>News & Brews P2121 20 </li></ul><ul><li>News & Brews P2121 20 </li></ul><ul><li>Doc-U-Mat: Quality Laundry and Books N914008 20 </li></ul><ul><li>Doc-U-Mat: Quality Laundry and Books N914014 25 </li></ul><ul><li>Doc-U-Mat: Quality Laundry and Books P3087a 20 </li></ul><ul><li>Doc-U-Mat: Quality Laundry and Books P3087a 25 </li></ul><ul><li>Doc-U-Mat: Quality Laundry and Books P3087a 15 </li></ul><ul><li>Doc-U-Mat: Quality Laundry and Books P3087a 25 </li></ul><ul><li>Fricative Bookshop QQ2299 15 </li></ul><ul><li>Fricative Bookshop TQ456 10 </li></ul><ul><li>Fricative Bookshop X999 35 </li></ul><ul><li>Bookbeat 423LL922 15 </li></ul><ul><li>... </li></ul><ul><li>(22 row(s) affected) </li></ul>
  18. 18. Joins <ul><li>What does this mean? </li></ul><ul><li>The select clause simply designates which columns we want to see. If we were retrieving a column that had the same name in the two tables, we would have to specify which table the data was coming from </li></ul><ul><li>select stores.stor_id,stor_name, ord_num, qty </li></ul><ul><li>from stores,sales </li></ul><ul><li>where stores.stor_id = sales.stor_id </li></ul>
  19. 19. Joins <ul><li>From clause </li></ul><ul><li>We are retrieving data from more than one table, so each table must be specified in the from clause </li></ul><ul><li>The from clause can be seen as the main driver of a SQL statement </li></ul><ul><li>If the table isn’t in the from clause, none of it's columns can be used in any other clause </li></ul>
  20. 20. Joins <ul><li>The where clause </li></ul><ul><li>where stores.stor_id = sales.stor_id </li></ul><ul><li>This tells the DBMS to take the first store ID in the stores table and add the data from the corresponding store ID in the sales table to the data retrieved from the stores table </li></ul><ul><li>It then continues with the second store ID, etc. until it reaches the end of the table </li></ul>
  21. 21. Joins <ul><li>A join can be seen as a special type of selection criteria. </li></ul><ul><li>If there is a stor_id in the stores table that does not exist in the sales table, the data for that particular store will not be returned </li></ul><ul><li>You can also add additional selection criteria </li></ul><ul><li>select stores.stor_id,stor_name,city, state,ord_num,qty </li></ul><ul><li>from stores,sales </li></ul><ul><li>where stores.stor_id = sales.stor_id and state = 'CA' </li></ul>
  22. 22. Joins <ul><li>As we have seen, you can specify just those columns that you want to see </li></ul><ul><li>For instance we are just concerned with the quantity of sales in CA </li></ul><ul><li>select sum(qty) from stores,sales where stores.stor_id = sales.stor_id and state = 'CA' </li></ul><ul><li>----------- </li></ul><ul><li>275 </li></ul><ul><li>(1 row(s) affected) </li></ul>
  23. 23. <ul><li>The type of join we have examined so far is also referred to as an equi-join or an inner join </li></ul><ul><li>In the case of stores and sales, we could have a store that doesn't have any sales </li></ul><ul><li>If we use the equi-join, we will not see these stores that do not have any sales </li></ul><ul><li>So, how do we get the list of sales for all stores regardless of whether they have any sales </li></ul>Joins
  24. 24. Outer Joins <ul><li>We accomplish this via an outer join </li></ul><ul><li>select stores.stor_id,stor_name, ord_num, qty from stores,sales where stores.stor_id *= sales.stor_id </li></ul><ul><li>stor_id stor_name ord_num qty </li></ul><ul><li>------- ------------------------------------ -------------------- ---- </li></ul><ul><li>6380 Eric the Read Books 6871 5 </li></ul><ul><li>6380 Eric the Read Books 722a 3 </li></ul><ul><li>7066 Barnum's A2976 50 </li></ul><ul><li>7066 Barnum's QA7442.3 75 </li></ul><ul><li>7067 News & Brews D4482 10 </li></ul><ul><li>7067 News & Brews P2121 40 </li></ul><ul><li>7067 News & Brews P2121 20 </li></ul><ul><li>7067 News & Brews P2121 20 </li></ul><ul><li>7131 Doc-U-Mat: Quality Laundry and Books N914008 20 </li></ul><ul><li>7131 Doc-U-Mat: Quality Laundry and Books N914014 25 </li></ul><ul><li>7131 Doc-U-Mat: Quality Laundry and Books P3087a 20 </li></ul><ul><li>7131 Doc-U-Mat: Quality Laundry and Books P3087a 25 </li></ul><ul><li>7131 Doc-U-Mat: Quality Laundry and Books P3087a 15 </li></ul><ul><li>7131 Doc-U-Mat: Quality Laundry and Books P3087a 25 </li></ul><ul><li>7896 Fricative Bookshop QQ2299 15 </li></ul><ul><li>7896 Fricative Bookshop TQ456 10 </li></ul><ul><li>7896 Fricative Bookshop X999 35 </li></ul><ul><li>8042 Bookbeat 423LL922 15 </li></ul><ul><li>8042 Bookbeat 423LL930 10 </li></ul><ul><li>8042 Bookbeat 756756 5 </li></ul><ul><li>8042 Bookbeat P723 25 </li></ul><ul><li>8042 Bookbeat QA879.1 30 </li></ul><ul><li>(22 row(s) affected) </li></ul>
  25. 25. Outer Joins <ul><li>Notice the use of the asterisk (*) </li></ul><ul><li>where stores.stor_id *= sales.stor_id </li></ul><ul><li>This tells the DBMS to return all of the rows in the stores table with the corresponding data in the sales table and do not drop any store IDs that are not in the sales table </li></ul><ul><li>Note: The use of an asterisk to designate an outer join is used in SQL Server (Sybase and MS) most other DBMSs support a slightly different syntax as does the ANSI-92 standard </li></ul>
  26. 26. Outer Joins <ul><li>Outer joins come in three different flavors </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>A left outer join is the same thing as a right outer join except for the order </li></ul><ul><li>Left: stores.stor_id *= sales.stor_id </li></ul><ul><li>Right: sales.stor_id =* stores.stor_id </li></ul><ul><li>Every left outer join can also be expressed as a right outer join and vice versa </li></ul>
  27. 27. Full Outer Join <ul><li>A full outer join is included here for completeness </li></ul><ul><li>You should use a full outer join ONLY under very specific circumstances </li></ul><ul><li>A full outer join will produce a cross product of the two tables </li></ul><ul><li>If you have one table with 100 rows and another with 1000 rows, a full outer join will produce a result set of 100,000 rows </li></ul>
  28. 28. Full Outer Join <ul><li>This is because with a full outer join, you are telling the database to give every combination of rows possible </li></ul><ul><li>i.e. Each row is matched to every row in the other table </li></ul><ul><li>This type is query will almost never be preformed and should be avoided at all costs. </li></ul><ul><li>The first time you inadvertently fire one of these off, you will get a rather angry call from your DBA </li></ul>
  29. 29. Subqueries <ul><li>Subqueries are simply a SQL statement nested inside of another SQL statement </li></ul><ul><li>The most common place to do this is in a where or having clause. </li></ul><ul><li>select [distinct] select_list </li></ul><ul><li>from table_list </li></ul><ul><li>where {expression {[not] in | comparison [any|all]}|[not] exists} </li></ul><ul><li>(select [distinct] subquery_select_list from table_list where conditions) </li></ul><ul><li>[group by group_by_list] </li></ul><ul><li>[having conditions] </li></ul><ul><li>[order by order_by_list] </li></ul>
  30. 30. Subqueries <ul><li>Subqueries come in two basic kinds: correlated and noncorrelated </li></ul><ul><li>A noncorrelated subquery is one in which the inner query is independent, gets evaluated first, and passes it’s result set back to the outer query </li></ul><ul><li>A correlated subquery is one in which the inner query is dependent upon the results from the outer query </li></ul>
  31. 31. Subqueries <ul><li>Below are examples of these two kinds </li></ul><ul><li>noncorrelated: </li></ul><ul><li>select pub_name from publishers </li></ul><ul><li>where pub_id in (select pub_id from titles </li></ul><ul><li>where type = 'business') </li></ul><ul><li>correlated: </li></ul><ul><li>select pub_name from publishers p </li></ul><ul><li>where 'business' in (select type from titles where oub_id = p.pub_id) </li></ul><ul><li>As is the case with most of the subqueries, you can also express them as a join </li></ul>
  32. 32. Subqueries <ul><li>Subqueries also come in three different types: </li></ul><ul><li>They return zero or more items </li></ul><ul><li>They return exactly one item </li></ul><ul><li>They test for existence of a value </li></ul><ul><li>If you have a subquery of the first type it must be preceeded by an IN. where column = (select…) will return an error if the subquery returns more than one item </li></ul>
  33. 33. Noncorrelated Subqueries <ul><li>At a conceptual level, a noncorrelated subquery is executed in two parts. </li></ul><ul><li>First the inner query is executed </li></ul><ul><li>It then passes its results back to the outer query which then finds the rows that match the list passed back </li></ul><ul><li>The column names are resolved implicitly based upon the from clause of the corresponding query. You can always explicitly define the table name. </li></ul><ul><li>This is recommended for complex subqueries </li></ul>
  34. 34. Correlated Subqueries <ul><li>Processing of a correlated subquery is much more complicated, but these can handle queries you can't easily do with noncorrelated subqueries or joins </li></ul><ul><li>A correlated subquery depends on data from the outer query </li></ul><ul><li>The inner query will execute once for each row in the outer query </li></ul>
  35. 35. Correlated Subqueries <ul><li>The outer query retrieves the first row of data and passes the data values to the inner query </li></ul><ul><li>The inner query finds all rows that match the data passed from the outer query </li></ul><ul><li>Finally the rows from the inner query are checked against the conditions in the outer query </li></ul><ul><li>If one or more rows match the conditions, the data corresponding to that row will be returned to the user </li></ul>
  36. 36. Joins or Subqueries <ul><li>select distinct pub_name from publishers, authors where = </li></ul><ul><li>AND </li></ul><ul><li>select pub_name from publishers where city in (select city from authors) </li></ul><ul><li>will return the same results </li></ul><ul><li>But if you want data from both the publishers and authors tables, you must use a join. </li></ul><ul><li>select pub_name,au_fname,au_lname </li></ul><ul><li>from publishers,authors </li></ul><ul><li>where = </li></ul>
  37. 37. Joins or Subqueries <ul><li>select au_lname,au_fname,city from authors where city in (select city from authors where au_fname = 'Dick' and au_lname = 'Straight') </li></ul><ul><li>can also be expressed as </li></ul><ul><li>select au_lname,au_fname,city from authors a1, authors a2 where = and a2.au_fname = 'Dick' and a2.au_lname = 'Straight' </li></ul><ul><li>This is referred to as a self join </li></ul>
  38. 38. Joins or Subqueries <ul><li>Whether you use joins or subqueries is usually a matter of choice </li></ul><ul><li>Most joins can be expressed as subqueries and vice versa </li></ul><ul><li>Calculating an aggregate and using this in the selection criteria is an advantage of subqueries </li></ul><ul><li>select title,price from titles </li></ul><ul><li>where price = (select min(price) from titles) </li></ul><ul><li>Displaying data from multiple tables is usually done with a join </li></ul>
  39. 39. Common Restrictions <ul><li>The select list of a inner query introduced by an IN can have only one column. This column must also be join compatible with the column in the where clause of the outer query </li></ul><ul><li>Subqueries introduced by an unmodified comparison operator (not followed by ANY or ALL) can not include a group by or having clause unless this will force the inner query to return a single value </li></ul><ul><li>Subqueries can not manipulate their results internally. i.e. They can not contain an order by or the keyword INTO </li></ul>
  40. 40. Any and All <ul><li>You use the ANY and ALL keywords with a comparison operator in a subquery </li></ul><ul><li>> ALL means greater than every value in the results of the inner query (> maximum value) </li></ul><ul><li>> ANY means greater than any value in the results of the inner query (> minimum value) </li></ul>
  41. 41. Any and All <ul><li>ALL Results ANY Results </li></ul><ul><li>> all (1,2,3) > 3 >any (1,2,3) > 1 </li></ul><ul><li>< all (1,2,3) < 1 < any (1,2,3) < 3 </li></ul><ul><li>= all (1,2,3) = 1 and =2 and =3 = any (1,2,3) =1 or =2 or =3 </li></ul><ul><li>select title from titles where advance > all </li></ul><ul><li>(select advance from publishers,titles where titles.pub_id = publishers.pub_id and pub_name = 'New Age Books') </li></ul><ul><li>title </li></ul><ul><li>-------------------------------------------------------------------------- </li></ul><ul><li>The Busy Executive's Database Guide </li></ul><ul><li>Cooking with Computers: Surreptitious Balance Sheets </li></ul><ul><li>You Can Combat Computer Stress! </li></ul><ul><li>Straight Talk About Computers </li></ul><ul><li>Silicon Valley Gastronomic Treats </li></ul><ul><li>The Gourmet Microwave </li></ul><ul><li>The Psychology of Computer Cooking </li></ul><ul><li>But Is It User Friendly? </li></ul><ul><li>Secrets of Silicon Valley </li></ul><ul><li>Net Etiquette </li></ul><ul><li>Computer Phobic AND Non-Phobic Individuals: Behavior Variations </li></ul><ul><li>Is Anger the Enemy? </li></ul><ul><li>Life Without Fear </li></ul><ul><li>Prolonged Data Deprivation: Four Case Studies </li></ul><ul><li>... </li></ul><ul><li>(18 row(s) affected) </li></ul>
  42. 42. Exists <ul><li>The last type of subquery is used to test for the existence of something </li></ul><ul><li>To find all of the publishers who publish business books we would do the following: </li></ul><ul><li>select distinct pub_name from publishers where exists (select 1 from titles where pub_id = publishers.pub_id and type = 'business') </li></ul><ul><li>pub_name </li></ul><ul><li>---------------------------------------- </li></ul><ul><li>Algodata Infosystems </li></ul><ul><li>New Moon Books </li></ul><ul><li>(2 row(s) affected) </li></ul>
  43. 43. Additional Restrictions <ul><li>A subquery that test for existence will either contain one column or an asterisk in the select list. It makes no sense to include a column list, because this type of query simply tests to see if a row exists and does not return any data </li></ul>
  44. 44. <ul><li>A subquery may contain another subquery </li></ul><ul><li>In fact you can nest as many levels as you need. However, for most applications more than four levels is an indication of poor database design </li></ul><ul><li>select au_lname,au_fname from authors where au_id in (select au_id from titleauthors where title_id in (select title_id from titles where type = 'popular_comp')) </li></ul><ul><li>This will return the list of authors who have written at least one popular computing book </li></ul>Nesting Subqueries
  45. 45. Unit 4 Review <ul><li>A relationships are connections between tables </li></ul><ul><li>A primary key is that set of columns that define a unique row </li></ul><ul><li>You can have only one primary key per table </li></ul><ul><li>A foreign key is one or more columns that refer to a primary key of the same or another table </li></ul><ul><li>You can have up to 255 foreign keys per table </li></ul><ul><li>A composite key consists of more than one column </li></ul><ul><li>Joins are used when you need to retrieve data from more than one table </li></ul><ul><li>The two kinds of joins are: equijoin and outer join </li></ul><ul><li>An outer join comes in three flavors: left, right, full </li></ul><ul><li>A full outer join will produce the cross product of the two tables </li></ul><ul><li>Subqueries are nested SQL statements </li></ul>
  46. 46. Unit 4 Review <ul><li>Subqueries come in two kinds: correlated and noncorrelated </li></ul><ul><li>Subqueries are also of three different types: return exactly one item, return zero or more items, and test for existence </li></ul><ul><li>Most joins can be written as a subquery and vice versa </li></ul><ul><li>A subquery is used when you need to include an aggregate in the where conditions </li></ul><ul><li>A join is used when you want to retrieve data from more than one table </li></ul><ul><li>All means every value (> all means greater than every value) </li></ul><ul><li>Any means at least one value (> any means greater than at least one value) </li></ul><ul><li>Exists allows us to test to see if a value exists </li></ul><ul><li>Exists queries are used with correlated subqueries </li></ul><ul><li>Subqueries can be nested any number of levels </li></ul>
  47. 47. Unit 4 Exercises <ul><li>Time allotted for exercises is 1 hour </li></ul>