SQL COUNT and AS
SQL COUNT counts the rows of a query result instead of listing them: COUNT(*) gives the number of rows. AS gives the result column a readable name.
The examples below use this books table. Change a query and press Run to see its result.
Table: books
| title | author | pages |
|---|---|---|
| Wonder | R. J. Palacio | 320 |
| Matilda | Roald Dahl | 240 |
| Holes | Louis Sachar | 272 |
| The BFG | Roald Dahl | 208 |
Count every row with COUNT(*)
Put COUNT(*) after SELECT where the column names would go:
SELECT COUNT(*)FROM books;The result is one row with one column, called COUNT(*). Its value is 4, the number of books.
Count only the rows that match
Add WHERE and COUNT(*) counts only the rows it keeps:
SELECT COUNT(*)FROM booksWHERE author = 'Roald Dahl';Two of the four books are by Roald Dahl, so the count is 2.
Name the result column with AS
Write AS and a name after COUNT(*) to give the column that name:
SELECT COUNT(*) AS books_on_shelfFROM books;The count is still 4, but the column is now called books_on_shelf.
See also: SQL WHERE.
Your turn
Add AS so the count column is called book_count.
book_count ---------- 4 (1 row)
-- add AS and a name after COUNT(*)SELECT COUNT(*)FROM books;