JIYIK CN >

Current Location:Home > Learning > DATABASE > MySQL >

Where and Having in MySQL

Author:JIYIK Last Updated:2025/04/24 Views:

Today, we will understand the difference between the WHEREand clauses in MySQL . We will understand these clauses individually with code examples and compare them in a tabular form to highlight the differences.HAVING

In WHEREMySQLHAVING

WHEREThe and HAVINGclauses are very similar. The main difference between these clauses is GROUP BYwhen they are used with .

We cannot use the clause with aggregate data WHERE, but we can use the HAVING.

We can say that the AND WHEREclause filters the records(rows) before grouping, but HAVINGthe IF clause excludes the records(rows) after grouping.

To continue with this article, we should have a table.

Therefore, create a transactionstable with four attributes named ID, Product, MonthOfTransactionand .AmountInUSD

Sample code:

#create a table
CREATE TABLE `ms20`.`transactions` (
    `ID` INT NOT NULL AUTO_INCREMENT,
    `Product` VARCHAR(45) NOT NULL,
    `MonthOfTransaction` VARCHAR(20) NOT NULL,
    `AmountInUSD` INT NOT NULL,
    PRIMARY KEY (`ID`));

#insert data into a table
INSERT INTO ms20.transactions(Product, MonthOfTransaction, AmountInUSD) VALUES
('Air Conditioner', 'January', 500),
('Television', 'January', 600),
('Refrigerator', 'January', 550),
('Television', 'March', 600),
('Air Conditioner', 'March', 500),
('Juicer Machine', 'March', 200);

#select all data from the table
SELECT * FROM ms20.transactions;

Output:

where vs in mysql - transaction data

WHEREClause in MySQL

In MySQL, we use WHEREthe EXEC clause to filter records and extract only those rows (records) that meet the specified condition. We can use it with SELECTthe EXEC statement and UPDATEthe , INSERTand DELETEcommands.

WHEREThe clause involves JOINspecific conditions placed on the selected columns while retrieving records from single or multiple tables using the IN clause. We can WHEREperform logical operations such as AND, , NOT.OR

We can also call them Boolean conditions that must be true (also called relations) when retrieving information from a table . These logical operators use comparison operators including <, , >, <=, >=, =and <>.

Sample code:

SELECT Product, sum(AmountInUSD) AS Total
FROM ms20.transactions
WHERE Product in ( 'Television', 'Refrigerator')
GROUP BY Product;

Output:

where vs have in mysql - where clause output

HAVINGClause in MySQL

In MySQL, HAVINGthe clause is used in conjunction with GROUP BYthe clause. The purpose of using this clause is to perform column operations and apply to aggregate data or group based on given conditions.

HAVINGThe clause returns only results for groups that meet the specified condition. If used WHEREwith HAVINGthe clause, WHEREfilters a single record (row).

Then, the records (rows) are grouped, aggregate calculations are performed, and finally, HAVINGthe groups are filtered. HAVINGThe clause checks GROUP BYthe conditions of the groups created by the clause.

In the absence GROUP BYof a clause, HAVINGthe clause behaves like WHEREa clause.

We can also use various aggregate functions by combining HAVINGthe clause with the statement. The aggregate (group) methods include , , , , and .SELECTSUMMAXMINCOUNTAVG

We can easily HAVINGuse aggregate functions with the clause whereas if WHEREused with the clause we will get an error 组函数的无效使用i.e.

Sample code (without aggregate functions):

SELECT Product, sum(AmountInUSD) AS Total
FROM ms20.transactions
GROUP BY Product
HAVING Product in ('Television', 'Refrigerator');

Output:

where vs have in mysql - having clause outputs a

Sample code (with aggregate functions):

SELECT Product, sum(AmountInUSD) AS Total
FROM ms20.transactions
GROUP BY Product
HAVING sum(AmountInUSD) > 800;

Output:

where vs have in mysql - having clause output 2

When we have multiple clauses in a query, it is important to understand the order of execution. We must remember the order FWGHSOL( Fstarting with and Lending with ) to know the order of execution, where F = FROM, W = WHERE, G = GROUP BY, H = HAVING, S = SELECT, O = ORDER BYand L = LIMIT.

Difference between WHEREand clauses in MySQLHAVING

While writing queries to manipulate data, we have to consider the following points.

WHERE Clause HAVING Clause
Implemented in row (record) operations. Implemented in column (attribute) operations.
Filtering is performed on individual rows before aggregation calculations. Performs filtering operations on aggregated (group) data.
Retrieve specific data from specific rows that meet given conditions. First all data is retrieved and then separated according to the specified conditions.
We cannot use aggregate methods in this clause. We can easily use aggregate methods in this clause.
It behaves like a prefilter and precedes the GROUP BY clause. It behaves like a post filter and comes after the GROUP BY clause.
It can be used with DELETE, SELECT, and UPDATE statements. It can only be used with the SELECT statement.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Get the version in MySQL

Publish Date:2025/04/24 Views:169 Category:MySQL

In this article, we will learn how to get the current version of MySQL on Windows systems. It is necessary for businesses to maintain versions of different tools and software used to run their business in order to keep systems compatible. T

Full Join in MySQL

Publish Date:2025/04/24 Views:70 Category:MySQL

This article aims to explore how to perform a full join or full outer join in MySQL. Full outer join is used to merge or combine the entire data from two separate tables. For example, suppose we have two tables named student_id and student_

Grouping by month in MySQL

Publish Date:2025/04/24 Views:166 Category:MySQL

In this article, we will learn how to group values ​​by month in MySQL database. Businesses and organizations have to find user or customer data based on purchase or usage trends over a few months. If a particular business achieves its

Enabling the slow query log in MySQL

Publish Date:2025/04/24 Views:177 Category:MySQL

Today, we will enable MySQL in MySQL using MySQL shell on Windows and Ubuntu 20.04 slow_query_log . For this tutorial, we are using MySQL version 8.0 and Ubuntu 20.04. MySQL slow_query_log MySQL slow_query_log contains SQL statements that t

Update multiple tables in MySQL with one query

Publish Date:2025/04/24 Views:65 Category:MySQL

In some cases, users want to update logically related tables at the same time. These logically related tables are linked to each other through some attributes. Advantages of updating multiple tables in one MySQL query Similar attributes in

Checking MySQL version in macOS

Publish Date:2025/04/24 Views:60 Category:MySQL

In this article, we aim to explore how to check the current version of MySQL on macOS. Checking MySQL version in macOS When trying to figure out the version, you must follow these steps. Each time a person logs into the MySQL server, the ve

Common table expressions in MySQL

Publish Date:2025/04/24 Views:168 Category:MySQL

This article aims to understand how to use common table expressions in MySQL. Most data analysts need to store the results of different queries in order to merge them with a separate query. With the help of common tables, expressions can ma

Sorting by date in MySQL

Publish Date:2025/04/24 Views:156 Category:MySQL

This article aims to understand how to sort values ​​by date in MySQL. Most of the businesses and organizations that use MySQL for data analysis or data visualization need to sort different table values ​​of their users based on dat

Sort MySQL data alphabetically

Publish Date:2025/04/24 Views:153 Category:MySQL

In this article, we aim to explore how to sort data alphabetically in MySQL database. Sorting is the ordering of elements or values ​​in an array or column based on a particular criteria. In this tutorial, we will set the criteria as al

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial