Understand how to use the COUNT and DISTICNCT function work.
Learn how to use these functions to count rows.
Practice using the COUNT and COUNT DISTINCT functions.
A common task in SQL is to count the number of rows in a table. This can be done using the COUNT function.
Using the COUNT Function
The COUNT function calculates the total number of rows in a table or the total number of non-null values in a column.
Syntax
To count a specific column, we put the name of the column inside parentheses right after COUNT .
To count all rows in a table, we can use the * character. Note that we put the * character inside parentheses (). Like this (*) .
Example
In the following table called students , we have students information with columns: id , name , age , and major .
students
id
name
age
major
1
John
21
Mathematics
2
Lily
22
Biology
3
Anil
21
Mathematics
4
Ira
20
Computer Science
To count the number of rows in the students table, we can use the following SQL query:
We will get the following result:
COUNT(*)
4
We can see that the students table has 4 rows.
Exercise 2.1
Run the following code to count the number of rows in the students table.
students
id
name
age
major
1
John
21
Mathematics
2
Lily
22
Biology
3
Anil
21
Mathematics
4
Ira
20
Computer Science
Interactive
Count All Rows
Exercise 2.2
Write a SQL statement to count the number of rows in the students table.
students
id
name
age
major
1
John
21
Mathematics
2
Lily
22
Biology
3
Anil
21
Mathematics
4
Ira
20
Computer Science
Interactive
Count All Rows
COUNT with Alias Name
By default, the name of the column in the result is COUNT(*) . We can also give it a custom name by using the AS keyword. For example, we can rename it to Total Students :
This will give us the following result:
Total Students
4
Exercise 2.3
Run the following code to count the number of rows in the students table and give the result a custom name ‘Total Students’.
id
name
age
major
1
John
21
Mathematics
2
Lily
22
Biology
3
Anil
21
Mathematics
4
Ira
20
Computer Science
Interactive
Count All Rows
Note: If the alias name contains spaces, you should enclose it in quotes. Otherwise, it will give you an error.
Exercise 2.4
The following code will give you an error. Correct the alias name to fix the error. Surround the alias name with quotes. Use ‘Total Students’ instead of Total Students.
Interactive
Fix Error
You can also use the AS keyword without quotes for the alias name if there is no space in the name.
Objectives
Understand how to filter rows based on conditions.