6.1 Aggregate Functions & NULL Mechanics
Key Takeaways
- Oracle group (aggregate) functions operate across sets of rows to return a single summarized result per group or table.
- COUNT(*) counts all rows including duplicates and NULLs, COUNT(expr) counts non-NULL occurrences of expr, and COUNT(DISTINCT expr) counts unique non-NULL values.
- All aggregate functions except COUNT(*) automatically ignore NULL values during calculation; use NVL or COALESCE to force NULLs into calculations (e.g., AVG(NVL(comm, 0))).
- If an aggregate function processes a dataset where all input values are NULL (or zero rows match), COUNT returns 0, while all other group functions (SUM, AVG, MIN, MAX, MEDIAN, STDDEV, VARIANCE) return NULL.
- SUM, AVG, STDDEV, and VARIANCE require numeric datatypes, whereas MIN and MAX operate on numeric, character, and datetime datatypes.
6.1 Aggregate Functions & NULL Mechanics
In relational database management, data analysis frequently requires calculating summary metrics across sets of records rather than transforming individual row values. Oracle SQL distinguishes sharply between single-row functions (which return one result for every individual row processed) and group functions (also known as aggregate functions or multi-row functions), which operate on collections of rows to yield a single summarized result per group or entire table.
Mastering group functions for the Oracle Database SQL Certified Associate (1Z0-071) exam requires understanding their mathematical mechanics, valid input datatypes, distinct modifiers, and—most importantly—their specialized behavior when encountering NULL values.
Overview of Oracle Group Functions
Oracle SQL provides a comprehensive suite of built-in aggregate functions for mathematical, statistical, and data-gathering operations:
+-----------------------------------------------------------------------------------+
| ORACLE GROUP FUNCTIONS |
+---------------------+-------------------------------------------------------------+
| Function | Description & Primary Purpose |
+---------------------+-------------------------------------------------------------+
| AVG(expr) | Calculates the mathematical mean of expr |
| SUM(expr) | Computes the arithmetic sum of expr |
| COUNT(*) | Returns the total number of rows retrieved |
| COUNT(expr) | Returns the number of non-NULL occurrences of expr |
| MIN(expr) | Identifies the lowest value of expr |
| MAX(expr) | Identifies the highest value of expr |
| MEDIAN(expr) | Calculates the middle value or 50th percentile of expr |
| STDDEV(expr) | Computes the sample standard deviation of expr |
| VARIANCE(expr) | Computes the sample statistical variance of expr |
+---------------------+-------------------------------------------------------------+
Syntax and Options
The standard syntax for group functions in Oracle SQL is:
aggregate_function([DISTINCT | ALL] expression)
ALL(Default): Directs the aggregate function to include all non-null values, including duplicate values. If omitted,ALLis assumed automatically.DISTINCT: Forces the function to consider only unique, non-null values, discarding duplicates before performing the computation.expression: Represents a column name, constant, or arithmetic/character expression. Aggregate functions cannot operate directly on nested aggregate functions unless accompanied by aGROUP BYclause.
Datatype Compatibility and Return Types
Not all aggregate functions accept all datatypes. The 1Z0-071 exam regularly tests whether a given group function can be applied to character strings, dates, or numeric values.
| Function | Allowed Input Datatypes | Return Datatype | Behavior / Collation Rules |
|---|---|---|---|
AVG | NUMBER, FLOAT, BINARY_FLOAT, BINARY_DOUBLE | Numeric (NUMBER or binary float) | Computes mean; non-numeric types raise ORA-00932: inconsistent datatypes. |
SUM | NUMBER, FLOAT, BINARY_FLOAT, BINARY_DOUBLE | Numeric (NUMBER or binary float) | Computes total; non-numeric types raise ORA-00932. |
COUNT | Any datatype (CHAR, VARCHAR2, NUMBER, DATE, TIMESTAMP, CLOB, BLOB) | NUMBER | Returns integer count of rows or non-null values. |
MIN | NUMBER, CHAR, VARCHAR2, DATE, TIMESTAMP, INTERVAL | Same as input datatype | Lowest number, earliest date/time, or lowest character string in collation order. |
MAX | NUMBER, CHAR, VARCHAR2, DATE, TIMESTAMP, INTERVAL | Same as input datatype | Highest number, latest date/time, or highest character string in collation order. |
MEDIAN | NUMBER, DATE, TIMESTAMP, INTERVAL | NUMBER or Datetime | Continuous percentile calculation; character datatypes raise ORA-00932. |
STDDEV | NUMBER, FLOAT, BINARY_FLOAT, BINARY_DOUBLE | NUMBER or binary float | Square root of variance; numeric only. |
VARIANCE | NUMBER, FLOAT, BINARY_FLOAT, BINARY_DOUBLE | NUMBER or binary float | Sample variance; numeric only. |
Character and Date Collation in MIN / MAX
When MIN and MAX are applied to non-numeric columns, Oracle determines ordering based on the binary ASCII/Unicode encoding or session linguistic sort:
-- Evaluating MIN/MAX across character and date columns
SELECT
MIN(last_name) AS first_alphabetical_name,
MAX(last_name) AS last_alphabetical_name,
MIN(hire_date) AS earliest_hired_employee,
MAX(hire_date) AS most_recent_hire
FROM employees;
MIN(last_name)returns'Abel'(lowest alphabetical sort value).MAX(last_name)returns'Zlotkey'(highest alphabetical sort value).MIN(hire_date)returns'13-JAN-2001'(the earliest chronological date).MAX(hire_date)returns'21-APR-2008'(the latest chronological date).
The Three Variants of COUNT
The COUNT function behaves differently depending on whether an asterisk (*), an expression (expr), or the DISTINCT keyword is passed as an argument. Understanding these differences is critical for exam success.
+-----------------------------------------------------------------------------------+
| COUNT VARIATIONS |
+---------------------+-------------------------------------------------------------+
| COUNT(*) | Counts EVERY row in the result set, including rows where |
| | individual or all column values are NULL. |
+---------------------+-------------------------------------------------------------+
| COUNT(expr) | Evaluates expr for each row and counts ONLY rows where expr |
| | is NOT NULL. Duplicate non-null values are counted. |
+---------------------+-------------------------------------------------------------+
| COUNT(DISTINCT expr)| Evaluates expr, filters out duplicate values, and counts |
| | ONLY unique non-NULL occurrences. |
+---------------------+-------------------------------------------------------------+
Practical Demonstration: Sample Dataset Walkthrough
Consider the following sample table SAMPLE_STAFF containing 6 rows:
| EMP_ID | FIRST_NAME | DEPARTMENT_ID | COMMISSION_PCT | SALARY |
|---|---|---|---|---|
| 101 | Neena | 10 | 0.20 | 10000 |
| 102 | Lex | 10 | 0.10 | 12000 |
| 103 | John | 20 | 0.20 | 8000 |
| 104 | Karen | 20 | NULL | 9000 |
| 105 | Jon | NULL | NULL | 7500 |
| 106 | David | 20 | NULL | 6500 |
Let us evaluate the results of different COUNT expressions on SAMPLE_STAFF:
SELECT
COUNT(*) AS total_rows,
COUNT(department_id) AS count_dept,
COUNT(DISTINCT department_id) AS count_dist_dept,
COUNT(commission_pct) AS count_comm,
COUNT(DISTINCT commission_pct) AS count_dist_comm
FROM sample_staff;
Evaluation Walkthrough:
COUNT(*): Evaluates all rows in the table. Result =6.COUNT(department_id): Rows 101, 102, 103, 104, and 106 have non-null department IDs (10, 10, 20, 20, 20). Row 105 isNULL. Result =5.COUNT(DISTINCT department_id): Non-null values are10and20. Result =2.COUNT(commission_pct): Rows 101 (0.20), 102 (0.10), and 103 (0.20) are non-null. Rows 104, 105, and 106 areNULL. Result =3.COUNT(DISTINCT commission_pct): Unique non-null values are0.20and0.10. Result =2.
Automatic NULL Exclusion & The NVL Solution
A fundamental axiom of Oracle SQL group functions is:
The NULL Handling Rule: All aggregate functions (
AVG,SUM,COUNT(expr),MIN,MAX,MEDIAN,STDDEV,VARIANCE) automatically ignoreNULLvalues when computing results. The only exception isCOUNT(*), which counts rows regardless of column contents.
Impact on Averages: AVG(col) vs. AVG(NVL(col, 0))
Because AVG calculates the arithmetic mean by dividing the sum of values by the number of non-null values, omitting NULL values can significantly alter business calculations:
Using our SAMPLE_STAFF table where COMMISSION_PCT values are [0.20, 0.10, 0.20, NULL, NULL, NULL] across 6 employees:
SELECT
AVG(commission_pct) AS avg_comm_active,
AVG(NVL(commission_pct, 0)) AS avg_comm_all_staff
FROM sample_staff;
-
Calculation for
AVG(commission_pct):- Sum of non-null values: $0.20 + 0.10 + 0.20 = 0.50$
- Count of non-null values: $3$
- Result: $\frac{0.50}{3} \approx \mathbf{0.1667}$
- Business Meaning: The average commission earned among employees eligible for commission.
-
Calculation for
AVG(NVL(commission_pct, 0)):NVLsubstitutes0for the 3NULLrows:[0.20, 0.10, 0.20, 0, 0, 0]- Sum of values: $0.20 + 0.10 + 0.20 + 0 + 0 + 0 = 0.50$
- Count of values: $6$
- Result: $\frac{0.50}{6} \approx \mathbf{0.0833}$
- Business Meaning: The average commission across the entire workforce, including non-commissioned staff.
Exam Trap: When a question asks for "the average bonus across all employees in the department," examine whether employees with
NULLbonuses should be treated as having earned zero. If yes, the query must wrap the column inNVL(bonus, 0)orCOALESCE(bonus, 0).
Aggregate Behavior on All-NULL Datasets or Empty Sets
What happens when a query aggregates a table that contains zero matching rows, or when every value in the selected column is NULL?
-- Querying against an empty subset
SELECT
COUNT(*) AS cnt_all,
COUNT(salary) AS cnt_sal,
SUM(salary) AS sum_sal,
AVG(salary) AS avg_sal,
MIN(salary) AS min_sal,
MAX(salary) AS max_sal
FROM employees
WHERE department_id = 9999; -- No rows match this condition
| Expression | Returned Result | Explanation |
|---|---|---|
COUNT(*) | 0 | COUNT always returns a non-negative integer representing the count of rows. |
COUNT(salary) | 0 | Zero non-null values found; returns numeric 0. |
SUM(salary) | NULL | No non-null values exist to sum; returns NULL (NOT 0). |
AVG(salary) | NULL | Cannot divide by zero count of values; returns NULL. |
MIN(salary) | NULL | No minimum value exists; returns NULL. |
MAX(salary) | NULL | No maximum value exists; returns NULL. |
SUMMARY OF EMPTY / ALL-NULL SET BEHAVIOR:
+---------------------------+----------------+
| Function | Result |
+---------------------------+----------------+
| COUNT(*) / COUNT(expr) | 0 |
| SUM, AVG, MIN, MAX | NULL |
| MEDIAN, STDDEV, VARIANCE | NULL |
+---------------------------+----------------+
If an application requires SUM or AVG to return 0 instead of NULL when no rows exist, the aggregate function must be wrapped in NVL: NVL(SUM(salary), 0).
A table named BONUSES contains 4 rows with the following BONUS values: 1000, 2000, NULL, and 3000. What are the results of AVG(bonus) and AVG(NVL(bonus, 0)) respectively?
Which group functions are valid for use with character string datatypes (such as VARCHAR2) in Oracle SQL?
A query executes SELECT COUNT(*), COUNT(commission_pct), SUM(commission_pct) FROM employees WHERE department_id = 888;. If department 888 has no employees in the table, what values are returned?