How many records match the question?
A normal SELECT query displays records from a database.
Sometimes the user does not need to see every matching record. They only need to know how many there are.
| Name | House |
|---|---|
| Amina | Blue |
| Ben | Red |
| Chen | Blue |
| Dara | Blue |
COUNT answers one clear question: how many records are included in the result?
A normal SELECT query displays records from a database.
Sometimes the user does not need to see every matching record. They only need to know how many there are.
| Name | House |
|---|---|
| Amina | Blue |
| Ben | Red |
| Chen | Blue |
| Dara | Blue |
The asterisk means that SQL should count the records returned by the query.
SELECT COUNT(*) FROM TableName;
A teacher could read every name on a class register, but sometimes only the class total is needed.
COUNT works in the same way. It checks the records and returns the total number rather than displaying the complete list.
The database table is called Students. The query must count only records where the House field contains Blue.
SELECT COUNT(*) FROM Students WHERE House = "Blue";
Three records match the condition.
SELECT COUNT(*) FROM Students;
This returns the total number of records in the Students table.
SELECT COUNT(*) FROM Students WHERE House = "Blue";
This returns only the number of students in the Blue house.
COUNT tells you how many records there are. SUM adds numerical values stored in a field.
βHow many sales were made?β
βWhat is the total value of all sales?β