← Python lessons

SQL COUNT and AS

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

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

titleauthorpages
WonderR. J. Palacio320
MatildaRoald Dahl240
HolesLouis Sachar272
The BFGRoald Dahl208

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.

🎯 Goal — make your query show exactly:
book_count
----------
4
(1 row)
-- add AS and a name after COUNT(*)SELECT COUNT(*)FROM books;