Skip to main content
Engineering LibreTexts

16.6.5: Joining Tables

  • Page ID
    92231
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    Joining two or more tables is the process of comparing the data in specified columns and using the comparison results to form a new table from the rows that qualify. A join statement:

    • Specifies a column from each table
    • Compares the values in those columns row by row
    • Combines rows with qualifying values into a new row

    Although the comparison is usually for equality – values that match exactly – other types of joins can also be specified. All the different joins such as inner, left (outer), right (outer), and cross join will be described below.

    Inner join

    An inner join connects two tables on a column with the same data type. Only the rows where the column values match are returned; unmatched rows are discarded.

    Example #1

    SELECT jobs.job_id, job_desc
    FROM jobs
    INNER JOIN Employees ON employee.job_id = jobs.job_id
    WHERE jobs.job_id < 7

    Example #2

    SELECT authors.au_fname, authors.au_lname, books.royalty, title
    FROM authorsINNER JOIN titleauthor ON authors.au_id=titleauthor.au_id
    INNER JOIN books ON titleauthor.title_id=books.title_id
    GROUP BY authors.au_lname, authors.au_fname, title, title.royalty
    ORDER BY authors.au_lname

    Left outer join

    left outer join specifies that all left outer rows be returned. All rows from the left table that did not meet the condition specified are included in the results set, and output columns from the other table are set to NULL.

    This first example uses the new syntax for a left outer join.

    SELECT publishers.pub_name, books.title
    FROM Publishers
    LEFT OUTER JOIN Books On publishers.pub_id = books.pub_id

    This is an example of a left outer join using the old syntax.

    SELECT publishers.pub_name, books.title
    FROM Publishers, Books
    WHERE publishers.pub_id *= books.pub_id

    Right outer join

    right outer join includes, in its result set, all rows from the right table that did not meet the condition specified. Output columns that correspond to the other table are set to NULL.

    Below is an example using the new syntax for a right outer join.

    SELECT titleauthor.title_id, authors.au_lname, authors.au_fname
    FROM titleauthor
    RIGHT OUTER JOIN authors ON titleauthor.au_id = authors.au_id
    ORDERY BY au_lname

    This second example show the old syntax used for a right outer join.

    SELECT titleauthor.title_id, authors.au_lname, authors.au_fname
    FROM titleauthor, authors
    WHERE titleauthor.au_id =* authors.au_id
    ORDERY BY au_lname

    Full outer join

    full outer join specifies that if a row from either table does not match the selection criteria, the row is included in the result set, and its output columns that correspond to the other table are set to NULL.

    Here is an example of a full outer join.

    SELECT books.title, publishers.pub_name, publishers.province
    FROM Publishers
    FULL OUTER JOIN Books ON books.pub_id = publishers.pub_id
    WHERE (publishers.province <> “BC” and publishers.province <> “ON”)
    ORDER BY books.title_id

     Cross join

    cross join is a product combining two tables. This join returns the same rows as if no WHERE clause were specified. For example:

    SELECT au_lname, pub_name,
    FROM Authors CROSS JOIN Publishers

     

    Key Terms

    aggregate function: returns summary values

    ASC: ascending order

    conversion function: transforms one data type to another

    cross join: a product combining two tables

    date function: displays information about dates and times

    DELETE statement: removes rows from a record set

    DESC: descending order

    full outer join: specifies that if a row from either table does not match the selection criteria

    GROUP BY: used to create one output row per each group and produces summary values for the selected columns

    inner join: connects two tables on a column with the same data type

    INSERT statement: adds rows to a table

    left outer join: specifies that all left outer rows be returned

    mathematical function: performs operations on numeric data

    right outer join: includes all rows from the right table that did not meet the condition specified

    SELECT statement: used to query data in the database

    string function: performs operations on character strings, binary data or expressions

    system function: returns a special piece of information from the database

    text and image functions: performs operations on text and image data

    UPDATE statement: changes data in existing rows either by adding new data or modifying existing data

    wildcard:  allows the user to match fields that contain certain letters.

     

     

    Exercises

     

    For questions 1 to 18 use the PUBS sample database created by Microsoft. To download the script to generate this database please go to the following site: http://www.microsoft.com/en-ca/download/details.aspx?id=23654.

    1. Display a list of publication dates and titles (books) that were published in 2011.
    2. Display a list of titles that have been categorized as either traditional or modern cooking. Use the Books table.
    3. Display all authors whose first names are five letters long.
    4. Display from the Books table: type, price, pub_id, title about the books put out by each publisher. Rename the column type with ”Book Category.” Sort by type (descending) and then price (ascending).
    5. Display title_id, pubdate and pubdate plus three days, using the Books table.
    6. Using the datediff and getdate function determine how much time has elapsed in months since the books in the Books table were published.
    7. List the title IDs and quantity of all books that sold more than 30 copies.
    8. Display a list of all last names of the authors who live in Ontario (ON) and the cities where they live.
    9. Display all rows that contain a 60 in the payterms field. Use the Sales table.
    10. Display all authors whose first names are five letters long , end in O or A, and start with M or P.
    11. Display all titles that cost more than $30 and either begin with T or have a publisher ID of  0877.
    12. Display from the Employees table the first name (fname), last name (lname), employe ID(emp_id) and job level (job_lvl) columns for those employees with a job level greater than 200; and rename the column headings to:  “First Name,” “Last Name,” “IDENTIFICATION#” and “Job Level.”
    13. Display the royalty, royalty plus 50% as “royalty plus 50” and title_id. Use the Roysched table.
    14. Using the STUFF function create a string “12xxxx567” from the string “1234567.”
    15. Display the first 40 characters of each title, along with the average monthly sales for that title to date (ytd_sales/12). Use the Title table.
    16. Show how many books have assigned prices.
    17. Display a list of cookbooks with the average cost for all of the books of each type. Use the GROUP BY.

     

     

    Advanced Questions (Union, Intersect, and Minus)

     

    1. The relational set operators UNION, INTERSECT and MINUS work properly only if the relations are union-compatible. What does union-compatible mean, and how would you check for this condition?
    2. What is the difference between UNION and UNION ALL? Write the syntax for each.
    3. Suppose that you have two tables, Employees and Employees_1. The Employees table contains the records for three employees: Alice Cordoza, John Cretchakov, and Anne McDonald. The Employees_1 table contains the records for employees: John Cretchakov and Mary Chen. Given that information, what is the query output for the UNION query? List the query output.
    4. Given the employee information in question 3, what is the query output for the UNION ALL query? List the query output.
    5. Given the employee information in question 3, what is the query output for the INTERSECT query? List the query output.
    6. Given the employee information in question 3, what is the query output for the EXCEPT query? List the query output.
    7. What is a cross join? Give an example of its syntax.
    8. Explain these three join types:
      1. left outer join
      2. right outer join
      3. full outer join
    9. What is a subquery, and what are its basic characteristics?
    10. What is a correlated subquery? Give an example.
    11. Suppose that a Product table contains two attributes, PROD_CODE and VEND_CODE. The values for the PROD_CODE are: ABC, DEF, GHI and JKL. These are matched by the following values for the VEND_CODE:  125, 124, 124 and 123, respectively (e.g., PROD_CODE value ABC corresponds to VEND_CODE value 125). The Vendor table contains a single attribute, VEND_CODE, with values 123, 124, 125 and 126. (The VEND_CODE attribute in the Product table is a foreign key to the VEND_CODE in the Vendor table.)
    12. Given the information in question 11, what would be the query output for the following? Show values.
      1. A UNION query based on these two tables
      2. A UNION ALL query based on these two tables
      3. An INTERSECT query based on these two tables
      4. A MINUS query based on these two tables

     

     

    Advanced Questions (Using Joins)

     

    1. Display a list of all titles and sales numbers in the Books and Sales tables, including titles that have no sales. Use a join.
    2. Display a list of authors’ last names and all associated titles that each author has published sorted by the author’s last name. Use a join.  Save it as a view named: Published Authors.
    3. Using a subquery, display all the authors (show last and first name, postal code) who receive a royalty of 100% and live in Alberta. Save it as a view titled: AuthorsView. When creating the view, rename the author’s last name and first name as ‘Last Name’ and ‘First Name’.
    4. Display the stores that did not sell the title Is Anger the Enemy?
    5. Display a list of store names for sales after 2013 (Order Date is greater than 2013).  Display store name and order date.
    6. Display a list of titles for books sold in store name “News & Brews.”  Display store name, titles and order dates.
    7. List total sales (qty) by title. Display total quantity and title columns.
    8. List total sales (qty) by type. Display total quantity and type columns.
    9. List total sales (qty*price) by type. Display total dollar value and type columns.
    10. Calculate the total number of types of books by publisher. Show publisher name and total count of types of books for each publisher.
    11. Show publisher names that do not have any type of book.  Display publisher name only.

    16.6.5: Joining Tables is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.

    • Was this article helpful?