How to Filter Records with Aggregate Function AVG Database: SQL PostgreSQL MS SQL Server Oracle MySQL SQLite Operators: AVG HAVING Table of Contents Problem: Example: Solution: Discussion: Problem: You want to filter groups of rows in by the average value of a given column. Example: Our database has a table named product with data in the following columns: id, name, store and price. idnamestoreprice 1milkGreen Shop2.34 2breadClark’s Grocery3.56 3breadSuper Market4.15 4milkSuper Market1.80 5breadGrocery Amanda2.26 6milkViolet Grocery3.45 7milkClark’s Grocery2.10 8breadViolet Grocery2.55 9milkGrocery Amanda1.95 Let’s find the products for which the average price is higher than 3.00. Solution: SELECT name, AVG(price) FROM product GROUP BY name HAVING AVG(price) > 3.00; Here’s the result: nameavg bread3.13 Discussion: In this query, you calculate the average price of each product. Because you calculate the value for each group of rows (we group rows by product name), the query has a GROUP BY clause with the name of the column to group rows (GROUP BY name). To calculate the average value for each group of rows, we use the aggregate AVG function, and give it the column price as an argument. To filter records using the aggregate function, we use the HAVING clause. Remember, HAVING should be put after GROUP BY clause. HAVING contains the condition comparing the value returned by the aggregate function with a given value. Here, our condition is AVG(price) > 3.00: we verify the average price is higher than 3.00. The query displayed only one product, bread, with an average price higher than three. Recommended courses: SQL Basics SQL Practice Set Standard SQL Functions Recommended articles: SQL Basics Cheat Sheet The SQL HAVING Clause Explained HAVING vs. WHERE in SQL: What You Should Know SQL SUM() Function Explained with 5 Practical Examples How to Use SUM() with GROUP BY: A Guide with 8 Examples 10 GROUP BY SQL Practice Exercises with Solutions SQL Aggregate Functions Cheat Sheet GROUP BY and Aggregate Functions: A Complete Overview Top 9 SQL GROUP BY Interview Questions See also: How to Filter Records with Aggregate Function COUNT How to Filter Records with Aggregate Function SUM Subscribe to our newsletter Join our monthly newsletter to be notified about the latest posts. Email address How Do You Write a SELECT Statement in SQL? What Is a Foreign Key in SQL? Enumerate and Explain All the Basic Elements of an SQL Query