# 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:
AuthorID | AuthorName |
---|---|
1 | J.K. Rowling |
2 | George Orwell |
3 | Leo Tolstoy |
# Books Table:
BookID | Title | AuthorID |
---|---|---|
101 | Harry Potter | 1 |
102 | 1984 | 2 |
103 | Animal Farm | 2 |
104 | War and Peace | 3 |
105 | Anna Karenina | 3 |
# SQL JOIN with Filter and Sort
Create a query that joins these tables and:
- Filters to show only books written by a specific author (e.g., George Orwell).
- Sorts the results by the book’s title.
|
|
# Expected Output:
Title | AuthorName |
---|---|
Anna Karenina | Leo Tolstoy |
War and Peace | Leo Tolstoy |
# Explanation:
- SELECT Clause: Retrieves the book titles and their corresponding author names.
- JOIN Operation: Joins the
Books
andAuthors
tables using theAuthorID
as the common field. - WHERE Clause: Filters the results to include only those books written by ‘Leo Tolstoy’.
- 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
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).
Write a query to list all suppliers and their products, sorted by the supplier’s name and product price.
# Lessons
- SQL - W3 Table JOINs - Introduction
- SQL - W3 Table JOINs - DROP Tables
- SQL - W3 Magic Store Database Overview
- SQL - W3 Table JOINs - One-to-Many Relationships
- SQL - W3 Table JOINs - JOIN Tables with One-to-Many Relationships
- SQL - W3 Table JOINs - Filter and Sort with JOINs
- Next: SQL - W3 One-to-Many JOINs - Practice Assignment