PL/SQL Statistics Library

Build a reusable Oracle PL/SQL statistics library using frequency tables, descriptive statistics, variance, standard deviation and percentiles.

1. A reusable statistics library

The STATS package in APPSDEMO takes raw numeric observations, builds a frequency table and derives descriptive statistics from it. It provides a common calculation engine for numeric lists, PL/SQL arrays and data stored against a statistics project in Oracle. The result contains both the summary statistics and the frequency table from which they were calculated.

The design principle is to build the frequency table once and reuse it. This is particularly useful when a dataset contains many repeated values, or when several percentiles are required for the same dataset.

GitHub - STATS package specification · package body

2. The STATS package

The package provides 23 public functions and two display procedures. Refer to the linked specification for the parameter declarations and return types. The following table describes their roles.

STATS public functions and procedures
RoutinePurpose
get_statsCore calculation: array to frequency table and summary record.
get_stats_arrayArray entry point; delegates to GET_STATS.
get_stats_listConvert comma-separated numbers to an array and calculate statistics.
get_stats_projectRetrieve observations from STATS_DATA for a project and calculate statistics.
populate_frequency_tableSort observations and store one row for each distinct key and its frequency.
frequency_table_sumSum of key multiplied by frequency.
frequency_table_countTotal number of observations (sum of frequencies).
frequency_table_meanArithmetic mean: sum divided by count.
frequency_table_medianMiddle observation, or average of the middle two.
frequency_table_modeReturn all keys tied for the highest frequency.
frequency_table_lowestFirst (lowest) key in the sorted frequency table.
frequency_table_highestLast (highest) key in the sorted frequency table.
frequency_table_rangeHighest minus lowest.
variance_popPopulation variance (divide by N).
variance_sampSample variance (divide by N − 1; NULL for N < 2).
stddev_popSquare root of population variance.
stddev_sampSquare root of sample variance.
percentile_contContinuous percentile, using linear interpolation.
percentile_discDiscrete percentile, returning an observed numeric value.
iqrContinuous 75th percentile minus continuous 25th percentile.
value_at_rankReturn key at a one-based observation rank, using cumulative frequencies.
median_arrayDirect median of a pre-sorted numeric array.
medianConvert a numeric list to an array, sort and calculate its median.
display_frequency_tableProcedure: display the frequency table.
display_statsProcedure: display summary and requested percentiles (default 0.5).

3. Entry points and the common calculation engine

Use the entry point that matches the source of your data. All four GET_STATS entry points ultimately use the same frequency-table calculation. The project interface bulk collects values from STATS_DATA, checks for NULL observations and copies them to a numeric VARRAY.

  FUNCTION get_stats(
    p_array IN plsql_types.t_number_array
  ) RETURN plsql_types.t_stats_result;
  FUNCTION get_stats_array(
    p_array IN plsql_types.t_number_array
  ) RETURN plsql_types.t_stats_result;
  FUNCTION get_stats_list(
    p_list IN VARCHAR2
  ) RETURN plsql_types.t_stats_result;
  FUNCTION get_stats_project(
    p_project_id IN stats_project.stats_project_id%TYPE
  ) RETURN plsql_types.t_stats_result;

The core GET_STATS function requires a non-empty, initialised array of numbers without NULL elements. The frequency-table builder accepts numeric values, including fractional and negative values. The list interface uses numeric conversion; use a decimal convention compatible with your Oracle session and the comma delimiter. The collection must fit within the capacity of PLSQL_TYPES.T_NUMBER_ARRAY.

Input and error handling: check the returned summary (for example, stats.sum_values IS NULL) and diagnostic messages before using or displaying results. Direct frequency-table routines expect a valid, dense, ascending table of distinct keys with positive frequencies. Do not supply a NULL or empty list. Not every public helper validates all of these preconditions independently.

4. Build the frequency table once

POPULATE_FREQUENCY_TABLE checks for NULL inputs and NULL elements, sorts the array in ascending order using UTIL_NUMERIC.SORT_ARRAY, and counts each run of equal values. It stores each distinct numeric value as a key and the number of observations equal to it as a frequency. This is an exact representation of the numeric distribution, not a grouped histogram with arbitrary interval widths.

tb_frequency_table := populate_frequency_table(p_array);

Consider the original example array 1,1,2,2,2,4,5. Seven observations are represented by four frequency rows.

Frequency table with cumulative ranks
KeyFrequencyCumulative frequencyObservation ranks
1221–2
2353–5
4166
5177
Frequency distribution of seven observationsKey 1 occurs twice, key 2 three times, key 3 does not occur, and keys 4 and 5 occur once each. Frequency 0 1 2 3 21 32 03 14 15 Observed numeric value (key)
Figure 1. Exact-value frequencies. Key 3 has no observations and is not stored in the frequency table.

The cumulative frequencies identify where each distinct value occurs in the conceptual sorted array. VALUE_AT_RANK walks the table until the running frequency reaches the required one-based rank. For this example rank 4 lies in the row for key 2; the median is therefore 2. Use ranks from 1 through N; the current helper has a last-key fallback for larger ranks.

5. Calculate and return summary statistics

Once the frequency table is built, GET_STATS calculates its summary by calling the individual routines. The following assignments are taken directly from the package body.

    rec_stats.sum_values      := frequency_table_sum(tb_frequency_table);
    rec_stats.n_total         := frequency_table_count(tb_frequency_table);
    rec_stats.distinct_n      := tb_frequency_table.COUNT;
    rec_stats.mean            := frequency_table_mean(tb_frequency_table);
    rec_stats.median          := frequency_table_median(tb_frequency_table);
    rec_stats.mode_values     := frequency_table_mode(tb_frequency_table); -- table of NUMBER
    rec_stats.lowest          := frequency_table_lowest(tb_frequency_table);
    rec_stats.highest         := frequency_table_highest(tb_frequency_table);
    rec_stats.range           := frequency_table_range(tb_frequency_table);
    rec_stats.variance_pop    := variance_pop(tb_frequency_table);
    rec_stats.variance_samp   := variance_samp(tb_frequency_table);
    rec_stats.stddev_pop      := stddev_pop(tb_frequency_table);
    rec_stats.stddev_samp     := stddev_samp(tb_frequency_table);
    rec_stats.iqr             := iqr(tb_frequency_table);

For each distinct key x with frequency f, its contribution to the sum is fx. The total count is the sum of the frequencies, and the distinct count is the number of rows. The mean is the weighted sum divided by the total count.

The population variance is the sum of f(x − mean)² divided by N; sample variance divides the same sum by N − 1. Standard deviation is the square root of the corresponding variance. Sample variance and sample standard deviation are undefined for a single observation and return NULL. The mode routine collects every key tied for the maximum frequency, including all distinct keys if their frequencies are equal.

The calculation routines do not modify the supplied frequency table. They are not strictly side-effect-free: error handling may invoke UTIL_ADMIN.LOG_MESSAGE, and the display procedures deliberately produce diagnostic output.

Result structure

The composite record PLSQL_TYPES.T_STATS_RESULT contains stats (a summary record) and freq_tbl (the frequency table). The frequency rows contain a NUMBER key and a PLS_INTEGER frequency; the mode values form a numeric nested table. Returning both components enables display and later calculations without recreating the distribution.

TYPE t_stats_result IS RECORD (
  stats       t_stats_summary,
  freq_tbl    t_frequency_table
);

See PLSQL_TYPES in the repository for the full type declarations.

6. Discrete and continuous percentiles

Percentile functions operate on the frequency table, not the raw observations. Their parameter is a proportion from 0 to 1 inclusive (for example, 0.75 for the 75th percentile). Invalid or NULL percentile parameters return NULL. Both functions return NUMBER, preserving fractional observed values in discrete calculations as well as interpolated values in continuous calculations.

  FUNCTION percentile_disc(
    p_frequency_table IN plsql_types.t_frequency_table,
    p_pct             IN NUMBER 
  ) RETURN NUMBER;
  FUNCTION percentile_cont(
    p_frequency_table IN plsql_types.t_frequency_table,
    p_pct             IN NUMBER 
  ) RETURN NUMBER;

Discrete: use rank max(1, ceil(p × N)) and return the corresponding observed value. Continuous: calculate position 1 + (N − 1) × p, then interpolate linearly between the observations at the floor and ceiling of that position. An integer position requires no interpolation.

For the seven observations in section 4, the 75th percentile has discrete rank 6 (value 4), while the continuous position is 5.5, halfway between values 2 and 4 (result 3). The continuous 25th percentile is 1.5, so the IQR is 3 − 1.5 = 1.5. A percentile need not be a value actually observed unless the discrete method is used.

GET_STATS stores IQR in the summary, using continuous percentiles internally. Arbitrary percentiles are calculated on demand using the returned frequency table. DISPLAY_STATS accepts an optional percentile and displays both types, defaulting to 0.5.

7. Complexity and design trade-offs

