Skip to content
BytePatterns

Author Book Counts in One Query

MediumSQL#n-plus-one#left-join#group-by~20m

Problem

Two tables: author(id, name) and book(id, author_id, title). A page lists every author with the number of books they wrote. Its code first runs SELECT id, name FROM author and then, inside a loop, one SELECT COUNT(*) FROM book WHERE author_id = ? per author, which is N + 1 statements for N authors. Rewrite it as a single query that returns name and books for every author, including authors with no books, sorted by name. The database must receive exactly one statement.

Examples

Input:  author = [(1, "Ana"), (2, "Ben"), (3, "Cy")]
        book   = [(10, 1, "Dune"), (11, 1, "Emma"), (12, 3, "Ivy")]
Output: rows = [("Ana", 2), ("Ben", 0), ("Cy", 1)], statements = 1
Why:    the loop version would send 4 statements for these 3 authors
Input:  author = [(1, "Ana")]
        book   = []
Output: rows = [("Ana", 0)], statements = 1
Why:    edge case, an author without books still appears, with 0

Hints

0 / 3

Stuck on the idea rather than the code? The N+1 Query Problem covers it.