SQL Aggregate Functions, Grouping & Joins Formulas & Cheat Sheet
Complete chapter-wise reference, step-by-step formula explanations, structured table, and board exam trap warnings.
Core Concepts & Theoretical Foundations
- SQL Aggregate Functions: Perform calculation on a column of values across multiple rows and return a SINGLE scalar value: `COUNT(*)`, `COUNT(col)`, `SUM()`, `AVG()`, `MIN()`, `MAX()`. All aggregate functions (except `COUNT(*)`) ignore NULL values.
- `COUNT(*)` vs `COUNT(column)`: `COUNT(*)` counts total rows including rows with NULLs; `COUNT(column)` counts only rows where the specified column is NOT NULL.
- GROUP BY Clause: Groups rows having the same values in specified columns into summary rows. Any non-aggregate column in SELECT list MUST appear in GROUP BY clause.
- HAVING Clause vs WHERE Clause: `WHERE` filters individual rows BEFORE grouping is applied; `HAVING` filters aggregated groups AFTER `GROUP BY` is applied (can contain aggregate functions).
- Table Joins: Combining rows from two or more tables based on a common related column: Equi-join (`table1.id = table2.id`), Natural Join (automatically equates columns with identical names and removes duplicate column from output), Cross Join (Cartesian product).
Chapter Formulas & Equations (10 entries)
| # | Topic / Formula Name | Mathematical Form & Equation | Conditions, Meaning & Board Tips |
|---|---|---|---|
| 1 | Standard SQL Query Execution Order |
|
Logical query processing pipeline explaining why alias names cannot be used in WHERE clauses. |
| 2 | COUNT(*) vs COUNT(col) Null Handling Identity |
|
Crucial difference in SQL aggregation. |
| 3 | AVG Function Null Exclusion Formula |
|
Excluding NULL from denominator prevents downward skew in averages. |
| 4 | GROUP BY with HAVING Filter Template |
|
HAVING filters groups; WHERE cannot filter aggregate conditions like `AVG(salary) > 50000`. |
| 5 | Equi-Join Two Table Syntax |
|
Combines matching records using explicit foreign key equality in WHERE clause. |
| 6 | JOIN ON Modern ANSI Syntax |
|
ANSI standard separating join conditions from row filter conditions. |
| 7 | Natural Join Output Column Rule |
|
Eliminates redundant duplicate join columns automatically. |
| 8 | Table Alias Resolution Rule |
|
Simplifies qualifying column names and self-joins. |
| 9 | GROUP BY Multiple Columns |
|
Creates sub-group aggregations (e.g. average salary per job role within each department). |
| 10 | Maximum / Minimum Date Handling |
|
Date comparisons treat chronologically later dates as larger values. |
Step-by-Step Worked Board Exam Examples
Example 1: Given table `EMPLOYEE(EmpId, Name, Dept, Salary, Commission)`: EmpId: 101, 102, 103, 104 Salary: 50000, 60000, 40000, 70000 Commission: 2000, NULL, 1500, NULL Calculate the results of: (a) `SELECT COUNT(*), COUNT(Commission) FROM EMPLOYEE;` (b) `SELECT AVG(Commission) FROM EMPLOYEE;` (c) `SELECT Dept, COUNT(*) FROM EMPLOYEE GROUP BY Dept HAVING COUNT(*) >= 2;`
1. (a) `COUNT(*)` counts total rows = 4. `COUNT(Commission)` counts non-null rows (2000, 1500) = 2. Result: 4, 2.
2. (b) `AVG(Commission)` = Sum of non-null / count of non-null = (2000 + 1500) / 2 = 3500 / 2 = 1750 (NOT 3500 / 4). Result: 1750.
3. (c) Groups by Dept and outputs only those departments having 2 or more employees.
Example 2: Given tables `STUDENT(AdmNo, Name, ClassId)` and `CLASS(ClassId, ClassName, Incharge)`. Write an SQL query to display `AdmNo`, student `Name`, `ClassName`, and `Incharge` of all students.
1. Identify join key: `ClassId` is common to both tables.
2. Join query using WHERE clause:
`SELECT S.AdmNo, S.Name, C.ClassName, C.Incharge FROM STUDENT S, CLASS C WHERE S.ClassId = C.ClassId;`
3. Alternative ANSI syntax:
`SELECT S.AdmNo, S.Name, C.ClassName, C.Incharge FROM STUDENT S JOIN CLASS C ON S.ClassId = C.ClassId;`
Common Mistakes to Avoid in Exam
- Using WHERE instead of HAVING for aggregate conditions: Writing `WHERE AVG(Salary) > 50000` causes an SQL syntax error; aggregate conditions MUST be placed in `HAVING AVG(Salary) > 50000`.
- Selecting unaggregated columns not listed in GROUP BY: `SELECT Dept, Job, AVG(Salary) FROM EMP GROUP BY Dept;` is invalid because `Job` is neither aggregated nor in GROUP BY.
- Dividing SUM by total rows instead of non-null rows in AVG: SQL `AVG()` ignores NULLs, so denominator is `COUNT(col)`, NOT `COUNT(*)`.
- Forgetting the join condition: Omitting `WHERE T1.id = T2.id` causes a CARTESIAN PRODUCT, multiplying row counts and generating bogus mismatched pairs.
Target Practice Questions
Q1. Write a query to find the maximum and minimum salary in each department.
Correct Answer: `SELECT Dept, MAX(Salary), MIN(Salary) FROM EMPLOYEE GROUP BY Dept;`
Q2. What will `SELECT SUM(Comm) FROM EMP` return if all values of Comm are NULL?
Correct Answer: It will return `NULL`.
Q3. Write a query to display department names having an average salary greater than 60,000.
Correct Answer: `SELECT Dept, AVG(Salary) FROM EMPLOYEE GROUP BY Dept HAVING AVG(Salary) > 60000;`
Frequently Asked Questions
Q. What is the difference between WHERE clause and HAVING clause?
`WHERE` filters individual rows BEFORE they are grouped by GROUP BY, and cannot contain aggregate functions. `HAVING` filters summarized groups AFTER GROUP BY has executed, and can evaluate aggregate conditions (like `HAVING COUNT(*) > 5`).
Q. What does `COUNT(*)` return versus `COUNT(column)`?
`COUNT(*)` returns the total number of records in the table, including rows with NULL values. `COUNT(column)` returns only the number of rows where that specific column contains a non-NULL value.
Q. What is an Equi-Join in SQL?
An Equi-Join is a join that links tables based on equality between common column values (using the `=` comparison operator, e.g. `WHERE Emp.DeptId = Dept.DeptId`).
Q. What is a Natural Join?
A Natural Join is an equi-join that automatically matches columns with identical names across both tables and suppresses duplicate join columns from the final result table.
Q. Can aggregate functions be nested in standard SQL?
No, standard ANSI SQL does not allow nesting of aggregate functions like `MAX(AVG(Salary))` in a single query level; subqueries or derived tables must be used.