HAVING for filtering groups in PostgreSQL - Time & Space Complexity
When we use HAVING in SQL, we filter groups after grouping data. Understanding how this affects time helps us know how query speed changes as data grows.
We want to see how the time to run a query with HAVING changes when the number of rows or groups increases.
Analyze the time complexity of the following code snippet.
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
This query groups employees by their department and then filters to keep only departments with more than 10 employees.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning all employee rows once to group them by department.
- How many times: Each employee row is processed once during grouping.
- Secondary operation: After grouping, filtering groups with HAVING condition is done once per group.
- How many times: Number of groups depends on distinct departments, usually much smaller than total rows.
As the number of employees grows, the time to scan and group them grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row scans and grouping steps |
| 100 | About 100 row scans and grouping steps |
| 1000 | About 1000 row scans and grouping steps |
Filtering groups with HAVING happens after grouping, so its cost depends on the number of groups, which usually grows slower than total rows.
Overall, the main work grows roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time to run the query grows roughly in direct proportion to the number of rows in the table.
[X] Wrong: "HAVING filters rows one by one before grouping, so it reduces the work early."
[OK] Correct: HAVING filters after grouping, so all rows must be processed first to form groups before filtering happens.
Understanding how grouping and filtering with HAVING affects query time helps you explain database performance clearly and shows you know how data size impacts operations.
"What if we added an index on the department column? How would the time complexity change?"
Practice
HAVING clause in a PostgreSQL query?Solution
Step 1: Understand the role of HAVING
The HAVING clause is used to filter groups created by GROUP BY based on aggregate conditions.Step 2: Differentiate HAVING from WHERE
WHERE filters rows before grouping, HAVING filters groups after aggregation.Final Answer:
To filter groups after aggregation -> Option DQuick Check:
HAVING filters groups = D [OK]
- Confusing HAVING with WHERE clause
- Thinking HAVING sorts data
- Using HAVING without GROUP BY
Solution
Step 1: Identify correct order of clauses
GROUP BY must come before HAVING in SQL syntax.Step 2: Check aggregate usage in HAVING
HAVING uses aggregate functions like SUM(sales) to filter groups.Final Answer:
SELECT store, SUM(sales) FROM sales_data GROUP BY store HAVING SUM(sales) > 1000; -> Option BQuick Check:
GROUP BY before HAVING = B [OK]
- Placing HAVING before GROUP BY
- Using WHERE with aggregate functions
- Incorrect clause order
orders with columns customer_id and amount, what will this query return?SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id HAVING COUNT(*) > 2;
Solution
Step 1: Understand the GROUP BY and COUNT(*)
The query groups rows by customer_id and counts orders per customer.Step 2: Apply HAVING filter
HAVING COUNT(*) > 2 keeps only customers with more than 2 orders.Final Answer:
All customers with more than 2 orders -> Option AQuick Check:
HAVING COUNT(*) > 2 filters groups with >2 rows [OK]
- Confusing > 2 with = 2
- Thinking HAVING causes syntax error
- Ignoring GROUP BY effect
SELECT department, AVG(salary) FROM employees HAVING AVG(salary) > 50000 GROUP BY department;
Solution
Step 1: Check clause order
SQL requires GROUP BY before HAVING clause.Step 2: Identify error in query
HAVING appears before GROUP BY, which is invalid syntax.Final Answer:
HAVING clause used before GROUP BY -> Option AQuick Check:
GROUP BY must precede HAVING [OK]
- Placing HAVING before GROUP BY
- Assuming AVG() not allowed in HAVING
- Confusing WHERE and HAVING
sales table with columns region, salesperson, and amount. Write a query to find regions where the total sales exceed 10,000 but only include salespeople who individually sold more than 3,000. Which query correctly applies HAVING to achieve this?Solution
Step 1: Understand filtering conditions
We want regions with total sales > 10,000 and salespeople with sales > 3,000.Step 2: Analyze correct logic
Group by region and salesperson, filter salespeople with >3000 sales using HAVING SUM(amount) > 3000, and filter regions with total sales > 10000 using a subquery in HAVING: region IN (SELECT region FROM sales GROUP BY region HAVING SUM(amount) > 10000).Step 3: Check HAVING usage
This correctly applies HAVING on both salesperson and region aggregates using subquery.Final Answer:
SELECT region, salesperson, SUM(amount) FROM sales GROUP BY region, salesperson HAVING SUM(amount) > 3000 AND region IN (SELECT region FROM sales GROUP BY region HAVING SUM(amount) > 10000); -> Option CQuick Check:
Use HAVING with subqueries for multi-level group filters [OK]
- Using WHERE with aggregate functions
- Incorrect clause order
- Combining unrelated HAVING conditions without subqueries
Ready to prove it?
Pass the test and this pattern moves unknown
