Sub topic 5
Calling single-row functions
This chapter assumes you can write a basic SELECT ... FROM statement, know what the DUAL table is, and can give columns aliases. It also assumes you have an Oracle session in SQL*Plus, SQL Developer, or SQL Worksheet. The HR sample schema is used for table examples.
What a single-row function is
A single-row function takes the values from one row and returns one value for that row. If a query reads 107 rows, the function runs 107 times and produces 107 results. An aggregate function such as COUNT or SUM is different. It collapses many rows into one result.
You can call a single-row function in several places:
- The
SELECTlist. - The
WHEREclause. - The
ORDER BYclause. - The arguments of another function.
Because DUAL has exactly one row, a query like SELECT UPPER('oracle') FROM dual runs the function once. This makes DUAL a good place to test a function before you use it on real data.
The functions fall into these families:
| Family | Typical members | Returns |
|---|---|---|
| Character | `UPPER`, `LOWER`, `INITCAP`, `SUBSTR`, `INSTR`, `LENGTH`, `REPLACE`, `TRIM`, `LPAD`, `RPAD` | Text or a number |
| Numeric | `ROUND`, `TRUNC`, `MOD`, `CEIL`, `FLOOR`, `ABS`, `POWER` | Number |
| Date | `ADD_MONTHS`, `MONTHS_BETWEEN`, `LAST_DAY`, `TRUNC`, `NEXT_DAY` | Date or number |
| Conversion | `TO_CHAR`, `TO_DATE`, `TO_NUMBER` | Target type |
| General (NULL-related) | `NVL`, `NVL2`, `COALESCE`, `NULLIF` | Type of the arguments |
Character functions
Character functions work on strings. Positions are 1-based, so the first character is position 1.
SELECT UPPER('oracle') AS upper_text,
INITCAP('hello oracle world') AS title_text,
LENGTH('Oracle') AS len,
SUBSTR('Oracle SQL', 8, 3) AS part,
INSTR('Oracle SQL', 'SQL') AS pos,
REPLACE('a-b-c', '-', '/') AS replaced,
LPAD('7', 3, '0') AS padded
FROM dual;The results are ORACLE, Hello Oracle World, 6, SQL, 8, a/b/c and 007.
Four details cause most mistakes:
- A negative start position counts from the end.
SUBSTR('Oracle SQL', -3)returnsSQL. INSTRreturns 0 when nothing matches. It does not return NULL or an error. Test for= 0when you check for absence.SUBSTRreturns NULL when the start is past the end of the string. It does not return an empty string.- Oracle treats an empty string as NULL.
LENGTH('')therefore returns NULL, not 0. Likewise'a' || NULLreturns'a', because||ignores NULL operands.
SELECT LENGTH('') AS empty_len,
'a' || NULL AS concat_null,
TRIM(' padded ') AS trimmed
FROM dual;TRIM with no extra keywords removes leading and trailing spaces. TRIM(BOTH 'x' FROM 'xxhixx') removes a chosen single character instead.
Numeric functions
SELECT ROUND(123.456, 1) AS round_1,
ROUND(123.456, -1) AS round_tens,
TRUNC(123.456, 1) AS trunc_1,
MOD(10, 3) AS mod_pos,
MOD(-7, 3) AS mod_neg,
CEIL(4.2) AS ceil_val,
FLOOR(-4.2) AS floor_val
FROM dual;The results are 123.5, 120, 123.4, 1, -1, 5 and -5.
ROUND and TRUNC accept a negative second argument, which works on digits left of the decimal point. ROUND rounds half away from zero. TRUNC simply cuts. MOD(-7, 3) returns -1 because Oracle gives the remainder the sign of the first argument. Other languages and some databases return a positive result here, so check before you port logic.
Date functions
A DATE value in Oracle always holds both a date and a time, to the second. Adding a number to a date adds days, and subtracting two dates gives the difference in days (possibly fractional).
SELECT TO_CHAR(DATE '2024-03-15' + 10, 'YYYY-MM-DD') AS plus_10_days,
TO_CHAR(ADD_MONTHS(DATE '2024-01-31', 1), 'YYYY-MM-DD') AS plus_1_month,
MONTHS_BETWEEN(DATE '2024-03-31', DATE '2024-01-31') AS months_diff,
TO_CHAR(LAST_DAY(DATE '2024-02-10'), 'YYYY-MM-DD') AS month_end,
TO_CHAR(TRUNC(DATE '2024-05-17', 'MM'), 'YYYY-MM-DD') AS month_start
FROM dual;The results are 2024-03-25, 2024-02-29, 2, 2024-02-29 and 2024-05-01.
ADD_MONTHS has a special rule. If the input is the last day of its month, the result is the last day of the target month. For that reason ADD_MONTHS(DATE '2024-01-31', 1) returns February 29, not an invalid date.
TRUNC(SYSDATE) returns today at 00:00:00. It is the usual way to compare dates ignoring the time of day. SYSDATE takes no parentheses and no arguments.
Conversion functions and format models
Oracle converts types implicitly in some cases, but the result can depend on session settings such as NLS_DATE_FORMAT. Explicit conversion with a format model gives the same result in every session.
SELECT TO_CHAR(1234567.891, 'FM9,999,999.00') AS num_text,
TO_NUMBER('1,234.50', '9,999.99') AS num_value,
TO_DATE('15-03-2024', 'DD-MM-YYYY') AS date_value,
TO_CHAR(TO_DATE('15-03-2024', 'DD-MM-YYYY'), 'Day, DD Month YYYY') AS long_text
FROM dual;The FM prefix removes the padding blanks that TO_CHAR otherwise adds, such as the leading space reserved for a sign. Without FM, the same call returns ' 1,234,567.89'. Without it, the Day and Month elements in long_text are also padded with trailing spaces to a fixed width.
Names of days and months in formats like 'DD-MON-YYYY' depend on NLS_DATE_LANGUAGE. A script that works in an English session can fail in a German one. Prefer numeric formats such as 'YYYY-MM-DD', or the ANSI literal DATE '2024-03-15', which is not session dependent.
NULL-related functions
These four functions handle the case where an expression may be NULL.
SELECT NVL(NULL, 'n/a') AS nvl_result,
NVL2('x', 'has value', 'none') AS nvl2_result,
COALESCE(NULL, NULL, 'third') AS coalesce_result,
NULLIF(5, 5) AS nullif_result
FROM dual;NVL(a, b)returnsbifais NULL, otherwisea.NVL2(a, b, c)returnsbifais not NULL, otherwisec.COALESCE(a, b, c, ...)returns the first non-NULL argument. It stops evaluating as soon as it finds one.NULLIF(a, b)returns NULL if the two are equal, otherwisea. It is a safe way to avoid division by zero:total / NULLIF(count_val, 0).
NVL always evaluates both arguments, even when the first is not NULL. If the second argument is an expensive function call, COALESCE can be cheaper. Both also require compatible data types. NVL(commission_pct, 'none') fails because a number and a string do not match. Use NVL(TO_CHAR(commission_pct), 'none').
Nesting functions
You can place a function call inside another function's argument. Oracle evaluates from the innermost call outward.
SELECT SUBSTR(INITCAP(TRIM(' oracle sql ')), 1, 6) AS result
FROM dual;Here the result is Oracle. To debug a long nested expression, run each layer as its own SELECT ... FROM dual and check the intermediate value.
Functions on table columns
With a real table, the function runs once per row that reaches that clause.
SELECT last_name,
LENGTH(last_name) AS name_len,
UPPER(SUBSTR(first_name, 1, 1)) || '. ' || last_name AS short_name,
ROUND(salary / 12, 2) AS monthly
FROM employees
WHERE department_id = 50
ORDER BY LENGTH(last_name) DESC, last_name
FETCH FIRST 5 ROWS ONLY;Functions in WHERE need extra care. In WHERE UPPER(last_name) = 'KING', Oracle applies UPPER to the column. A regular index on last_name cannot be used for that predicate, so Oracle may scan the whole table. A function-based index fixes this when the query is frequent:
CREATE INDEX emp_upper_last_ix ON employees (UPPER(last_name));The function in the query must match the indexed expression exactly.
Common errors
| Error | Typical cause |
|---|---|
| ORA-00909: invalid number of arguments | Wrong argument count, such as `SUBSTR('abc')` |
| ORA-00904: invalid identifier | Misspelled function name, or a function that does not exist in your release |
| ORA-01722: invalid number | `TO_NUMBER('abc')`, or an implicit conversion of non-numeric text |
| ORA-01843: not a valid month | Date string that does not match the format model, such as `TO_DATE('2024-13-01', 'YYYY-MM-DD')` |
| ORA-00937: not a single-group group function | A single-row expression mixed with an aggregate in the same `SELECT` without `GROUP BY` |
Exercises
Exercise
What does SELECT LENGTH('') AS len, 'ab' || NULL AS joined FROM dual return, and why?
Show answer
len is NULL and joined is ab. Oracle treats the empty string as NULL, so LENGTH of it is NULL, not 0. The || operator ignores a NULL operand, so only ab remains.
Exercise
Write a query against DUAL that returns the first day of the month after 2024-05-17, as text in YYYY-MM-DD form.
Show answer
SELECT TOCHAR(TRUNC(ADDMONTHS(DATE '2024-05-17', 1), 'MM'), 'YYYY-MM-DD') AS nextmonthstart FROM dual; The result is 2024-06-01. ADDMONTHS moves to 2024-06-17, TRUNC with 'MM' resets to the first of that month, and TOCHAR formats it. An equivalent is TOCHAR(LASTDAY(DATE '2024-05-17') + 1, 'YYYY-MM-DD').
Exercise
Why can WHERE UPPER(last_name) = 'KING' be slow on a large table that has an ordinary index on last_name, and what can you do about it?
Show answer
The function is applied to the column, so the ordinary index, which stores the raw values, cannot be used for the comparison. Oracle may scan the whole table. Create a function-based index on the same expression, CREATE INDEX emp_upper_last_ix ON employees (UPPER(last_name));, or compare against the bare column when the case is known.