Join the
shop.

An account lets you order books, follow your orders and write reviews.

Register

Already registered? Log in

SQL behind this page 1 statement

This page was built with 1 statement

  1. SELECT c.category_id, c.name, COUNT(b.book_id) AS book_count
    FROM category c
    LEFT JOIN book b ON b.category_id = c.category_id
    GROUP BY c.category_id, c.name
    ORDER BY c.name

    Builds: the category links: in the menu row and the footer, and on a book list the category band or the side list with the number of books.

    Show on the page
    Picture

    The page as it is now. Red: what this statement builds.

    Step by step
    SELECT c.category_id, c.name, COUNT(b.book_id) AS book_count
    FROM category c
    LEFT JOIN book b ON b.category_id = c.category_id
    GROUP BY c.category_id, c.name
    ORDER BY c.name

    Step 1 of 5

    SELECT

    Chooses the columns (or computed values) that the result shows. Here COUNT counts rows.

    Back
    SELECT c.category_id, c.name, COUNT(b.book_id) AS book_count
    FROM category c
    LEFT JOIN book b ON b.category_id = c.category_id
    GROUP BY c.category_id, c.name
    ORDER BY c.name

    Step 2 of 5

    FROM

    The table the rows come from.

    SELECT c.category_id, c.name, COUNT(b.book_id) AS book_count
    FROM category c
    LEFT JOIN book b ON b.category_id = c.category_id
    GROUP BY c.category_id, c.name
    ORDER BY c.name

    Step 3 of 5

    LEFT JOIN

    Like JOIN, but a row is kept even when the other table has no match (then its columns are empty).

    SELECT c.category_id, c.name, COUNT(b.book_id) AS book_count
    FROM category c
    LEFT JOIN book b ON b.category_id = c.category_id
    GROUP BY c.category_id, c.name
    ORDER BY c.name

    Step 4 of 5

    GROUP BY

    Puts the rows with the same values into one group, so COUNT, SUM or AVG give one result per group.

    SELECT c.category_id, c.name, COUNT(b.book_id) AS book_count
    FROM category c
    LEFT JOIN book b ON b.category_id = c.category_id
    GROUP BY c.category_id, c.name
    ORDER BY c.name

    Step 5 of 5

    ORDER BY

    Sorts the result by these columns, from the smallest to the largest (A to Z) unless DESC is written.

    Back to this SQL statement