
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
WHERE vs HAVING in MySQL?
We can use a conditional clause called the WHERE Clause to filter out the results. Using this WHERE clause, we can specify a selection criteria to select the required records from a table. The HAVING clause specify filter conditions for a group of rows or aggregates
WHERE clause cannot be used with aggregate function while HAVING can be used with aggregate function. The following is an example −
Let us now create a table.
mysql> create table WhereDemo -> ( -> Price int -> ); Query OK, 0 rows affected (0.64 sec)
Inserting records into table.
mysql> insert into WhereDemo values(100); Query OK, 1 row affected (0.13 sec) mysql> insert into WhereDemo values(200); Query OK, 1 row affected (0.21 sec) mysql> insert into WhereDemo values(300); Query OK, 1 row affected (0.15 sec) mysql> insert into WhereDemo values(400); Query OK, 1 row affected (0.12 sec)
To display all records.
mysql> select *from WhereDemo;
The following is the output.
+-------+ | Price | +-------+ | 100 | | 200 | | 300 | | 400 | +-------+ 4 rows in set (0.00 sec)
The HAVING clause can be used with aggregate function.
mysql> select sum(Price) from WhereDemo HAVING Sum(Price) > 500;
The following is the output.
+------------+ | sum(Price) | +------------+ | 1000 | +------------+ 1 row in set (0.00 sec)
Here, if we will try to use WHERE with aggregate function, an ERROR will get generated.
mysql> select sum(Price) from WhereDemo where Sum(Price) > 200; ERROR 1111 (HY000): Invalid use of group function
- Related Articles
- Implement WHERE IN vs OR in MySQL with similar example
- How can we simulate the MySQL INTERSECT query having WHERE clause?
- Difference between Where and Having
- Difference Between Where and Having Clause in SQL
- CURDATE () vs NOW() in MySQL
- length() vs char_length() in MySQL?
- HAVING with GROUP BY in MySQL
- MySQL ON vs USING?
- SELECT WHERE IN null in MySQL?
- Multiple WHERE with LIMIT in MySQL?
- SELECT DISTINCT vs GROUP BY in MySQL?
- int(5) vs. int(10) in MySQL?
- System variables vs Local Variables in MySQL?
- How to implement HAVING LENGTH(field) in MySQL?
- Get current year in MySQL WHERE clause?

Advertisements