0%

Chapter 4 · practice

Summarize Many Rows

Count the Items in the Catalog

The lending desk does not always need one row for every item. Sometimes the whole question is “How many items are in the catalog?” Returning six asset tags and counting them by eye would make Python and the reader do work SQLite can do directly.

Open summary.sql. Replace its broad item query with this one:

SELECT COUNT(*) AS item_count
FROM items;

Press Run. Six stored item rows become one result row with one :

== summary.sql ==
Columns: item_count
6

COUNT(*) asks SQLite to count source rows. The star means each row counts, regardless of which values it contains. This is an aggregate: it looks across several source rows and produces a summary value instead of one answer row per item.

Compare that with the starting query. SELECT asset_tag FROM items produces one result row for each source row because every tag is shown separately. COUNT(*) consumes the same source set but reports its size, so the result no longer represents an individual item.

The alias AS item_count gives that value a useful heading. It does not add a column to items; it shapes only this result, just like the aliases in your shortlist.

The project also contains run_summaries.py. Leave it unchanged. When you press Run, it creates a fresh copy of the familiar six-item catalog, runs each summary file that is present, and prints SQLite’s columns and values. Your work stays in summary.sql; the temporary database disappears after the run.

There is an important empty-catalog detail. COUNT(*) still returns one result row when the table has no rows, and the value in that row is 0. That differs from a search whose result contains no rows at all. A summary can report that zero rows contributed.

Submit tries both nonempty and empty catalogs. Use COUNT(*) rather than counting a particular column, adding a literal, or copying the visible 6. The question is specifically about the number of source rows.

If you need the starting file again, use Reset project, then reopen this page. Once Run shows the item_count heading and one value, you have changed the shape of the answer: many catalog rows are now one useful fact.

Task

Replace summary.sql with a query that returns COUNT(*) AS item_count from items.

Run it and check that the six visible rows become one count, then submit it.