Introduction to SQL



Joins

This document explains relating columns from two or more tables together.

Contents

  • Querying Two Tables
  • Join Operation
  • Joining Tables
  • Cartesian Product
  • Joins with Order By and Group By
  • Aliases
  • Joins with Additional Conditions (in where clause)
  • Joining More than two tables


  • Querying Two Tables

  • Join is the hallmark of the relational model
  • Combines tables by matching values from rows in each table

  • Join Operation

  • Relationship lines help find the join that will connect the tables
  • Multi-table operation
  • Part of the search condition must be a valid join
  • Columns with the same name must be preceded by a table name
  • Partial Syntax
        select [table.]column_name, [... ]
          from {table }{, table }[... ]
          [where search_conditions ]
    

  • Joining Tables

  • A row in one table matches a row in the other because the contents of columns from each table are equal
    Example:
        List the stores and the quantity each has ordered of each book
    
        select store.store_id, stor_name, title_id, qty
               from sales_detail, stores
               where salesdetail.stor_id = stores.stor_id
    

  • Cartesian Product

  • If you don't specify how to join rows from different tables, the system will assume you want to join every row in each table.

  • Joins with Order By and Group By

  • List total revenue for each book for each time the book was ordered.
        select titles.title_id, qty, price, total_price = price * qty
               from titles, sales_detail
               where titles.titles.id = sales_detail.titles_id
               order by price * qty
    
  • List number of books each store has ordered.
        select stor_name, salesdetail.stor_id, sum(qty)
               from sales_detail, stores
               where sales_detail.stor_id = stores.stor_id
               group by stor_name, salesdetail.stor_id
    

  • Aliases

  • To save typing a table name repeatedly it can be aliased within the query
  • The alias can be used everywhere in the query
        select pub_name, title_id
               from titles t, publishers p
               where t.pub_id = p.pub_id
               and price = $19.99
    

  • Joins with Additional Conditions (in where clause)

        select stores.stor_id, qty, title_id, stor_name
               from salesdetail sd, stores s
               where sd.stor_id = s.stor_id
               and qty < 35
    

    Joining More than two tables

  • From clause must list all the tables involved in the query
  • Where clause must list enough join conditions to connect all the tables
        select stor_name, title
               from stores s, salesdetail sd, titles t
               where s.stor_id = sd.stor_id
               and sd.title_id = t.title_id
    

  • [HOME] [TOP] [PREVIOUS] [NEXT]
    Darrick Jones <DARRICK_JONES@ccmail.sel.sony.com>

    Created: July 17, 1998