Counting rows with COUNT #
So far we've only pulled raw rows out of a table. Sometimes you don't want the rows themselves, you want a summary of them, for example, "how many rows are there?" That's what aggregate functions are for: they take many rows and collapse them into a single value. COUNT is the simplest one, it counts rows.
SELECT
COUNT(*)
FROM
table_name;
COUNT(*) counts every row in the table, regardless of whether any column is NULL. As with any column, you can give the result a friendlier name with AS:
SELECT
COUNT(*) AS total
FROM
table_name;
Example #
SELECT
COUNT(*) AS total
FROM
customers;
Result:
+-------+
| total |
+-------+
| 10 |
+-------+
This tells us there are 10 rows in the customers table, without us having to fetch and count them ourselves.
Exercise #
Write a command that counts the total number of rows in the products table.
- The result has a
totalcolumn. - The value of
totalmatches the number of rows inproducts.
Solution
SELECT
COUNT(*) AS total
FROM
products;
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity