Course Resources

Search

Search IconIcon to open search

Last updated Nov 17, 2024

# Filter and Sort with JOINs

# Using WHERE and ORDER BY with JOINs

We can still utilize the clauses from previous lessons to filter and sort on joined data.

For this example, we’ll use the Authors and Books tables with a one-to-many relationship. Each author can write multiple books, but each book has only one author.

# Authors Table:

AuthorIDAuthorName
1J.K. Rowling
2George Orwell
3Leo Tolstoy

# Books Table:

BookIDTitleAuthorID
101Harry Potter1
10219842
103Animal Farm2
104War and Peace3
105Anna Karenina3

# SQL JOIN with Filter and Sort

Create a query that joins these tables and:

  1. Filters to show only books written by a specific author (e.g., George Orwell).
  2. Sorts the results by the book’s title.
1
2
3
4
SELECT Books.Title, Authors.AuthorName FROM Books
JOIN Authors ON Books.AuthorID = Authors.AuthorID
WHERE Authors.AuthorName = 'George Orwell'
ORDER BY Books.Title;
# Expected Output:
TitleAuthorName
Anna KareninaLeo Tolstoy
War and PeaceLeo Tolstoy

# Explanation:

  1. SELECT Clause: Retrieves the book titles and their corresponding author names.
  2. JOIN Operation: Joins the Books and Authors tables using the AuthorID as the common field.
  3. WHERE Clause: Filters the results to include only those books written by ‘Leo Tolstoy’.
  4. ORDER BY Clause: Sorts the resulting list of books by their titles in ascending order.

JOIN must come before our WHERE and ORDER BY clauses because we need to have access to both the AuthorName and Title in order to filter and sort them.

# Practice Questions

  1. Write a query to list all products supplied by ‘Enchanted Wares Ltd.’ including the supplier name along with the product names and prices. Sort the results by product name (Z to A).

  2. Write a query to list all suppliers and their products, sorted by the supplier’s name and product price.

# Lessons