Sub topic 11
Handling bad input safely (Oracle 12.2 and later)
Conversion functions raise an error when a string does not fit the format model. One bad value in a million-row load can abort the whole statement. Oracle 12.2 added two tools for this: the DEFAULT ... ON CONVERSION ERROR clause and the VALIDATE_CONVERSION function. This chapter shows how to use each one and when to prefer it.
This chapter assumes you know TO_CHAR, TO_DATE, and TO_NUMBER with format models, and that you have seen ORA-01722, ORA-01843, and ORA-01861. You need Oracle Database 12.2 or later. Earlier versions reject this syntax.
The problem: one bad row stops the query
Suppose a staging table holds text that was loaded from a file. Every column is VARCHAR2, because the loader could not trust the data.
CREATE TABLE stg_orders (
order_id NUMBER,
qty_text VARCHAR2(20),
ship_text VARCHAR2(20)
);
INSERT INTO stg_orders VALUES (1, '12', '2026-11-01');
INSERT INTO stg_orders VALUES (2, '1,5', '2026-13-01');
INSERT INTO stg_orders VALUES (3, 'abc', '2026-11-15');
INSERT INTO stg_orders VALUES (4, NULL, '2026-02-30');
INSERT INTO stg_orders VALUES (5, '7', '2026-12-24');
COMMIT;This query fails as soon as Oracle reaches row 2 or 3:
SELECT order_id, TO_NUMBER(qty_text) AS qty
FROM stg_orders;The error is ORA-01722 (invalid number). Which row triggers it depends on how Oracle reads the table, so you cannot count on rows 1 to 5 being processed in order. Nothing is returned, even for the good rows.
DEFAULT ... ON CONVERSION ERROR
You can put a fallback value inside the conversion function. If the conversion fails, Oracle returns the fallback instead of raising an error.
SELECT order_id,
TO_NUMBER(qty_text DEFAULT NULL ON CONVERSION ERROR) AS qty,
TO_DATE(ship_text DEFAULT NULL ON CONVERSION ERROR, 'YYYY-MM-DD') AS ship_date
FROM stg_orders
ORDER BY order_id;The result has these values. Dates appear in your session's NLS_DATE_FORMAT.
| order_id | qty | ship_date | Why |
|---|---|---|---|
| 1 | 12 | 2026-11-01 | Both values valid |
| 2 | NULL | NULL | `'1,5'` is not a number, month 13 is invalid |
| 3 | NULL | 2026-11-15 | `'abc'` is not a number |
| 4 | NULL | NULL | Input quantity was already NULL, `'2026-02-30'` is not a real day |
| 5 | 7 | 2026-12-24 | Both values valid |
Syntax rules
- The clause goes after the first argument. The format model and
nlsparamfollow it, as inTO_DATE(x DEFAULT d ON CONVERSION ERROR, fmt, nlsparam). - It works with
TO_NUMBER,TO_DATE,TO_TIMESTAMP,TO_TIMESTAMP_TZ,TO_BINARY_FLOAT,TO_BINARY_DOUBLE,TO_DSINTERVAL,TO_YMINTERVAL, andCAST. - The default is converted with the same format model as the input. If you give a string default to
TO_DATE, it must match the format model. This is valid:TO_DATE(ship_text DEFAULT '1900-01-01' ON CONVERSION ERROR, 'YYYY-MM-DD'). - A NULL input still returns NULL. The default applies only when a conversion fails.
- The clause covers input that does not fit the model. Check the format model itself with a known good value first, so you do not mistake a wrong model for bad data.
CAST uses the same idea:
SELECT CAST('x12' AS NUMBER DEFAULT 0 ON CONVERSION ERROR) AS n
FROM dual;This returns 0. CAST also accepts a format model after the clause, for example CAST(s AS DATE DEFAULT NULL ON CONVERSION ERROR, 'YYYY-MM-DD').
Choosing the default
The default is a decision about your data, not a technicality.
NULLsays "unknown". Aggregates such asSUMandAVGskip it, andIS NULLfinds it again.- A sentinel such as
-1orDATE '1900-01-01'keeps a columnNOT NULL. It also gets counted in totals and averages, and can silently distort them. - A sentinel can collide with a real value. If
-1can be a legitimate quantity, useNULL.
VALIDATE_CONVERSION
VALIDATE_CONVERSION answers a yes/no question: would this conversion succeed? It returns 1 if it would and 0 if it would not. It never raises a conversion error.
SELECT order_id, qty_text, ship_text
FROM stg_orders
WHERE VALIDATE_CONVERSION(qty_text AS NUMBER) = 0
OR VALIDATE_CONVERSION(ship_text AS DATE, 'YYYY-MM-DD') = 0
ORDER BY order_id;This returns rows 2, 3, and 4. Row 5 passes both checks, and row 1 does too.
Points to remember:
- The syntax is
VALIDATE_CONVERSION(expr AS datatype [, fmt [, 'nlsparam']]). - The target types include
NUMBER,DATE,TIMESTAMP,TIMESTAMP WITH TIME ZONE,BINARY_FLOAT,BINARY_DOUBLE, and the interval types. - A NULL input returns
1, because converting NULL never fails. Row 4 has a NULLqty_textand is not flagged by the quantity check. It is flagged only by its date. - Pass the same format model and
nlsparamyou will use in the real conversion. A value can be valid under one model and invalid under another.
The next example is a common cleanup pattern. It copies the good rows into a typed table and keeps the rejects for review.
CREATE TABLE orders_clean (
order_id NUMBER,
qty NUMBER,
ship_date DATE
);
INSERT INTO orders_clean (order_id, qty, ship_date)
SELECT order_id,
TO_NUMBER(qty_text),
TO_DATE(ship_text, 'YYYY-MM-DD')
FROM stg_orders
WHERE VALIDATE_CONVERSION(qty_text AS NUMBER) = 1
AND VALIDATE_CONVERSION(ship_text AS DATE, 'YYYY-MM-DD') = 1;Read the next section before you rely on this pattern.
Why the filter above is not guaranteed
Oracle may evaluate conditions in the WHERE clause in any order, and may evaluate a SELECT-list expression before the filter removes the row. In theory TO_NUMBER(qty_text) could run on row 3 even though VALIDATE_CONVERSION would exclude that row. You would then get ORA-01722 on a query that looks safe. Order in the SQL text does not control evaluation order.
The reliable fix is to make the converting expression safe by itself. Use DEFAULT ... ON CONVERSION ERROR in the SELECT list, and keep VALIDATE_CONVERSION only as a filter:
INSERT INTO orders_clean (order_id, qty, ship_date)
SELECT order_id,
TO_NUMBER(qty_text DEFAULT NULL ON CONVERSION ERROR),
TO_DATE(ship_text DEFAULT NULL ON CONVERSION ERROR, 'YYYY-MM-DD')
FROM stg_orders
WHERE VALIDATE_CONVERSION(qty_text AS NUMBER) = 1
AND VALIDATE_CONVERSION(ship_text AS DATE, 'YYYY-MM-DD') = 1;Now the result is correct whatever order Oracle chooses. The default never fires on a surviving row, so it acts as a guard, not as a data change.
Choosing between the two tools
| Need | Use |
|---|---|
| Return a typed value, with a fallback on failure | `DEFAULT ... ON CONVERSION ERROR` |
| List or count rows that would fail | `VALIDATE_CONVERSION(...) = 0` |
| Reject bad rows from a load | `VALIDATE_CONVERSION(...) = 1` plus a guarded conversion |
| Keep an application error for bad input | Plain `TO_NUMBER` or `TO_DATE` |
The last row matters. If bad input means a bug upstream, an error is the right outcome. A default hides the problem.
Effects on performance and indexes
The earlier chapter on WHERE clauses showed that wrapping a column in a function prevents a regular index from being used on that column. These functions behave the same way.
WHERE TO_NUMBER(qty_text DEFAULT -1 ON CONVERSION ERROR) > 10cannot use a plain index onqty_text.WHERE VALIDATE_CONVERSION(qty_text AS NUMBER) = 0also needs a scan of the rows it checks.
Both are cleanup queries, so a scan is usually acceptable. If you run one repeatedly on a large table, the lasting fix is to store the data in the right type and enforce it with a constraint.
Common mistakes
- Using a default to hide a wrong format model. If
TO_DATE(x DEFAULT NULL ON CONVERSION ERROR, 'DD/MM/YYYY')returns NULL for every row, the model is probably wrong. Test withVALIDATE_CONVERSIONand count failures before you trust the result. - Forgetting the language and separators.
TO_DATE('15-JAN-2026' DEFAULT NULL ON CONVERSION ERROR, 'DD-MON-YYYY')can return NULL in a session with a non-EnglishNLS_DATE_LANGUAGE. Pass'NLS_DATE_LANGUAGE=ENGLISH'as thenlsparamargument, both in the conversion and inVALIDATE_CONVERSION. - Using a sentinel that passes later checks. A default of
DATE '1900-01-01'is a valid date, so laterVALIDATE_CONVERSIONor constraint checks will not flag it. - Counting NULL defaults as missing data. After conversion, a NULL could mean "input was NULL" or "input was bad". If you need to tell them apart, keep the original text in another column or run
VALIDATE_CONVERSIONon it.
Summary
DEFAULT ... ON CONVERSION ERROR turns a failing conversion into a value you choose. VALIDATE_CONVERSION tells you in advance which values would fail. Use the default when you want a result for every row, and use validation when you want to find or exclude the bad rows. Always pass the same format model and nlsparam to both, and guard the conversion itself instead of trusting the order of your WHERE clause.
Exercise
A column amount_text holds values such as '19.99', '1,250.00', and 'n/a'. Write a query against a table payments that returns each row's amount as a NUMBER, using NULL for values that cannot be parsed. Use the format model '9,999.99' and make the result independent of the session's NLSNUMERICCHARACTERS.
Show answer
SELECT TONUMBER(amounttext DEFAULT NULL ON CONVERSION ERROR, '9,999.99', 'NLSNUMERICCHARACTERS=''.,''') AS amount FROM payments; The nlsparam fixes the decimal character as '.' and the group separator as ','. The value 'n/a' fails and returns NULL.
Exercise
A colleague writes: SELECT TODATE(d, 'YYYY-MM-DD') FROM t WHERE VALIDATECONVERSION(d AS DATE, 'YYYY-MM-DD') = 1; They report that it sometimes raises ORA-01843. Explain why and fix it.
Show answer
Oracle does not guarantee that the WHERE filter runs before the SELECT-list expression is evaluated, so TODATE can run on a row that validation would reject. Make the conversion safe by itself: SELECT TODATE(d DEFAULT NULL ON CONVERSION ERROR, 'YYYY-MM-DD') FROM t WHERE VALIDATE_CONVERSION(d AS DATE, 'YYYY-MM-DD') = 1; The filter still removes bad rows, and the default prevents an error if the order differs.
Exercise
What does VALIDATECONVERSION(NULL AS NUMBER) return, and what does that mean when you search for bad rows with VALIDATECONVERSION(col AS NUMBER) = 0?
Show answer
It returns 1, because converting NULL never fails. Rows where col is NULL are not reported as bad. If NULL also counts as a problem in your data, add col IS NULL to the condition.