Bird
0
0

Given tables:

hard📝 Application Q9 of 15
SQL - LEFT and RIGHT JOIN
Given tables:
authors(id, name), books(id, author_id, title), reviews(id, book_id, rating)
How to write a query to show each author's name, book title, and average rating, including authors without books or reviews?
ASELECT a.name, b.title, AVG(r.rating) FROM authors a INNER JOIN books b ON a.id = b.author_id INNER JOIN reviews r ON b.id = r.book_id GROUP BY a.name, b.title;
BSELECT a.name, b.title, AVG(r.rating) FROM authors a LEFT JOIN books b ON a.id = b.author_id LEFT JOIN reviews r ON b.id = r.book_id GROUP BY a.name, b.title;
CSELECT a.name, b.title, AVG(r.rating) FROM authors a LEFT JOIN books b ON b.author_id = a.id INNER JOIN reviews r ON r.book_id = b.id GROUP BY a.name, b.title;
DSELECT a.name, b.title, AVG(r.rating) FROM authors a RIGHT JOIN books b ON a.id = b.author_id LEFT JOIN reviews r ON b.id = r.book_id GROUP BY a.name, b.title;
Step-by-Step Solution
Solution:
  1. Step 1: Use LEFT JOINs to include all authors

    LEFT JOIN books and reviews to include authors without books or reviews.
  2. Step 2: Aggregate average rating and group results

    Use AVG(r.rating) and GROUP BY author name and book title.
  3. Final Answer:

    SELECT a.name, b.title, AVG(r.rating) FROM authors a LEFT JOIN books b ON a.id = b.author_id LEFT JOIN reviews r ON b.id = r.book_id GROUP BY a.name, b.title; -> Option B
  4. Quick Check:

    LEFT JOIN + AVG + GROUP BY = SELECT a.name, b.title, AVG(r.rating) FROM authors a LEFT JOIN books b ON a.id = b.author_id LEFT JOIN reviews r ON b.id = r.book_id GROUP BY a.name, b.title; [OK]
Quick Trick: LEFT JOIN preserves all authors; aggregate ratings with GROUP BY [OK]
Common Mistakes:
MISTAKES
  • Using INNER JOIN excludes authors without books
  • Mixing JOIN types incorrectly
  • Omitting GROUP BY with aggregates

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes