Can we use the result of a SUM() function in MySQL WHERE clause


We can use the HAVING clause rather than the WHERE in MySQL. Let us first create a table −

mysql> create table DemoTable
(
   Name varchar(50),
   Price int
);
Query OK, 0 rows affected (0.79 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris',30);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David',40);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Chris',10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Mike',44);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('David',5);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+-------+
| Name  | Price |
+-------+-------+
| Chris | 30    |
| David | 40    |
| Chris | 10    |
| Mike  | 44    |
| David | 5     |
+-------+-------+
5 rows in set (0.00 sec)

Following is the query to use the result of SUM() function in HAVING clause −

mysql> select Name,SUM(Price) AS Total_Price from DemoTable group by Name having Total_Price > 40;

This will produce the following output −

+-------+-------------+
| Name  | Total_Price |
+-------+-------------+
| David | 45          |
| Mike  | 44          |
+-------+-------------+
2 rows in set (0.03 sec)

Updated on: 03-Oct-2019

484 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements