Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteSome links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Use WHERE to filter individual rows before grouping; use HAVING to filter groups after an aggregate has been calculated. For example, this returns customers with at least five orders:
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 5;
The examples below follow the MySQL 8.4 Reference Manual. Check the documentation for your deployed version if you rely on version-specific behavior.
What does HAVING do?
HAVING tests the results of a grouped query. A GROUP BY clause collects rows into groups—such as one group per customer—and aggregate functions calculate a value for each group. HAVING keeps only the groups that meet its condition.
In the opening query, MySQL groups orders by customer_id, counts the rows in each group, then returns groups whose count is at least five. Because this condition depends on a count, it belongs in HAVING, not WHERE. See the MySQL 8.4 SELECT statement documentation.
#1 Best Overall
- Desktop-Level Performance, Anywhere: Get legendary gaming performance with the Intel Core Ultra 9 275HX processor, delivering ultra-smooth gameplay and future-ready AI (Up to 13 NPU TOPS). Offload tasks like background removal and audio optimization to the NPU for seamless streaming and gaming, while Intel Application Optimization enhances performance on classic titles.
- Game-Changing Realism: Powered by NVIDIA Blackwell architecture, GeForce RTX 5070 Ti Laptop GPU unlocks the game changing realism of full ray tracing. Equipped with a massive level of 992 AI TOPS horsepower, the RTX 50 Series enables new experiences and next-level graphics fidelity. Experience cinematic quality visuals at unprecedented speed with fourth-gen RT Cores and breakthrough neural rendering technologies accelerated with fifth-gen Tensor Cores.
- Supreme Speed. Superior Visuals. Powered by AI: DLSS is a revolutionary suite of neural rendering technologies that uses AI to boost FPS, reduce latency, and improve image quality. DLSS 4 brings a new Multi Frame Generation and enhanced Ray Reconstruction and Super Resolution, powered by GeForce RTX 50 Series GPUs and fifth-generation Tensor Cores.
- The Ultimate in Ray Tracing and AI: NVIDIA RTX is the most advanced platform for full ray tracing and neural rendering technologies that are revolutionizing the ways we play and create. Over 700 games and applications use RTX to deliver realistic graphics and incredibly fast performance with cutting-edge AI features like DLSS Multi Frame Generation.
- Immersive Depth and Detail: At 18 inches with a 16:10 aspect ratio, the pristine WQXGA screen offering vibrant colors with up to 100% DCI-P3 operates at a fast 240Hz refresh and 3ms overdrive response time. Alongside the suite of features from NVIDIA G-SYNC and NVIDIA Advanced Optimus, you're guaranteed that whatever's on-screen is a distinct viewing delight.
MySQL HAVING syntax and clause order
SELECT grouping_column, aggregate_function(value_column) AS result_alias
FROM table_name
WHERE row_condition
GROUP BY grouping_column
HAVING group_condition
ORDER BY sort_expression
LIMIT row_count;
The useful conceptual order is:
FROMchooses the input tables.WHEREremoves rows that do not qualify.GROUP BYforms groups from the remaining rows.- Aggregate functions calculate values for those groups.
HAVINGremoves groups that do not qualify.ORDER BYsorts the result andLIMITrestricts how many rows are returned.
This is a way to understand what each clause means, not a promise that MySQL’s optimizer executes every query as a literal sequence of steps.
WHERE vs. HAVING
WHERE filters input rows; HAVING filters grouped output. Use the earliest clause that expresses the condition correctly: row conditions normally belong in WHERE, while conditions that depend on a group or aggregate belong in HAVING.
| Requirement | Clause | Example |
|---|---|---|
| Keep orders dated January 1, 2026 or later | WHERE |
WHERE order_date >= '2026-01-01' |
| Keep customers with at least five orders | HAVING |
HAVING COUNT(*) >= 5 |
| Keep products priced above 100 before calculating totals | WHERE |
WHERE price > 100 |
| Keep product groups with sales above 10,000 | HAVING |
HAVING SUM(amount) > 10000 |
You can use both in one query. This first limits the orders being counted, then keeps customers with enough qualifying orders:
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteSELECT customer_id, COUNT(*) AS order_count
FROM orders
WHERE order_date >= '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) >= 5;
Using WHERE for row-level filtering can reduce the input to aggregation, but actual performance depends on the query, indexes, data, and execution plan. MySQL advises using WHERE rather than HAVING for conditions that do not require group filtering.
Common aggregate conditions
COUNT(): count rows or values
SELECT product_id, COUNT(*) AS review_count
FROM reviews
GROUP BY product_id
HAVING COUNT(*) >= 10;
COUNT(*) counts rows. COUNT(column) counts only non-NULL values in that column. COUNT(DISTINCT column) counts distinct non-NULL values. For example, to find customers who bought at least three different products:
SELECT customer_id, COUNT(DISTINCT product_id) AS products_bought
FROM order_items
GROUP BY customer_id
HAVING COUNT(DISTINCT product_id) >= 3;
SUM(): test a group total
SELECT customer_id, SUM(total) AS lifetime_value
FROM orders
GROUP BY customer_id
HAVING SUM(total) > 1000;
AVG(): test a group average
SELECT category_id, AVG(price) AS average_price
FROM products
GROUP BY category_id
HAVING AVG(price) BETWEEN 20 AND 50;
MIN() and MAX(): test group extremes
SELECT employee_id, MAX(sale_amount) AS largest_sale
FROM sales
GROUP BY employee_id
HAVING MAX(sale_amount) >= 5000;
Combine conditions
A group can be tested against more than one aggregate:
SELECT customer_id,
COUNT(*) AS order_count,
SUM(total) AS total_spent
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 5
AND SUM(total) >= 1000;
When mixing AND and OR, use parentheses to make the intended logic explicit:
Rank #2
HAVING (COUNT(*) >= 5 AND SUM(total) >= 1000)
OR MAX(total) >= 5000;
Aggregate functions and their handling of NULL are described in the MySQL 8.4 aggregate functions reference.
Can HAVING use a SELECT alias?
MySQL allows HAVING to refer to an expression alias from the SELECT list:
SELECT customer_id, SUM(total) AS total_spent
FROM orders
GROUP BY customer_id
HAVING total_spent > 1000;
This is convenient, but support for aliases in HAVING varies across database systems. Writing the aggregate expression directly is often clearer and more portable:
HAVING SUM(total) > 1000
Avoid aliases that could be confused with source-column names. Distinct names make a query easier to read and help avoid ambiguity in MySQL’s name resolution.
Free tools Windows power users keep installed
One-click scans. No signup required.
HAVING without GROUP BY
MySQL permits HAVING without GROUP BY. In an aggregate query, all rows that survive WHERE form one implicit group:
SELECT COUNT(*) AS total_orders
FROM orders
HAVING COUNT(*) > 100;
This returns one row if the table has more than 100 orders; otherwise it returns no rows. You can filter the input to that implicit group first:
SELECT SUM(total) AS revenue
FROM orders
WHERE order_date >= '2026-01-01'
HAVING SUM(total) > 100000;
Do not use this as a substitute for ordinary row filtering. For a row condition such as paid status, use WHERE:
Rank #3
- Intel Core i9 HX Power for Elite Gaming: Dominate demanding titles with the Intel Core i9-14900HX and its 24-core hybrid architecture, delivering fast load times, high FPS, and smooth multitasking.
- GeForce RTX 5070 With Ray Tracing & DLSS 4: Powered by NVIDIA Blackwell, the RTX 5070 delivers stronger ray tracing, higher FPS, faster AI upscaling, and more responsive gameplay—ideal for competitive and cinematic gaming.
- QHD 165Hz, 100% DCI-P3 for Ultra-Clear Combat: The QHD 165Hz display reveals more detail, reduces motion blur, and boosts visibility in fast-paced games while delivering richer, more accurate colors.
- Cooler Boost 5 for Sustained Performance: Dual fans and a 5-heat-pipe share-pipe design keep the CPU and GPU cool, maintaining stable frame rates during long gaming marathons.
- 4-Zone RGB Keyboard + Full Game-Ready Ports: Customize your setup with a 4-zone RGB keyboard and highlighted WASD keys. Includes USB-C Gen 2, HDMI up to 8K, multiple USB-A ports, RJ45, Wi-Fi 6E & Hi-Res Audio.
SELECT *
FROM orders
WHERE status = 'paid';
HAVING with joins
To find customers whose paid orders total more than 1,000, filter individual orders by status, group by customer, then test each group’s total:
SELECT c.customer_id,
c.name,
SUM(o.total) AS total_spent
FROM customers AS c
JOIN orders AS o
ON o.customer_id = c.customer_id
WHERE o.status = 'paid'
GROUP BY c.customer_id, c.name
HAVING SUM(o.total) > 1000;
To find customers with no orders, preserve every customer with a LEFT JOIN and count a non-nullable order identifier:
SELECT c.customer_id,
c.name,
COUNT(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
HAVING COUNT(o.order_id) = 0;
Here, COUNT(o.order_id) is zero for a customer without a matching order. COUNT(*) would count the preserved customer row, so it would not identify the missing child.
Be careful about filtering the right-hand table of a left join. Putting o.status = 'paid' in WHERE removes rows where there is no matching order, effectively changing which customers are retained. If customers without a paid order must remain, put the condition in the join instead:
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
AND o.status = 'paid'
NULL and conditional aggregation
Most aggregate functions ignore NULL values. For instance, COUNT(manager_id) counts only rows with a manager, while COUNT(*) counts every row in the group:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
SELECT department_id,
COUNT(*) AS rows_in_group,
COUNT(manager_id) AS rows_with_manager
FROM employees
GROUP BY department_id
HAVING COUNT(manager_id) > 0;
A comparison such as SUM(amount) > 100 is not true when the sum is NULL, so such a group does not pass the condition. If the intended rule treats a missing sum as zero, express that explicitly:
HAVING COALESCE(SUM(amount), 0) > 100
To aggregate only selected rows while retaining other rows in each group, use conditional aggregation with CASE:
Rank #4
- Vibrant 15.6" FHD IPS Display: Experience stunning visuals on a large 15.6-inch Full HD (1920x1080) IPS screen. With narrow bezels and wide viewing angles, this laptop offers an immersive experience for streaming movies, online classes, or working on documents with crystal-clear detail
- Efficient Daily Performance: Powered by the Intel Celeron N4020 processor and 4GB LPDDR4 RAM, this notebook delivers reliable performance for web browsing, light multitasking, and school projects. The 128GB storage provides ample space for your essential files, photos, and apps
- Modern Connectivity & PD Fast Charge: Equipped with a versatile Type-C PD 45W port for fast charging and high-speed data transfer. Combined with Dual-Band AC WiFi and Bluetooth, you’ll enjoy a stable and fast internet connection for seamless video calls and cloud-based work
- Silent & Ultra-Portable Design: Featuring an advanced fanless cooling system, this laptop operates in total silence—perfect for libraries or late-night study sessions. Its sleek, lightweight body fits easily into backpacks, making it the ideal companion for students and commuters
- Ready for Work & Play: Pre-installed with Windows 11 Home, offering a secure and user-friendly interface. Includes a HD webcam and high-quality speakers for clear communication. A practical choice for online learning, remote work, or everyday entertainment
SELECT customer_id,
SUM(CASE WHEN status = 'paid' THEN total ELSE 0 END) AS paid_total
FROM orders
GROUP BY customer_id
HAVING SUM(CASE WHEN status = 'paid' THEN total ELSE 0 END) > 1000;
If the aggregate expression is long or needed in multiple places, calculate it in a CTE and filter the result with an outer WHERE:
WITH customer_totals AS (
SELECT customer_id,
SUM(CASE WHEN status = 'paid' THEN total ELSE 0 END) AS paid_total
FROM orders
GROUP BY customer_id
)
SELECT customer_id, paid_total
FROM customer_totals
WHERE paid_total > 1000;
ONLY_FULL_GROUP_BY and grouping errors
MySQL’s ONLY_FULL_GROUP_BY SQL mode rejects grouped queries that select a nonaggregated value which is neither grouped nor functionally determined by the grouped columns. For example, a department can contain many employees, so this query does not specify which employee name should represent the department:
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →SELECT department_id, employee_name, COUNT(*)
FROM employees
GROUP BY department_id;
Choose a fix that matches the result you actually need. To count employees by department and show one aggregate name value:
SELECT department_id,
MAX(employee_name) AS example_employee,
COUNT(*) AS employee_count
FROM employees
GROUP BY department_id;
MAX(employee_name) returns the maximum name according to the column’s ordering; it does not mean “a representative employee” in any business-defined sense. If you want a count for each department-and-name combination, group by both:
SELECT department_id, employee_name, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id, employee_name;
Columns determined by a grouped key can be valid in MySQL where it can establish that functional dependency, but do not rely on arbitrary values from an ambiguous group. Disabling ONLY_FULL_GROUP_BY may hide the issue rather than give the query a well-defined result. See the MySQL 8.4 GROUP BY handling documentation.
When to use HAVING, a CTE, or a window function
Use HAVING when the query produces one row per group and the condition is about that group’s aggregate. It is the most direct option when the aggregate is calculated and filtered in the same query.
Use a CTE or derived table when you need several query stages, reuse an aggregate, join aggregate results elsewhere, or want to separate calculation from filtering. For example:
Best Value
- Stunning 15.6" FHD IPS Display: Experience crisp 1920x1080 resolution on this 15.6 inch laptop with an IPS panel that delivers wide viewing angles and vivid colors. The narrow-bezel design maximizes screen real estate for comfortable viewing on this Win 11 laptop, whether you're studying or working.
- Celeron J4105 Processor & 256GB SSD: Powered by a reliable Celeron J4105 processor paired with 12GB DDR4 memory and a fast 256GB M.2 SSD. This laptop computer supports SSD expansion up to 2TB and TF card expansion up to 1TB, so your storage grows with your needs. Delivers smooth multitasking for daily productivity.
- AI-Powered Win 11 Laptop: Built-in AI features enhance your productivity with smart assistance for writing, summarizing, and task management. Pre-installed with Win 11 and includes Office 365 subscription. This student laptop is backed by 1-year warranty and 24/7 customer support.
- All-Day 7000mAh Battery & 180° Hinge: The high-capacity 7000mAh battery keeps this laptop powered through long classes or meetings. The 180-degree lay-flat hinge lets you share your screen effortlessly during presentations. This durable laptop computer adapts to your dynamic workflow.
- Versatile Connectivity Hub: Equipped with USB 3.2, Type-C, Mini HDMI, and 3.5mm audio jack to connect all your peripherals. Stay online anywhere with high-speed 5G WiFi and Bluetooth 4.2. This college laptop keeps you connected at home, in the library, or on the go.
WITH category_totals AS (
SELECT category_id, SUM(amount) AS category_total
FROM sales
GROUP BY category_id
)
SELECT category_id, category_total
FROM category_totals
WHERE category_total > 10000;
Use a window function when you need to keep detail rows while calculating a value for each group. A grouped query collapses each department to one row:
SELECT department_id, AVG(salary) AS department_average
FROM employees
GROUP BY department_id
HAVING AVG(salary) > 75000;
A window query retains employee rows and adds the department average to each:
SELECT employee_id,
department_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS department_average
FROM employees;
To keep only employees earning above their department average, calculate the window value in a CTE, then filter it outside:
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →WITH employee_averages AS (
SELECT employee_id,
department_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS department_average
FROM employees
)
SELECT *
FROM employee_averages
WHERE salary > department_average;
In MySQL, window functions are evaluated after HAVING and may be used in the select list and ORDER BY, not directly in WHERE or HAVING. The outer query provides the required filtering stage. See MySQL 8.4 window function usage.
Advanced: HAVING with WITH ROLLUP
WITH ROLLUP adds subtotal and total rows to grouped results. MySQL’s GROUPING() function can identify those super-aggregate rows, including in HAVING:
SELECT year,
country,
SUM(profit) AS profit
FROM sales
GROUP BY year, country WITH ROLLUP
HAVING GROUPING(year, country) <> 0;
This keeps rollup rows rather than ordinary detail groups. A NULL in a rollup row may be a generated subtotal marker, not a stored NULL value; use GROUPING() to distinguish them. Read the MySQL references for GROUP BY modifiers and ROLLUP and GROUPING().
Quick Recap
Quick troubleshooting checklist
- Does the condition describe individual rows? Put it in
WHERE. - Does it depend on a group aggregate? Put it in
HAVING. - Are you trying to use an aggregate in
WHERE? Move that condition toHAVING. - Does a grouped query select a nonaggregated column that is neither grouped nor functionally determined by the grouping key? Clarify the intended result and correct the grouping or aggregation.
- Are you looking for missing rows after a
LEFT JOIN? UseCOUNT(child.id) = 0, notCOUNT(*) = 0. - Does a right-table predicate in
WHEREremove unmatched left-side rows? Move it to the join condition if those rows must remain. - Is an alias ambiguous or is portability important? Use a distinct alias or repeat the aggregate expression.
- Are you filtering a window-function result? Put the window calculation in a CTE or derived table, then filter in the outer query.
Quick reference
| Goal | Pattern |
|---|---|
| At least five orders per customer | GROUP BY customer_id HAVING COUNT(*) >= 5 |
| Groups with total sales above 10,000 | GROUP BY category_id HAVING SUM(amount) > 10000 |
| Rows from 2026 onward, then groups with at least 100 units | WHERE order_date >= '2026-01-01' GROUP BY product_id HAVING SUM(quantity) >= 100 |
| Customers with no orders | LEFT JOIN ... GROUP BY customer_id HAVING COUNT(order_id) = 0 |
| Test a single aggregate over the filtered table | SELECT COUNT(*) ... HAVING COUNT(*) > 100 |
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

