SQL COUNT() Function

The SQL COUNT() function can be used in two ways:

  • COUNT(*) – counts the number of rows in a table
  • COUNT(column_name) – counts the number of rows that have values in a specific column, while ignoring the NULL values.

The syntax of the COUNT(*) function:

SELECT COUNT(*) FROM table_name;

The syntax of the COUNT(column_name) function:

SELECT COUNT(column_name) FROM table_name;

Example of SELECT COUNT(*)

If we want to count the number of rows in the Products table, we can use the following SQL COUNT statement:

SELECT COUNT(*) FROM products;

This will produce the following result:

+----------+
| count(*) |
+----------+
|      110 |
+----------+

Example of SELECT COUNT(column_name)

If we want to count number of rows that contain the “USA” country code from the City table, we can use the following SQL COUNT statement:

SELECT COUNT(CountryCode) AS SameCountryCode FROM city WHERE CountryCode=’USA’;

This would produce the following result:

+-----------------+
| SameCountryCode |
+-----------------+
|             274 |
+-----------------+
Geek University 2022