Building an Oracle Query That Alerts When the Failure Rate Exceeds 10% in the Last 5 Minutes — Date Arithmetic, SUM(CASE), HAVING, Indexes and Batch Integration
A step-by-step guide to an Oracle query that computes the failure rate of the last N minutes from a transaction log and flags when it crosses a threshold — covering DATE and TIMESTAMP arithmetic, time-window filtering, aggregation with SUM(CASE) and HAVING, division by zero and small samples, indexes, and calling it from a Pro*C batch.
A request like this comes up often on production systems: "If more than 10% of transactions failed in the last five minutes, notify the on-call person." On older business systems without a dedicated monitoring product, this kind of check is commonly handled by a batch program that runs every minute and a single SQL statement.
The requirement fits in one sentence, but writing the query raises one question after another. How do you say "five minutes ago" in Oracle? How do you get the difference between two times in minutes? Why does subtracting TIMESTAMP columns return something that is not a number? And if there was only one transaction and it failed, should a 100% failure rate really trigger an alert? This article answers those questions one at a time and ends with a monitoring query you can actually use.
Example table and test data
For illustration, assume a simple log table that stores one row per transaction result.
CREATE TABLE tx_log (
tx_id NUMBER PRIMARY KEY,
svc_code VARCHAR2(10) NOT NULL, -- service (PAY, AUTH, QUERY, ...)
req_time DATE DEFAULT SYSDATE NOT NULL, -- processing time
status CHAR(1) NOT NULL -- 'S' success, 'F' failure
);
For testing, insert 120 rows at 10-second intervals covering the last 20 minutes, with roughly one in seven marked as a failure.
INSERT INTO tx_log (tx_id, svc_code, req_time, status)
SELECT LEVEL,
CASE MOD(LEVEL, 3) WHEN 0 THEN 'PAY' WHEN 1 THEN 'AUTH' ELSE 'QUERY' END,
SYSDATE - LEVEL * 10 / 86400, -- 10 seconds further back each row
CASE WHEN MOD(LEVEL, 7) = 0 THEN 'F' ELSE 'S' END
FROM dual
CONNECT BY LEVEL <= 120;
COMMIT;
86400 is the number of seconds in a day. The next section explains why we divide by it.
Oracle date arithmetic basics: DATE behaves like a number of days
Oracle's DATE type holds both a date and a time (down to the second). When you add a number to or subtract a number from a DATE, that number is interpreted as days. So one hour is 1/24, one minute is 1/1440 (24×60), and one second is 1/86400.
| Expression | Result type | Meaning |
|---|---|---|
SYSDATE - 1 |
DATE | Exactly one day ago |
SYSDATE - 1/24 |
DATE | One hour ago |
SYSDATE - 5/1440 |
DATE | Five minutes ago (same as 1/24/12) |
SYSDATE - INTERVAL '5' MINUTE |
DATE | Five minutes ago (intent is clearer) |
date2 - date1 |
NUMBER | Difference between two times, in days (with fractions) |
ts2 - ts1 (two TIMESTAMPs) |
INTERVAL DAY TO SECOND | An interval value, not a number |
To turn the difference between two DATE values into minutes, multiply the day-based result by 24 and by 60.
SELECT (TO_DATE('2026-11-19 10:30:00', 'YYYY-MM-DD HH24:MI:SS')
- TO_DATE('2026-11-19 10:00:00', 'YYYY-MM-DD HH24:MI:SS')) * 24 * 60 AS diff_min
FROM dual;
-- DIFF_MIN = 30
If seconds are involved the result has a fraction too (a 90-second gap gives 1.5). For display, tidy it with ROUND(..., 1) or TRUNC(...). If the times are stored as strings, convert them to DATE with TO_DATE first, as above; you cannot subtract strings.
The fractional style such as 5/1440 is very common in older code, so you need to be able to read it. In new code, a form that shows the unit, such as INTERVAL '5' MINUTE, is easier for the next person to read.
If the column is a TIMESTAMP: CAST to DATE or unpack the INTERVAL
Log tables often store their time column as TIMESTAMP. Subtracting two such values does not give a number but an INTERVAL such as +000000000 00:30:00.000000. Multiplying that by 24 * 60 will not give you the number of minutes you want.
The simplest approach is to convert both sides to DATE before subtracting.
SELECT (CAST(end_ts AS DATE) - CAST(start_ts AS DATE)) * 24 * 60 AS diff_min
FROM job_history;
-- How many minutes have passed since a given time
SELECT (SYSDATE - CAST(last_run_ts AS DATE)) * 24 * 60 AS elapsed_min
FROM job_status;
Because DATE only holds whole seconds, this conversion drops fractional seconds. That is fine for minute-level monitoring, but if milliseconds matter you need to pull the parts out of the INTERVAL and compute it yourself.
SELECT EXTRACT(DAY FROM (end_ts - start_ts)) * 1440
+ EXTRACT(HOUR FROM (end_ts - start_ts)) * 60
+ EXTRACT(MINUTE FROM (end_ts - start_ts))
+ EXTRACT(SECOND FROM (end_ts - start_ts)) / 60 AS diff_min
FROM job_history;
Filtering by time window: leave the column alone and compute the boundary
The condition for "the last five minutes" looks like this:
WHERE req_time >= SYSDATE - INTERVAL '5' MINUTE
AND req_time < SYSDATE
The key point is to apply no function or arithmetic to the column side. The following forms look equivalent, but even with an index on req_time they may not be able to use it properly.
-- Forms to avoid: every row must be computed before it can be judged
WHERE (SYSDATE - req_time) * 24 * 60 <= 5
WHERE CAST(req_ts AS DATE) >= SYSDATE - 5/1440
If the column is a TIMESTAMP, it is safest to make the comparison value the same type.
WHERE req_ts >= SYSTIMESTAMP - INTERVAL '5' MINUTE
AND req_ts < SYSTIMESTAMP
Conversely, comparing a DATE column with a TIMESTAMP value can make Oracle implicitly convert the column side, which again works against index use. Make it a habit to match the column type and the comparison type.
One more thing to know: SYSDATE is the operating-system time of the database server. CURRENT_DATE follows the session time zone, so it can differ depending on client settings. And if the application server writes req_time from its own clock, it may drift from the database clock. Where possible, record times with the database clock, for example DEFAULT SYSDATE, so the monitoring query and the data use the same reference. Within a single SQL statement SYSDATE evaluates to the same value, so the two SYSDATE references in the condition above will not disagree.
Counting successes and failures in one pass: SUM(CASE ...)
A first attempt often counts successes and failures in separate subqueries and combines them.
-- Works, but reads the same range twice
SELECT s.cnt AS success_cnt, f.cnt AS fail_cnt
FROM (SELECT COUNT(*) cnt FROM tx_log
WHERE req_time >= SYSDATE - INTERVAL '5' MINUTE AND status = 'S') s,
(SELECT COUNT(*) cnt FROM tx_log
WHERE req_time >= SYSDATE - INTERVAL '5' MINUTE AND status = 'F') f;
The result is correct, but it reads the same time range twice, and any change to the condition must be made in two places. If you use CASE to turn each row into 0 or 1 and add them up with SUM, you can get several counts in a single read.
SELECT COUNT(*) AS total_cnt,
SUM(CASE WHEN status = 'S' THEN 1 ELSE 0 END) AS success_cnt,
SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END) AS fail_cnt
FROM tx_log
WHERE req_time >= SYSDATE - INTERVAL '5' MINUTE
AND req_time < SYSDATE;
Decide up front what the denominator is. If there are status values other than 'S' and 'F', such as 'P' for in progress, COUNT(*) includes them too. If you want "the share of completed transactions that failed," add AND status IN ('S', 'F') to the WHERE clause.
Computing the failure rate with HAVING: keep only what crosses the threshold
To see the failure rate per service and keep only the services above the threshold, use GROUP BY and HAVING. The difference is that WHERE filters rows before groups are formed, while HAVING filters groups after aggregation.
SELECT svc_code,
COUNT(*) AS total_cnt,
SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END) AS fail_cnt,
ROUND(SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END) / COUNT(*) * 100, 1) AS fail_pct
FROM tx_log
WHERE req_time >= SYSDATE - INTERVAL '5' MINUTE
AND req_time < SYSDATE
GROUP BY svc_code
HAVING COUNT(*) >= 20 -- minimum sample size
AND SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END) > COUNT(*) * 0.1 -- failure rate above 10%
ORDER BY fail_pct DESC;
Two safeguards are built in here.
1. Compare with multiplication instead of division. Writing fail > total * 0.1 instead of fail / total > 0.1 means the denominator can never be zero. With GROUP BY, groups without rows are never created in the first place, but when you aggregate without groups, as in the overall query below, zero rows is entirely possible. If you need to display the ratio, use fail / NULLIF(total, 0) to turn 0 into NULL and avoid the error (ORA-01476).
2. Minimum sample size. If a single transaction arrives at 3 a.m. and fails, the failure rate is 100%. Waking someone up for that is usually not what you want. A minimum-count condition such as COUNT(*) >= 20 reduces these false alarms. The right value depends on your normal traffic.
Alarm decision in one statement: the overall monitoring query
The most convenient shape for a batch program is a query that "always returns exactly one row and says Y/N for the alarm." Aggregating without groups always returns one row, even when no rows match, which keeps the program side simple.
SELECT COUNT(*) AS total_cnt,
NVL(SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END), 0) AS fail_cnt,
ROUND(SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END)
/ NULLIF(COUNT(*), 0) * 100, 1) AS fail_pct,
CASE
WHEN COUNT(*) >= 20
AND SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END) > COUNT(*) * 0.1
THEN 'Y' ELSE 'N'
END AS alarm_yn
FROM tx_log
WHERE req_time >= SYSDATE - INTERVAL '5' MINUTE
AND req_time < SYSDATE
AND status IN ('S', 'F');
With zero matching rows, COUNT(*) is 0 and SUM(...) is NULL. That is why fail_cnt is wrapped in NVL, while fail_pct stays NULL to mean "cannot be computed." alarm_yn becomes 'N' because the COUNT(*) >= 20 condition already rules it out.
Allowing for late commits
If req_time is the start time of a transaction and the commit happens a few seconds later, some rows belonging to "the last minute" may not yet be visible when the monitoring query runs. The most recent stretch is then under-counted. If accuracy matters, shift the window back slightly.
WHERE req_time >= SYSDATE - INTERVAL '6' MINUTE
AND req_time < SYSDATE - INTERVAL '1' MINUTE
The alert arrives one minute later, but in exchange you look at a window whose rows are almost certainly final.
Indexes: keep the monitoring query from burdening production
This query runs every minute, 1,440 times a day. Log tables keep growing, so if it reads the whole table it will get slower over time and load the production database.
| Query shape | Index to consider | Why |
|---|---|---|
| Overall (time condition only) | (req_time, status) |
Narrow by time range, then read status straight from the index |
| Per-service aggregation | (req_time, status, svc_code) |
All needed columns are in the index, reducing table access |
| Watching one service | (svc_code, req_time) |
Narrow first with svc_code = :x |
Adding indexes blindly slows down writes on an insert-heavy log table, so first check whether an existing index is good enough. You can see the execution plan like this:
EXPLAIN PLAN FOR
SELECT COUNT(*), SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END)
FROM tx_log
WHERE req_time >= SYSDATE - INTERVAL '5' MINUTE
AND req_time < SYSDATE;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
An INDEX RANGE SCAN means the time condition is narrowing the range. If you see TABLE ACCESS FULL on a large table, first check that no function is applied to the column in the condition and that the types match.
Calling it from a batch program (Pro*C)
On legacy systems this query is often run periodically by a Pro*C batch written in C. Rather than hard-coding the threshold and window length, pass them as bind variables so the criteria can be adjusted by changing only a configuration file. NUMTODSINTERVAL is a convenient way to turn a number of minutes into an INTERVAL.
#include <stdio.h>
#include <string.h>
#include <sqlca.h>
EXEC SQL BEGIN DECLARE SECTION;
int win_min; /* window length in minutes */
int min_total; /* minimum sample size */
double threshold; /* failure-rate threshold (0.1 = 10%) */
int total_cnt;
int fail_cnt;
char alarm_yn[2];
EXEC SQL END DECLARE SECTION;
/* Returns 1 = alarm, 0 = normal, -1 = error */
int check_failure_rate(int window_minutes, int min_samples, double rate)
{
win_min = window_minutes;
min_total = min_samples;
threshold = rate;
EXEC SQL
SELECT COUNT(*),
NVL(SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END), 0),
CASE
WHEN COUNT(*) >= :min_total
AND SUM(CASE WHEN status = 'F' THEN 1 ELSE 0 END) > COUNT(*) * :threshold
THEN 'Y' ELSE 'N'
END
INTO :total_cnt, :fail_cnt, :alarm_yn
FROM tx_log
WHERE req_time >= SYSDATE - NUMTODSINTERVAL(:win_min, 'MINUTE')
AND req_time < SYSDATE
AND status IN ('S', 'F');
if (sqlca.sqlcode != 0) {
fprintf(stderr, "[monitor] query failed: %.*s\n",
sqlca.sqlerrm.sqlerrml, sqlca.sqlerrm.sqlerrmc);
return -1;
}
printf("[monitor] last %d min: total=%d, fail=%d, alarm=%s\n",
win_min, total_cnt, fail_cnt, alarm_yn);
return (alarm_yn[0] == 'Y') ? 1 : 0;
}
The caller invokes check_failure_rate(5, 20, 0.10) and, on a return value of 1, sends a notification through whatever channel the organization uses (email, SMS, messenger). A few things to check:
- An aggregate query always returns one row, so
sqlcodewill never be1403(no data found). That is why any non-zero value is treated as an error right away. fail_cntis wrapped inNVL, so it can be fetched without an indicator variable and will not raise the NULL error (ORA-01405). Conversely, to fetch a value that can be NULL, such asfail_pct, you must declare an indicator variable with it.- If the same alert goes out every minute while an incident continues, people quickly start ignoring it. Rules such as "alert after N consecutive breaches" or "after alerting once, stay quiet for a set period" belong on the program side.
Common pitfalls and how to check them
| Symptom | Common cause | Check / fix |
|---|---|---|
| Minute differences are wildly too big or small | Forgot *24*60 on the day-based result, or applied it twice |
Test with two known times via SELECT ... FROM dual |
| Cannot multiply the result of a TIMESTAMP subtraction | The result is an INTERVAL | Subtract after CAST(... AS DATE) or break it down with EXTRACT |
| The query gets slower over time | A function or arithmetic on the column prevents index use | Look for TABLE ACCESS FULL in the plan and rewrite the condition |
| ORA-01476 (divisor is equal to zero) | Computing a ratio over a window with no transactions | Use NULLIF(total, 0) or compare with multiplication |
| False alarms every night | Sample size too small | Add a minimum-count condition COUNT(*) >= N |
| Failure rate of the latest window jumps around | Late-committed rows are not visible yet | Shift the window back by about a minute |
| Results differ between servers | App-server clock vs database clock, or use of CURRENT_DATE |
Use the database time (SYSDATE) for both recording and comparison |
Summary: failure-rate monitoring query checklist
- Subtracting DATEs gives a number of days; multiply by
24 × 60for minutes. - Subtracting TIMESTAMPs gives an INTERVAL; handle it with
CAST(... AS DATE)orEXTRACT. - Write time conditions as
column >= computed value, with no function on the column and matching types. - Count successes and failures in one pass with
SUM(CASE ...). - Decide clearly which statuses the denominator (total count) includes.
- Avoid division by zero by comparing
fail > total * thresholdinstead of dividing. - Reduce false alarms with a minimum sample size.
- Check the execution plan and, if needed, consider an index such as
(req_time, status). - Pass the window and threshold as bind variables, and add rules to prevent duplicate alerts.
Even a one-line requirement involves more than it seems once you consider date types, empty windows, sample size and indexes. On the other hand, with these points covered you can build fairly reliable monitoring without a separate product. If you are looking for help maintaining or tuning an older Oracle or Pro*C system, or are considering migrating it to another technology, contact Springuptech. We will look at your current setup with you and suggest a realistic path forward.
※ This article expands on our lead engineer's earlier personal blog posts (in Korean): "Oracle 두 시간 사이의 차이 구하기 * 몇 분 차이인지 구하기", "오라클 ProC 분단위 기간 정보 구하기", "오라클 Pro*C 몇 분 지났는지 정보구하기", "Oracle 5분간 실패율 10%이상 집계 쿼리".
Jaeyong Roh
Lead engineer at Springuptech · 22 years in software engineering
Have a project related to this topic?
Even if it is just an idea, we will help you work out what is possible.