Sub topic 1
Converting Types with TO_CHAR, TO_DATE, and TO_NUMBER
Prerequisites
This chapter assumes you know basic SELECT, WHERE, and ORDER BY syntax. You should understand the NUMBER, VARCHAR2, and DATE data types, and you should be able to run SQL in SQL*Plus or SQL Developer. You should also know that DUAL is a one-row table Oracle provides for expressions that need a FROM clause.
Why explicit conversion matters
Oracle converts values between types when it needs to. This is called implicit conversion. It saves typing, but it depends on session settings and can fail on bad data. An explicit conversion names the function and the format, so the result is the same in every session.
-- Implicit: Oracle converts order_ref to a number for every row
SELECT * FROM orders WHERE order_ref = 1001;
-- Explicit: the comparison is text on both sides
SELECT * FROM orders WHERE order_ref = '1001';If order_ref is a VARCHAR2 column that holds one non-numeric value, the first query can fail with ORA-01722. The second query does not convert the column.
Reading and writing format models
A format model is a string such as 'YYYY-MM-DD' or '9,999.99' that describes how a value looks as text. TOCHAR uses a format model to write a value out. TODATE and TO_NUMBER use one to read a string in. Each element in the model must match the input.
flowchart TD
A[Text value] -->|TO_DATE or TO_NUMBER| B[DATE or NUMBER value]
B -->|TO_CHAR| Acaption: Text becomes a DATE or NUMBER through TODATE or TONUMBER, and TOCHAR turns it back into text. alt: A flowchart with two boxes, Text value and DATE or NUMBER value. An arrow labelled TODATE or TONUMBER points from text to the typed value, and an arrow labelled TOCHAR points back.
Formatting dates with TO_CHAR
Use TOCHAR with a date and a format model. Always pass the model, because the default depends on NLSDATE_FORMAT.
SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS now_text
FROM dual;HH24 gives a 24-hour clock. HH gives a 12-hour clock with no AM or PM marker, so use HH24 for unambiguous output.
Formatting numbers with TO_CHAR
Number models use 9 for a digit position and 0 for a forced zero. A comma and a period set the grouping and decimal marks.
SELECT TO_CHAR(1234567.891, '9,999,999.00') AS padded
FROM dual;The result begins with a space, which reserves a position for a sign. The next section removes it.
callout note Check the output of a format model before you use it in a report. A model that is too narrow for the value returns a string of # characters instead of an error. callout
Exercise
Exercise
What does TO_CHAR(1234567.891, '9,999,999.00') return, and why does it start with a space?
Show answer
It returns ' 1,234,567.89'. The leading space reserves a position for the sign, because the model has no FM modifier to remove the padding.