Learn SQL: COUNT
Counting with COUNT
Lien puts the kettle on. "How many rentals did we do this summer? I'd guess fifty." No more guesswork: you count.
COUNT counts rows
COUNT(*) counts the rows of a table. Instead of thirty rows you get one row with one number: a function that sums up all the rows like this is called an *aggregate function*.
With AS you give the number a name. Add a WHERE and you only count the rows that are left.
SELECT COUNT(*) AS rentals FROM rentals| rentals |
|---|
| 30 |
COUNT(column) skips NULL
Put a column between the brackets and COUNT only counts the rows where that column is filled in. NULL doesn't count.
Not every customer left a rating. This way you see straight away how many did.
SELECT COUNT(*) AS all_rows, COUNT(rating) AS with_rating FROM rentals| all_rows | with_rating |
|---|---|
| 30 | 24 |
Counting different values
With COUNT(DISTINCT column) you count how many different values a column has. Thirty rentals, but the customers came from only five countries.
SELECT COUNT(customer_country) AS row_count, COUNT(DISTINCT customer_country) AS countries FROM rentals| row_count | countries |
|---|---|
| 30 | 5 |
Try it yourself
Repairs under warranty cost De Trapper nothing (cost is 0). How many were there?
Ready for more?
The full lesson has 6 exercises, from easy to challenging, with hints, points and a streak you can build.
Start the lesson