Quick Reach
MySQL count function
The count is an aggregate function that returns the total number of rows of the given column used in the Select query. If you use ‘*’ in the Select statement, the count function will return the total number of rows in the table.
See a count example online
If you specify a column to count its rows then it will not include the Null values.
MySQL count syntax
This is how you can use the count function:
Select count(column_name) from table_name
Where col_name = value
Examples of count function
In our examples, we will use the tbl_emp_salary_paid table that stores employees salaries. Click on the following link to see table structure with data we entered for demo purpose.
A count example
In the following example, we will return the total number of rows in our example table. The query and output can be seen by clicking the link below:
The MySQL select count statement:
1
|
select count(*) as Total_records from tbl_emp_salary_paid
|
An example of count with distinct
You have seen in the above example, the count query returned the total number of rows including any duplicate occurrence. You can use MySQL Distinct clause with count function to return only unique records.
The following query will return the total number of unique employee names exist in the emp_name column.
The Select count MySQL with Distinct:
1
|
select count(DISTINCT emp_name) as Total_unique_employees from tbl_emp_salary_paid
|
A count example with Group by clause
In this example, we will use the count function with the group by clause where we will return the total count of salaries paid to each employee with employee names.
The MySQL select-count with group by clause:
1
2
3
|
select emp_name,count(emp_sal_paid) as Total_times_paid from tbl_emp_salary_paid
group by emp_name
|
Also see MySQL join | MySQL Group by
Leave A Comment?