Published on

Introduction to Joins in SQL

Published in: Education, Business, 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


  1. 1. Joins CIS-182
  2. 2. Multi-Table Queries • Multi-table queries allow data from different tables to be combined and compared • Typically done by comparing a common value – Comparison done between like data types – May be primary key/foreign key fields but doesn’t have to be
  3. 3. Types of Multi-table Queries • Joins: combine columns from multiple tables – Combine publishers and titles to show title and publisher name • Unions: combine rows from different lists – Create a list of editors and authors who live in California • Subqueries: use the results of one query to determine result of a second query – Find all books that have a higher than average price
  4. 4. Joins • Inner Join: create a row for each match of values from two tables • Outer Join: include all rows from one table and any related data found in a second table • Cartesian Join: match each row in a table with every row in a second table – Also referred to as a cross join
  5. 5. Inner Joins • Most common kind of join • Get related data from two tables where values match – Also referred to as an equi-join • May be done using FROM clause or WHERE clause – Microsoft does not fully support WHERE clause in SQL Server 2008
  6. 6. Join With FROM • Use the keyword JOIN with or without INNER preceeding it • Specify the fields to compare using ON • Field names that are not unique must be qualified by the table they’re in
  7. 7. From Clause Examples SELECT * FROM Publishers JOIN Titles ON Publishers.pub_id = Titles.pub_id SELECT * FROM Publishers INNER JOIN Titles ON Publishers.pub_id = Titles.pub_id
  8. 8. Join With WHERE • List tables in FROM clause, separated by comma • WHERE clause defines the fields to compare
  9. 9. Where Clause Example SELECT * FROM Publishers, Titles WHERE Publishers.pub_id = Titles.pub_id
  10. 10. Outer Joins • Used when rows from one table should be part of the result even if there are no related rows in a second table – Create a list of all publishers, including any titles the publisher has published • Direction must be specified – Left/Right specify which table has the rows which should always be included – Full specifies that rows from both tables should be included even if no match
  11. 11. Outer Join Example • Include all publishers, even if they haven’t published a book: SELECT * FROM Publishers LEFT OUTER JOIN Titles ON Publishers.pub_id = Titles.pub_id
  12. 12. Cartesian Join • Match each row from table 1 with every row from table 2 – Result is (table 1 row count)*(table 2 row count) • May be done using CROSS JOIN SELECT * FROM Publishers, Titles SELECT * FROM Publishers CROSS JOIN Titles