The COUNT function returns the number of rows in a table. With this function, you can count all the rows that fulfill a specified condition.
COUNT has three forms: COUNT(*), COUNT(expression), and COUNT(DISTINCT expression).
To visualize each function form, we will be using the data set numbers with the values below as an example.
SELECT * FROM count_num;
The COUNT(*) function returns the number of rows in a dataset using the SELECT statement. The function counts rows with NULL, duplicate, and non-NULL values.
SELECT COUNT(*) FROM numbers;
You can also use the WHERE clause to specify a condition.
SELECT COUNT(*)FROM numbersWHERE val = 5;
The COUNT(expression) function returns the number of rows that do not contain NULL values.
SELECT COUNT(val)FROM numbers;
Row six contains a NULL val, so the expression will return .
The COUNT(DISTINCT expression) function returns the number of distinct non-NULL values.
SELECT COUNT(DISTINCT val)FROM numbers;
Row and share the same value, row and share the same value and row has a NULL value, which leaves only distinct non-NULL rows.
Free Resources