SQL Group Functions & Group By Clause Notes
1. Introduction to Aggregate Functions
(Top Margin Notes: 1. Rational, 2. Fun, 3. Logical)
Count Function Variations:
-
Query:
SELECT COUNT(*) - COUNT(sal) FROM emp;- Concept: Gives the count of employees not receiving salary (
NULLhandling). - Performance:
COUNT(*)is faster as the values are already present in the RAM (metadata/indexes).
- Concept: Gives the count of employees not receiving salary (
-
Query:
SELECT COUNT(*) FROM emp WHERE sal IS NOT NULL;- Performance Note: Due to the
WHEREclause, searching will slow down the select statement compared to the direct subtraction method above.
- Performance Note: Due to the
Arithmetic with Group Functions:
-
Query:
SELECT MAX(sal) / MIN(sal) FROM emp;- Calculation: $8000 / 3000 \rightarrow 2.67$
-
Rule: Multiple Group functions can be selected together separated by arithmetic operators.
Averages and Null Handling:
-
Method 1 (Two functions working simultaneously):
SELECT SUM(sal) / COUNT(*) FROM emp;- Calculation: $26000 / 5 \rightarrow 5200$
-
Method 2 (Using
NVL/IFNULL):SELECT AVG(IFNULL(sal, 0)) FROM emp;- Result: $5200$
- Performance Note: 1 function executed at a time. This method requires double the time compared to the arithmetic split.
2. Group Function Capabilities
Function Types & Data Types
SUM(col),AVG(col),STDDEV(col),VARIANCE(col): work with Number only.MIN,MAX,COUNT(col): work with All Data Types (Number, String/ename, Date/hiredate).
Summary Reports
- Query:
SELECT COUNT(*), MIN(sal), MAX(sal), SUM(sal), AVG(sal) FROM emp;- Result: Will show me all the totals at a glance.
- Usage: Summary Reports can give suitable aliases.
Syntax Rules
- In a single select statement, multiple group functions can be selected together (comma separated).
SELECT COUNT(ename), MIN(sal) FROM emp; -- Result: 5, 3000 - Error Scenario:
SELECT ename, MIN(sal) FROM emp;- Error:
enameis not a group function. You cannot select a raw column along with a group function unless it is in aGROUP BYclause.
- Error:
3. The WHERE Clause Limitations (Assumption Logic)
Assumption: 4th row Salary is 9000.
-
Query:
SELECT SUM(sal) FROM emp WHERE deptno = 1;- Calculation: $8 + 7 + 3 = 18000$
- Execution Location:
WHERE deptno = 1is used for searching in the Hard Disk (HD) only. - The
salcolumn is brought into the RAM only.
-
Query:
SELECT AVG(sal) FROM emp WHERE job = 'C';- Result: 6000
4. Restrictions on Group Functions
- You cannot select a standard column along with a Group Function (unless grouped).
- You cannot select single-row functions along with a Group Function (unless grouped).
- Example:
SELECT UPPER(ename), MIN(sal)...-> Error.
- Example:
- WHERE Clause Restriction:
- Query:
SELECT * FROM emp WHERE sal > AVG(7000); -- OR AVG(sal) - Result: ERROR.
- Reason: The
WHEREstatement is searching in the Server HD.AVGwill be generated when the column is operated on by the RAM. You cannot use Group Functions in theWHEREclause.
- Query:
5. The GROUP BY Clause
Purpose: Used for grouping. Execution Order:
WHERE(Searching/Filtering)GROUP BY(Sorting)- Update/Lock rows manually (if applicable)
Process Flow:
- Rows are retrieved from DB Server HD to Server RAM.
- Sorting is done
deptwise. - Grouping is done
deptwise.
Visualization (RAM Status)
A temporary table is created in RAM:
| DeptNo | Job | Sum(Sal) |
|---|---|---|
| 1 | C | 10000 |
| 1 | M | 8000 |
| 2 | C | 8000 |
| 2 | M | 8000 |
- Internal Logic: Behaves like a Nested For Loop.
- After the select statement is executed, the temp table is removed from RAM.
Rules for GROUP BY
- Selection Rule: Whichever column is present in
SELECTmust be present inGROUP BY(besides the group functions).SELECT deptno, SUM(sal) FROM emp GROUP BY deptno; - Reverse Selection Rule: Whichever column is present in
GROUP BYmay not be present in theSELECTstatement.SELECT SUM(sal) FROM emp GROUP BY deptno; -- This is Valid- Note: The column is present in the group calculation but not displayed in the final output.
6. Multi-Dimensional Queries
Multi-Column Grouping:
SELECT deptno, job, SUM(sal) FROM emp GROUP BY deptno, job;
Concepts:
- 2D Query: 1 column in
GROUP BY(Can plot X-Y graph, Bar graph). - 3D Query: 2 columns in
GROUP BY. - 4D Query: 3 columns in
GROUP BY. - Known as Multi-Dimensional Queries or Spatial Queries.
Performance Warning:
- No upper limit on the number of columns in
GROUP BYclause. - However: If you have a large number of rows in the table and a large number of columns in the
GROUP BYclause, the Select statement will be very slow. - Reason: Excessive sorting must take place internally.
7. Column Ordering Implications
- Order in
SELECTclause: Determines the position of the columns in the Output (User requirements). - Order in
GROUP BYclause: Determines the Sorting order, the Grouping order, the Summation order, and hence the speed of processing.- Tip: Write as per
COUNT(DISTINCT column_name)from Low to High.
- Tip: Write as per
Example (Optimization):
-
Consider:
COUNT(DISTINCT deptno) -> 25 -
Consider:
COUNT(DISTINCT job) -> 400 -
Option A:
GROUP BY deptno, job; -- Outer loop: Dept (25 iterations), Inner loop: Job. (FASTER) -
Option B:
GROUP BY job, deptno; -- Outer loop: Job (400 iterations). (SLOWER)
8. The HAVING Clause
Definition: HAVING clause works after the summation is done.
Process Comparison:
-
Using
WHERE(Efficient):SELECT deptno, SUM(sal) FROM emp WHERE sal > 7000 GROUP BY deptno;WHEREclause is used to retrieve rows from DB Server HD to Server RAM.
-
Using
HAVING(Specific Usage):SELECT deptno, SUM(sal) FROM emp GROUP BY deptno HAVING SUM(sal) > 17000;- ERROR Scenario:
HAVING sal > 7000. - Reason: After summation is done, individual
SALdoes not exist in Server RAM. OnlyDeptNoandSUM(sal)exist in RAM.
- ERROR Scenario:
Rules for HAVING:
- Whichever column is present in the
SELECTclause can be used in theHAVINGclause.- Example:
HAVING deptno = 1. - Note: This will work but is Inefficient. (Should have used
WHERE deptno = 1to filter earlier at the HD level).
- Example:
- Recommendation: Only Group Functions should be used in the
HAVINGclause.
9. Order of Clauses (Syntax)
The mandatory order of execution and syntax:
SELECT ...(Projection)FROM ...(Table selection)WHERE ...(Row filtering - HD level)GROUP BY ...(Sorting & Grouping - RAM level)HAVING ...(Group filtering - RAM level)ORDER BY ...(Final Sorting)
- Matrix Report:
SELECT deptno, COUNT(*), MIN(sal), MAX(sal), SUM(sal) FROM emp GROUP BY deptno ORDER BY 1; -- Sort by first column (deptno)
10. Nesting of Group Functions
Oracle RDBMS Feature:
- Nesting of Group functions is supported only in Oracle RDBMS. It is not supported in other RDBMS.
- Query:
SELECT MAX(SUM(sal)) FROM emp GROUP BY deptno; -- Result: 18000
Workaround for MySQL / Other RDBMS: Since direct nesting isn’t supported, use a Subquery (Derived Table).
-
Logic:
abcdis a temporary table created after the execution of the innerSELECT.- After execution, it is destroyed.
-
Query:
SELECT MAX(sum_sal) FROM ( SELECT SUM(sal) AS sum_sal FROM emp GROUP BY deptno ) AS abcd;- Result: 18000
Summary of Execution Flow
- WHERE: Retrieves rows from DB Server HD to Server RAM.
- GROUP BY: Sorts and Groups data in RAM.
- HAVING: Filters the summarized data in RAM.
- SELECT: Projects the specific columns/calculations requested.