The count function of SQL

  • The SQL Count() function returns the total count of rows for the given column in the table.
  • The Count can also return all number of rows if ‘*’ is given in the select count statement.
  • If given column contains Null values, it will not be counted.
See count example online
Count with distinct example

Syntax of using count

The general syntax of using the count SQL function is:

Select count(column_name) from table_name

Where col_name = value

Examples of using count SQL function

Following examples shows how to use SQL select with the count. In our examples, we will use the tbl_emp_salary_paid table that stores the employees’ salaries.

The data in the table is shown with each example below to make it easier to understand. Simply click the Demo link with each example.

Example of using count in simple select statement

This example returns the total number of records exist in the tbl_emp_salary_paid table by using the count function.

The SQL select with count statement:

See SQL select count example online

Example of using count with Distinct clause

This example returns the total number of unique employee names exist in the emp_name column by using count function with the DISTINCT clause.

The count function distinct clause query:

See this example online with graphic

Example of using count with Group by clause

This query will return the total number of times salary paid to each employee by using the count aggregate function with the group by clause.

The SQL count with group by statement:

See count with group by example

As you can see in the above graphic, two queries are shown. One with the simple select statement to show all records in the table. The other query uses select with count and group by clause to show the total number of times the salary is paid to each employee.