SQL Tutorial – COUNT() – Counting rows in a table.

You want to count the number of rows in a table or want to count the number of values in a column. For example, you want to find the total number of countries in the country table or want to find total number of countries in each continent.

Solution –

To count the number of rows in a table or to count the number of values (Non-null values + Null values) in a column, we use the COUNT() function along with the * character.

SELECT
    COUNT(*) as total_countries
FROM
    country

And to count the number of rows for each group, we first group the data by GROUP BY clause and then apply the COUNT() function.

SELECT
    Continent,
    COUNT(*) as total_countries
FROM
    country
GROUP BY
    Continent

Note – If you want, you can exclude the continent from the SELECT clause it is not necessary but it is very useful for readability. It helps you understand which rows of data comes from which continent.

Related Post – COUNT() – counting values in a column.

If you want to know how to count Non-Null values in a column or what is the difference between COUNT(*) and COUNT(column name) then read the above related post.

if you like this post, please share it with others and subscribe to our blog below to learn data science.

Rating: 1 out of 5.

Posted in SQL

Leave a Reply