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 |
In Cambridge IGCSE Computer Science (0478 and 0984), the SQL COUNT function returns the total number of records matching a query as a single integer. Using COUNT(*) counts all rows in a table, while adding a WHERE clause limits the count strictly to matching records.
Practise counting Blue house records in the Students table and distinguish COUNT from SUM so you earn full marks on Topic 9.7 exam questions.
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?β