MySQL Wildcards

MySQL Wildcards

MySQL Aliases

MySQL Aliases

MySQL Data Types

MySQL Data Types

MySQL Interview Questions

MySQL Interview Questions and Answers


MySQL Having Clause

The MySQL HAVING Clause is used with GROUP BY clause, because aggregate functions could not be used with WHERE keyword. It always returns the rows where condition is TRUE. The HAVING clause is often used with the GROUP BY clause to filter groups based on a specified condition.

Note: The aggregate functions can not be used with WHERE Clause.

MySQL HAVING CLAUSE Syntax

To filter groups based on a specified condition, use the following syntax:

Syntax

SELECT col1, col2, ... 
FROM tablename  
[WHERE conditions]  
GROUP BY col1, col2, ...  
HAVING condition
ORDER BY col1[ASC|DESC], col2[ASC|DESC], ...;  

Parameters:

tablename: The table name from which you want to fetch the records.

condition: To specify the conditions that must be fulfilled for the records to be selected.

HAVING: To sort data set in ascending order.

ORDER BY: To specify filter conditions for a group of rows or aggregates. It shows only those groups in result set whose conditions are TRUE.

MySQL HAVING CLAUSE example with Count function

The following MySQL statement is used to filter groups based on a specified condition:

Example

SELECT COUNT(firstName), address
FROM tblcustomerloan
GROUP BY address
HAVING COUNT(firstName) > 1
ORDER BY COUNT(firstName) DESC;

Note:

In the above example, we have fetched records using filter groups based on a specified condition using HAVING.

You can use MySQL Command Line Client to fetched records using filter groups based on a specified condition using HAVING. It will look like this: