Generating Statistics from a CSV File

Import numeric observations into Oracle, calculate project statistics and export CSV reports using reusable PL/SQL packages and a recoverable Windows batch process; exchange raw data with the standalone Bond and Pollard C++ Statistics application.

1. From CSV input to a statistical report

In Blog 11 - PL/SQL Statistics Library, we built a reusable engine for analysing numeric observations. Here we use that engine in a complete application: receive a CSV file, validate its contents, import the observations, calculate statistics and export the results. The file-handling and validation architecture reuses the components described in Blog 5 - CSV File Data Import.

Install APPSDEMO on a local Windows system as described in Blog 1. The example requires the configured application environment, Oracle directory objects and SQL*Plus. The database packages perform the business logic; the Windows batch script provides the file-discovery and command-line interface.

GitHub - APPSDEMO repository · Installation and development guide (PDF)

2. Create a CSV file

In this example, the PL/SQL examination results for an elite group of programmers, which may include a few cats, are stored in a CSV file. The format is a sequence of project header records followed by their observations. There is no separate column-heading row.

PROJECT,PL/SQL Exam Results
              Fred,90
              Jim,93
              Ann,97
              Ian,98
              Steve F,100
              Bruce Scott,99
              Tiger,95
              Mary,91
              Connor McD,100
              Seyi,96
              Harsh,98
              Peter,89
              Doris,85
              Winston,92
              Charlie,91
              Morse,90
  • Use a unique filename beginning with stats and ending in .csv, for example stats_demo_exam.csv.
  • Each project begins with PROJECT, followed by its description.
  • Each observation has a description followed by a non-NULL numeric value. Use the numeric format expected by your Oracle session.
  • More than one project can be included in the file. Each must have at least one observation, and observations must follow a project header.

Use PROJECT only as the header marker: the current parser recognises headers by the first seven characters, ignoring case. Do not start an observation description with those characters. Keep fields within the installed database column sizes and the collection capacity used by STATS. The numeric field is not restricted to examination marks; the same interface can be used for measurements, durations and other numeric data. When exchanging data with the standalone C++ Statistics application described in section 8, use only one project per file.

3. Application architecture and transaction boundary

The batch script discovers STATS*.CSV files in RECEIVED, including subdirectories. It copies each file to DATA_IN and checks that the copy succeeded before deleting the incoming file. Existing working or archived filenames are not overwritten. SQL*Plus is then invoked with the working filename.

Application components
ModuleResponsibility
IMPORT_STATS.BATDiscover input files, copy safely and report the aggregate exit status.
IMPORT_STATS.SQLCoordinate import, commit, calculation and export.
IMPORT.STATS_IMP / STATS_VALIDStage and validate the entire file, insert projects and observations, archive the input and return the generated project IDs.
STATS_PROJECT / STATS_DATAStore project headers and associated observations using STATS_PROJECT_ID.
STATS.GET_STATS_PROJECTRetrieve the observations for a project and calculate its frequency table and statistical summary.
EXPORT.PROJECT_STATSWrite the statistical results to a CSV file and return its filename.
Statistics import, commit and export workflowAfter copying, the entire file is validated. Rejected files go to the error directory without inserting project data. Valid files are imported, archived and committed before project statistics are calculated and exported. Output failures are recovered using committed project IDs. RECEIVED → DATA_INChecked copy; remove incoming file IMPORT.STATS_IMPStage in IMPORTCSV; validate complete file File valid? NoYes Reject fileKeep errors; no new projects DATA_IN_ERRORExit 1; retain diagnostics STATS_PROJECT / STATS_DATAInsert all projects and observations DATA_IN_PROCESSEDArchive; log project IDs COMMITProject data now durable STATS + EXPORTCalculate and export each project Output incompleteExit 2; recover by project ID DATA_OUTExit 0; all outputs complete
Figure 1. Normal import and validation paths, with a separate post-commit output stage. Status values are SQL*Plus exit statuses; the batch aggregates any failure to 1. Technical interruptions require checking both the database and file location.

The entire input file is validated before creating any projects. Invalid data is rejected as a unit, preserving diagnostic records in IMPORTERROR and APPLOG. An unexpected import error rolls back to a savepoint before loading the file. A failed move into the processed archive prevents the import from being committed.

After a successful import and archive move, the SQL*Plus script records every generated project ID with the source filename in APPLOG and explicitly commits. It then calculates and exports the results for each project. If calculation or export fails, the earlier commit remains effective. This distinction makes recovery possible without duplicating the imported observations.

4. Import the examination results

Save the example as stats_demo_exam.csv in DATA_HOME\RECEIVED, using a new filename if that name already exists. Open the configured APPSDEMO command prompt and run the following. Enter the DEMO_CONNECT password when prompted; keep credentials out of published logs.

import_stats
              echo %ERRORLEVEL%

A successful run reports each new project ID and the name of its exported file, followed by Success! and a batch status of 0. The following abbreviated example illustrates the expected output format; the project ID and timestamp depend on your installation.

Data Import from file: stats_demo_exam.csv
              File stats_demo_exam.csv imported Project ID [104]
              Statistics for Project ID [104] exported to file: stats_104_YYYYMMDD_HHMMSS.csv
              Success!
              
              0

The input CSV is archived in DATA_HOME\DATA_IN\processed. The output is written under DATA_HOME\DATA_OUT, with filename pattern stats_[ProjectID]_YYYYMMDD_HH24MISS.csv. Record your actual project ID; it is not necessarily the same as the illustrative value above.

5. Inspect the imported data and statistics

Run stats_data.sql to display the stored observations and stats_project.sql to display the frequency table and statistical summary for the project. Use the generated project ID when selecting the data. These reports work with existing project data; they do not need to reimport the CSV.

Frequency of examination marksSixteen scores range from 85 to 100. Scores 90, 91, 98 and 100 each occur twice. All other observed scores occur once. 0 1 2 1 85 86 87 88 1 89 2 90 2 91 1 92 1 93 94 1 95 1 96 1 97 2 98 1 99 2 100 FrequencyExamination mark
Figure 2. Frequency distribution for the 16 examination results. The four modes are 90, 91, 98 and 100.
Frequency table
MarkFrequency
851
891
902
912
921
931
951
961
971
982
991
1002
Statistical summary
StatisticExpected value
Sum1,504
Count (N)16
Distinct count12
Mean94
Median94
Modes90, 91, 98, 100
Minimum85
Maximum100
Range15
Population variance19
Sample variance20.2666666667
Population standard deviation4.3588989435
Sample standard deviation4.5018514710
Interquartile range7.25
Discrete percentile (0.67)97
Continuous percentile (0.67)97.05

The expected results above are calculated from the supplied example, independent of the project ID. A percentile of 0.67 identifies the 67th percentile. The discrete percentile returns an observed mark; the continuous percentile interpolates between ranks. See Blog 11 for the underlying calculations.

6. Export results from an existing project

The batch process generates an output CSV automatically after a successful import. To generate output again for an existing project, use stats_project_csv.sql. Alternatively, the package calls below calculate the statistics and export them without inserting a new project. This is also the recovery method when the automatic output stage fails.

SET SERVEROUTPUT ON
              ACCEPT p_project_id NUMBER PROMPT "Enter an existing project ID: "
              
              DECLARE
                v_stats_result plsql_types.t_stats_result;
                v_csv_fname    plsql_constants.filenamelength_t;
              BEGIN
                v_stats_result := stats.get_stats_project(&p_project_id);
                IF v_stats_result.stats.sum_values IS NULL THEN
                  raise_application_error(-20001, 'Statistics calculation failed');
                END IF;
              
                v_csv_fname := export.project_stats(&p_project_id, v_stats_result);
                IF v_csv_fname IS NULL THEN
                  raise_application_error(-20002, 'Export failed');
                END IF;
                dbms_output.put_line('Exported: ' || v_csv_fname);
              END;
              /

Run the block using Run Script (F5) in SQL Developer, or in SQL*Plus. Enter the actual existing project ID. Check that the returned CSV exists in DATA_OUT and contains the expected results. The block is a reporting operation, not an import. It creates a statistics report CSV for Excel, not a raw-data CSV suitable for reimporting into Oracle or loading into C++. To export original observations instead, use stats_data_export.sql as described in section 8.

Numeric summary values and frequency-table keys are written without thousands separators, using a full stop as the decimal separator and ten decimal places. Counts are written as integers. For example, the sum of the examination marks is written as "Sum",1504.0000000000. The comma separates the label and the numeric value; it is not part of the number. Spreadsheet applications may display numbers using their own locale and cell formatting.

7. Error handling and manual recovery

Exit status conventions
SQL*Plus statusBatch ERRORLEVELMeaning
00 if all files succeedImport committed and output completed; an empty incoming directory is also a successful batch run.
11Import rejected or failed; check committed data before retrying.
21Project data committed, but subsequent calculation or export incomplete. Do not reimport.

Check echo %ERRORLEVEL% immediately after the batch completes. The batch continues processing other incoming files; its result is an aggregate status, not a per-project status. A message that the PL/SQL block completed does not by itself establish success. Use APPLOG and IMPORTERROR to determine the outcome for each file.

Rejected data or interrupted import

Inspect IMPORTERROR and APPLOG and locate the file in DATA_IN\error, DATA_IN or RECEIVED as appropriate. Correct validation errors, resolve any technical failure and confirm that no corresponding projects were committed. Preserve a backup and use a new, unique filename when returning the corrected file to RECEIVED. File moves are not rolled back by Oracle: a failure between archive movement and commit may require reconciliation. Do not rely on file location alone.

Project data committed but output incomplete

If DATA_OUT is unavailable, the export can fail even though the project has been successfully imported. The following is a diagnostic message from the local acceptance test:

Project data committed; output incomplete for file
              stats-sunshine-cpp2.csv, Project ID [104], stage
              EXPORT.PROJECT_STATS. Do not re-import.

Resolve the cause of the output failure, then recover the existing projects using the report or the PL/SQL block in section 6. For a file containing several projects, inspect all project IDs logged against the input filename and the completed export messages. Processing stops at the first calculation or export failure within that file, so later projects may also need output. Check for partial output files; regenerate only the outputs that are missing or incomplete. Do not reimport committed project data.

The directory-based process is designed for a single import run at a time. Deliver complete files, avoid overlapping runs and keep recoverable backups. Database transactions do not provide atomicity across filesystem operations.

8. Data interchange between Oracle and C++ applications

The Bond and Pollard Ltd C++ Statistics application (stats.cpp) is a separate, standalone console program in our statistics GitHub repository. It accepts manually entered or imported numeric observations and calculates count, arithmetic mean and sample standard deviation directly from the data held in memory. The Oracle STATS package uses a frequency table to calculate a wider range of statistics. Neither application requires the other to run.

GitHub - C++ Statistics repository (source code and README)

Both applications use a common raw-data CSV interface for exchanging original labelled observations in either direction. The Oracle application also produces a separate statistics report CSV for Excel, while C++ Print Results produces a formatted text report. Neither report is a valid raw-data input file. A CSV extension alone does not make a file suitable for import.

Raw-data interchange versus reporting
OperationFile format and purposeRaw-data import?
Oracle EXPORT.PROJECT_STATS_DATAstats_data_[Project ID]_YYYYMMDD_HH24MISS.csv: original project description, labels and observationsYes
C++ SAVE Data (option 3)Raw-data CSV with the same record structureYes
Oracle EXPORT.PROJECT_STATS or EXPORT.STATS_EXPORTstats_[Project ID or name]_YYYYMMDD_HH24MISS.csv: frequency table and calculated statistics for ExcelNo
C++ Print Results (option 6)Formatted text report containing observations and summary statistics; use a .txt filenameNo

For reliable interchange use one PROJECT header, one or more labelled observations, and exactly two comma-separated fields per record. Use simple text without commas, quotation marks or line breaks; avoid significant leading or trailing whitespace and labels beginning with PROJECT (case-insensitive). Use finite numbers with a decimal point, no thousands separators, and matching Oracle import settings. Respect both applications' field and numeric limits. Oracle NUMBER and C++ double have different precision; arbitrary decimal values may not round-trip exactly. The current Oracle exporter writes unquoted text and does not specify a record order.

Integration test: Oracle to C++

On 29 November 2026, we imported the following file, stats-import-1.csv, using import_stats:

PROJECT,Stats Data Import to Oracle or CPP
Sun 8 November 2026,2.4
Mon 9 November 2026,3.4
Tue 10 November 2026,4.9
Wed 11 November 2026,4
Thu 12 November 2026,3.8
Fri 13 November 2026,3.8
Sat 14 November 2026,3.6

Oracle created project 109 and automatically generated stats_109_20261129_115225.csv, the statistical report for Excel. To obtain the original observations instead, run stats_data_export.sql in SQL*Plus or SQL Developer (Run Script, F5), and enter 109. The script calls EXPORT.PROJECT_STATS_DATA and exits the SQL*Plus script session. The resulting file was stats_data_109_20261129_120840.csv in DATA_OUT. It was byte-for-byte identical to the input file in this test.

Build and run the C++ Statistics program from the repository linked above. Load that raw-data CSV using Load Data (option 4), or supply the filename on the command line as shown below. Select Calculate Statistics (option 5), then Print Results (option 6).

stats.exe stats_data_109_20261129_120840.csv

This command is an example for the Windows command prompt, assuming stats.exe has been compiled and the input file is in the current directory. The actual report, stats-test-109-print.txt, retained every observation and produced the following results:

Verified results for project 109
StatisticOracle CSV reportC++ text report
Count77
Mean3.70000000003.7
Sample standard deviation0.74610097620.746101

The independent calculations agree to the precision shown by C++. The C++ report uses six significant digits, whereas SAVE Data uses sufficient digits to preserve a double when reloaded. To exchange data in the reverse direction, use C++ SAVE Data (option 3), give the file a new name beginning with stats and ending in .csv, copy it into RECEIVED and run import_stats. This creates a new project. The report files are not inputs to either application.

9. Verification and next steps

The local Oracle 26ai Free acceptance tests exercised multiple projects in one file, invalid statistics input, export failure after commit and recovery of an existing project without reimporting it. The STATS package also passed 59 regression tests covering the statistical calculations, percentile endpoints, fractional observations and invalid input. These are targeted tests, not exhaustive production certification.

The next article, Blog 13 - Neural Networks, explores building a neural network from first principles in C++.