WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY runs. WHERE cannot use aggregate functions like SUM() or COUNT() because those values do not exist yet. HAVING is designed specifically for aggregate conditions. Use WHERE for row-level filters and HAVING for group-level filters in SQL.
- WHERE runs before grouping and cannot reference aggregate functions.
- HAVING runs after grouping and is designed for aggregate conditions.
- You can use both clauses in the same query; they filter at different stages.
- HAVING can technically work without GROUP BY, but it is rarely useful outside edge cases.
- Knowing this distinction is one of the most common SQL questions in data analyst interview questions rounds at Indian tech companies.
How WHERE Filters Rows in SQL
WHERE is the workhorse of SQL filtering. It evaluates each row in the source table before the database engine groups or aggregates anything. Think of it as a gatekeeper: only rows that pass the WHERE condition move forward in the query pipeline. Understanding where and having in SQL starts with understanding this row-level filter.
Basic WHERE Syntax
Here is a simple example. Say you have an orders table for an e-commerce company like Flipkart or Meesho, and you want only orders from Mumbai:
SELECT customer_id, order_amount
FROM orders
WHERE city = 'Mumbai';
The database scans every row, keeps the ones where city = 'Mumbai', and discards the rest. No grouping involved yet.
What WHERE Cannot Do
WHERE cannot reference the result of an aggregate function. This query will throw an error:
-- This FAILS
SELECT city, SUM(order_amount)
FROM orders
WHERE SUM(order_amount) > 50000
GROUP BY city;
The reason is simple: at the point WHERE runs, SUM() has not been calculated yet. The database does not know the group totals because it has not grouped anything. This is the single most common mistake beginners make when learning where and having in SQL, and it shows up regularly in technical interviews at companies like Infosys, Wipro and TCS.
WHERE with Multiple Conditions
You can chain conditions with AND and OR. A query pulling high-value orders from Delhi or Bengaluru looks like this:
SELECT order_id, customer_id, order_amount
FROM orders
WHERE (city = 'Delhi' OR city = 'Bengaluru')
AND order_amount > 10000;
This still filters rows, not groups. Every condition here references a column value in a single row, not a computed aggregate across multiple rows.
How HAVING Filters Groups in SQL
HAVING was created specifically to filter the output of GROUP BY. After the database groups rows and computes aggregates, HAVING decides which groups survive into the final result set. That is the whole job. When comparing where and having in SQL, HAVING is always the post-grouping filter.
Basic HAVING Syntax with GROUP BY
Using the same orders table, here is how you would find every city where total orders exceed Rs 5,00,000:
SELECT city, SUM(order_amount) AS total_sales
FROM orders
GROUP BY city
HAVING SUM(order_amount) > 500000;
The database first groups all rows by city, calculates the SUM for each group, and then HAVING filters out any city group that does not meet the threshold. This is exactly what WHERE cannot do.
How HAVING Works in MySQL
MySQL follows the SQL standard closely here. The MySQL 8.0 SELECT documentation confirms that HAVING is applied after GROUP BY and before ORDER BY. MySQL also allows HAVING to reference column aliases defined in the SELECT list, which is a MySQL-specific extension not available in all databases. So in MySQL you can write:
SELECT city, SUM(order_amount) AS total_sales
FROM orders
GROUP BY city
HAVING total_sales > 500000;
Standard SQL would require you to repeat SUM(order_amount) in the HAVING clause. MySQL’s flexibility here is handy, but do not rely on it if you are writing portable SQL for PostgreSQL or Oracle.
Can You Use HAVING Without GROUP BY?
Yes, technically. Without GROUP BY, the entire result set is treated as one single group. This query returns the whole table only if the total of all order amounts exceeds Rs 10,00,000:
SELECT SUM(order_amount) AS grand_total
FROM orders
HAVING SUM(order_amount) > 1000000;
It works, but it is a niche use case. In practice, almost every HAVING clause you write in production or in an interview will sit alongside a GROUP BY.
Using Both WHERE and HAVING Together in SQL
This is where things get genuinely useful. You can combine WHERE and HAVING in the same query to filter at both levels: rows first, then groups. This is a pattern that data engineers and analysts use constantly. Mastering where and having in SQL together is what separates intermediate from advanced SQL writers.
A Real Combined Query
Suppose you want to find cities where the total sales of orders placed in 2024 exceeded Rs 5,00,000, but you only care about orders with a status of ‘completed’:
SELECT city, SUM(order_amount) AS total_sales
FROM orders
WHERE status = 'completed'
AND order_year = 2024
GROUP BY city
HAVING SUM(order_amount) > 500000
ORDER BY total_sales DESC;
WHERE eliminates non-completed and non-2024 rows first. The database then groups the surviving rows by city and sums them. HAVING then drops any city group below the Rs 5,00,000 threshold. ORDER BY sorts the final output.
WHERE vs HAVING in SQL: Side-by-Side Comparison
| Feature | WHERE | HAVING |
|---|---|---|
| Filters | Individual rows | Groups (after GROUP BY) |
| Runs at | Before grouping | After grouping |
| Aggregate functions | Not allowed | Allowed and intended |
| Used with GROUP BY | Optional | Almost always |
| Performance tip | Filter early to reduce rows processed | Filter after grouping; always use WHERE first to reduce load |
| SQL standard support | All major databases | All major databases |
| Can reference column alias from SELECT | No (in standard SQL) | Yes in MySQL; No in standard SQL |
A practical tip from real-world SQL work: always push as much filtering as possible into WHERE. If you can eliminate rows before grouping, the database has less data to aggregate. HAVING is not a substitute for WHERE; using HAVING to filter non-aggregate conditions is a performance anti-pattern. This is one of the most tested concepts when interviewers probe knowledge of where and having in SQL.
SQL Order of Execution: Where WHERE and HAVING Fit
Understanding where WHERE and HAVING sit in SQL’s processing order makes everything click. SQL does not execute clauses in the order you write them. The logical order is fixed by the standard, and every major database, including MySQL, PostgreSQL and Oracle, follows it.
The Logical Order SQL Runs Clauses
- FROM – identify the source tables and join them if needed
- WHERE – filter individual rows from the source
- GROUP BY – group the surviving rows
- HAVING – filter the groups
- SELECT – compute the output columns and aliases
- DISTINCT – remove duplicate rows if specified
- ORDER BY – sort the final result
- LIMIT / OFFSET – restrict the number of rows returned
This order explains every question about where and having in SQL. SELECT runs at step 5, which is why WHERE (step 2) cannot see column aliases defined in SELECT. It also explains why HAVING can use aggregates: by step 4, GROUP BY has already run and the aggregate values exist.
Why This Matters for Interviews and Real Projects
According to the Stack Overflow Developer Survey 2024, SQL remains the third most commonly used language globally, with over 51% of professional developers using it regularly. According to the NASSCOM Technology Sector Report 2024, India’s data and analytics talent demand is growing at over 30% year-on-year, with SQL listed as the top required skill across data analyst and data engineer job descriptions on platforms like Naukri and LinkedIn India. The TIOBE Index for 2024 consistently ranks SQL among the top 10 programming languages worldwide, reflecting its continued dominance in enterprise and product companies alike.
At that level of adoption, interviewers at companies like Infosys, Wipro, TCS, Zomato and Paytm treat SQL execution order as a baseline expectation, not an advanced topic. If you are preparing for data roles, this concept pairs directly with understanding how query optimisers work. Students doing a BSc Computer Science or MCA will encounter execution order in database management system (DBMS) coursework, and it is equally relevant if you are looking at jobs and salary after MCA in data or backend engineering.
A common on-the-job mistake: writing a query with a HAVING clause when a WHERE clause would do the job faster. If the condition does not involve an aggregate, it belongs in WHERE. Always. Letting HAVING do row-level filtering is like checking every passenger’s ticket after the flight has landed.
If you are building data analytics projects with real datasets, getting these filters right is the difference between a query that runs in milliseconds and one that times out on a table with millions of rows. And if you are curious about the broader career path, read up on how to become a data engineer to see where SQL fits into the full skill stack. For those weighing career options, the data analyst vs data scientist comparison breaks down exactly which SQL skills each role demands in the Indian job market.
Frequently Asked Questions
What is the difference between WHERE and HAVING in SQL?
WHERE filters individual rows before any grouping occurs and cannot use aggregate functions. HAVING filters groups after GROUP BY has run and is specifically designed for aggregate conditions like SUM(), COUNT() and AVG(). The key rule when working with where and having in SQL: if your condition references an aggregate, use HAVING; if it references a plain column value, use WHERE.
Can I use HAVING without GROUP BY in SQL?
Yes. Without GROUP BY, SQL treats the entire result as one group, so HAVING applies to that single group. For example, HAVING COUNT(*) > 100 would return the result only if the table has more than 100 rows total. It is valid SQL, but it is rarely what you actually need in a real query.
How does HAVING work in MySQL specifically?
MySQL follows the SQL standard: HAVING runs after GROUP BY and before ORDER BY. MySQL also allows HAVING to reference column aliases from the SELECT list, which is a MySQL-specific extension. The MySQL 8.0 documentation covers this behaviour in detail. Do not rely on alias references in HAVING if your code needs to run on PostgreSQL or Oracle.
Can WHERE use aggregate functions in SQL?
No. WHERE runs before GROUP BY, so aggregate values have not been computed yet. Writing WHERE SUM(sales) > 1000 will produce an error in every major SQL database. If you need to filter on an aggregate result, move that condition into a HAVING clause after your GROUP BY. This is one of the most tested aspects of where and having in SQL interviews.
What is SQL’s order of execution and where do WHERE and HAVING fit?
SQL processes clauses in this fixed order: FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT. This is the logical processing order, not the order you write the clauses. Understanding this sequence explains why WHERE cannot see SELECT aliases and why HAVING can reference aggregate functions that WHERE cannot. This is a standard DBMS topic covered in BSc Computer Science and MCA programmes across Indian universities.
What is the performance difference between WHERE and HAVING in SQL?
WHERE is faster for non-aggregate filters because it reduces the number of rows before grouping happens. HAVING operates on already-grouped data, so if you use HAVING for a condition that does not involve an aggregate, you are making the database do unnecessary work. Always use WHERE to filter rows early and reserve HAVING strictly for aggregate conditions.
The bottom line on WHERE and HAVING in SQL is straightforward: use WHERE to filter rows, use HAVING to filter groups, and always filter as early as possible for better performance. If you want to put this into practice right now, here are three steps you can take this week:
- Open MySQL Workbench or any online SQL editor, create a sample sales table, and write one query that uses WHERE, GROUP BY and HAVING together. Run it, then remove WHERE and observe how the result changes.
- Review the top data analyst interview questions and note how many hinge on SQL fundamentals like where and having in SQL. Practice explaining the execution order out loud, not just writing it.
- Check out 3.0 University’s full catalogue of online certification courses in Cybersecurity, AI, Blockchain and Web3 to build on your SQL foundation with structured learning paths.
Strong SQL fundamentals are the foundation for roles in data engineering, backend development, ethical hacking and AI. The CEH v13 AI online course is a particularly strong next step if you want to apply your programming knowledge in cybersecurity, where understanding databases and queries is directly relevant to SQL injection, penetration testing and secure coding.
Last updated: June 2025. Reviewed by the 3University editorial team.