1. What is GROUP BY in SQL.
• GROUP BY groups rows with same values
• Used with aggregate functions
• One row per group in output
Example
Find total salary per department
FROM employees
GROUP BY department;
Logic
• Rows grouped by department
• SUM runs on each group
2. Why do we use aggregate functions.
• To summarize data
• To calculate totals, averages, counts
Common functions
• COUNT
• SUM
• AVG
• MIN
• MAX
3. What happens if you use GROUP BY without aggregation.
• Output shows unique combinations of grouped columns
Example
FROM employees
GROUP BY department;
Logic
• Acts like DISTINCT
4. Difference between WHERE and HAVING.
• WHERE filters rows
• HAVING filters groups
• WHERE runs before GROUP BY
• HAVING runs after GROUP BY
Example
Find departments with total salary above 5,00,000
FROM employees
GROUP BY department
HAVING SUM(salary) > 500000;
5. Can you use WHERE with GROUP BY.
• Yes
• WHERE filters raw data before grouping
Example
Ignore inactive employees
FROM employees
WHERE status = 'Active'
GROUP BY department;
6. Common GROUP BY interview error.
Why does this query fail
FROM employees
GROUP BY department;
Answer
• Non aggregated column must be in GROUP BY
• name is missing
Correct query
FROM employees
GROUP BY department;
7. What's the difference between COUNT(*) COUNT(column)?
• COUNT(*) counts all rows
• COUNT(column) skips NULL values
Example
SELECT COUNT(delivery_date) FROM orders;
8. Find total orders per customer.
FROM orders
GROUP BY customer_id;
Logic
• One row per customer
• COUNT runs per customer group
9. Find customers with more than 5 orders.
FROM orders
GROUP BY customer_id
HAVING COUNT(order_id) > 5;
Logic
• GROUP first
• Filter groups using HAVING
10. Execution order for GROUP BY queries.
• FROM
• WHERE
• GROUP BY
• HAVING
• SELECT
• ORDER BY
Interview advice
• Say execution order clearly
• Explain using one simple example
• Avoid mixing WHERE and HAVING logic
Double Tap ♥️ For More