Let N be the number of observations and D the number of distinct values, with D no greater than N. Sorting is necessary for the sequential grouping approach. The current UTIL_NUMERIC.SORT_ARRAY uses nested loops comparing pairs of elements, so sorting is O(N²), not O(N log N). Once sorted, compressing equal values into frequency rows takes O(N). The full frequency-table build is consequently quadratic with the current sort.

Computational cost (excluding database access and diagnostic overhead)
OperationTime
Current array sortO(N²)
Frequency grouping after sortO(N)
Sum, count, mean, median, modeO(D)
Variance, standard deviation, percentiles, IQRO(D)
Minimum, maximum and range on a valid sorted frequency tableO(1)

The frequency table itself uses O(D) storage, with O(N) working storage for the sorted array. A bounded number of passes over D distinct values is attractive when D is much smaller than N, especially for repeated calculations on the same frequency table. If every observation is distinct, the distribution provides no compression. A more efficient sort, or SQL grouping for data already stored in tables, could reduce preparation cost; neither is assumed to be implemented by this package.

For relational data, Oracle SQL already supports SUM, COUNT, AVG, MEDIAN, VAR_POP, VAR_SAMP, STDDEV_POP, STDDEV_SAMP and percentile aggregates. The collection-based library is useful when the data is already in memory or when the application needs the frequency table and statistics together. Choose the approach based on data location, scale and measured performance.

8. Try it yourself

Run this example in SQL Developer as a script (F5), with APPSDEMO installed and access to the STATS package. It uses the original worked dataset and percentile of 0.66. Change the literal list and percentile to experiment with other data.

SET SERVEROUTPUT ON

DECLARE
  v_stats_result plsql_types.t_stats_result;
BEGIN
  v_stats_result := stats.get_stats_list('1,3,1,2,1,5,9,1,7,3,2');
  IF v_stats_result.stats.sum_values IS NULL THEN
    raise_application_error(-20001, 'Statistics calculation failed');
  END IF;
  stats.display_frequency_table(v_stats_result);
  stats.display_stats(v_stats_result, 0.66);
END;
/

Expected results are shown below (the numeric display format is ten decimal places).

----------------------------------------------------------
FREQUENCY TABLE
----------------------------------------------------------
KEY=1.0000000000 Frequency=4
KEY=2.0000000000 Frequency=2
KEY=3.0000000000 Frequency=2
KEY=5.0000000000 Frequency=1
KEY=7.0000000000 Frequency=1
KEY=9.0000000000 Frequency=1
----------------------------------------------------------
STATISTICS
Sum=35.0000000000
N Total=11
Distinct N=6
Mean=3.1818181818
Median=2.0000000000
Mode 1 = 1.0000000000
Lowest=1.0000000000
Highest=9.0000000000
Range=8.0000000000
Variance Population=6.6942148760
Variance Sample=7.3636363636
Standard Deviation Population=2.5873180856
Standard Deviation Sample=2.7136021012
Interquartile Range=3.0000000000
Percentile Discrete ( 0.66)=3.0000000000
Percentile Continuous ( 0.66)=3.0000000000

For comparison, the following SQL calculates selected statistics directly over the same observations. The result should agree with the summary produced by STATS.

SELECT COUNT(*) AS n,
       COUNT(DISTINCT column_value) AS distinct_n,
       SUM(column_value) AS total,
       AVG(column_value) AS mean,
       MEDIAN(column_value) AS median,
       VAR_POP(column_value) AS variance_pop,
       VAR_SAMP(column_value) AS variance_samp,
       STDDEV_POP(column_value) AS stddev_pop,
       STDDEV_SAMP(column_value) AS stddev_samp,
       PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY column_value)
         - PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY column_value) AS iqr,
       PERCENTILE_DISC(0.66) WITHIN GROUP (ORDER BY column_value) AS pct_disc,
       PERCENTILE_CONT(0.66) WITHIN GROUP (ORDER BY column_value) AS pct_cont
FROM TABLE(sys.odcinumberlist(1,3,1,2,1,5,9,1,7,3,2));

Useful further tests include a single observation, repeated equal values, multiple modes, negative and fractional values, even and odd counts, percentile endpoints and invalid input. The SEARCH maintenance regression suite also checks statistics count, sum, distinct count, median and rejection of an empty array.

9. Generate statistics from a CSV file

The project entry point supports data loaded into STATS_DATA from a CSV file by IMPORT.STATS_IMP. In Blog 12 - Generating Statistics from a CSV File, we use these components in a complete import, analysis and export process. The same library can also be used as the calculation engine for an APEX application.