Quick Reach
Having clause of MySQL
A few main points about Having clause in MySQL are:
- The having clause is related to Group by clause of MySQL.
- If you know how to use the Where clause then understanding Having clause is quite easier.
- The having clause is used with the Group by clause.
- As such, the Where clause cannot be used with the group by, we use the having clause to filter results returned after using the group by clause.
- You can only use those columns in having MySQL clause that are used in the Group by clause.
Syntax of using having clause of MySQL
This is how you can use Having clause:
select col_name, aggregate_function (col_name) from table_name
where col_name = value
group by emp_name
having aggragated_column=value;
Having clause of MySQL example
For our examples to explain the having clause, we will use our created table tbl_emp_salary_paid that stores employees salaries.
An example of MySQL having clause
In this example, we will use group by clause to Sum up salaries of each employee. While having clause is used to return total salary of Mike only.
The having query:
1
2
3
4
5
|
select emp_name, sum(emp_sal_paid)as total_paid from tbl_emp_salary_paid
group by emp_name
having emp_name = ‘Mike’
|
An example with count aggregate function
This query will return the total number of salaries paid overall to employee Mike only by using having MySQL with the count function.
The having MySQL query with count function is:
1
2
3
4
5
|
select emp_name, count(emp_sal_paid)as total_paid from tbl_emp_salary_paid
group by emp_name
having emp_name = ‘Mike’
|
Also see MySQL Group by | MySQL count
Leave A Comment?