Sub topic 3
Scalar Functions Inside Expressions
Prerequisites
This chapter assumes you can write SELECT ... FROM ... WHERE queries and know the basic column types: numbers, text and dates. It also assumes you have seen the arithmetic and comparison operators from the previous chapter. Examples use an employees table with employee_id, first_name, last_name, salary (a DECIMAL), commission, hire_date and department_id. Unless noted, the syntax runs on PostgreSQL. The dialect section lists where other databases differ.
What a scalar function is
A scalar function takes zero or more input values and returns one value. It runs once per row, wherever an expression is allowed. That is the difference from an aggregate function such as SUM, which collapses many rows into one result.
SELECT first_name,
UPPER(first_name) AS shouted,
LENGTH(first_name) AS name_length
FROM employees;Each input row produces one output row. UPPER and LENGTH are called once per row, and their results sit beside the original column.
Because a function call is an expression, you can use it in the same places as a column or a literal:
- in the SELECT list
- in
WHERE,ORDER BYandGROUP BY - as an argument to another function
- as an operand of
+,||or a comparison
Common function families
Every database ships hundreds of functions. A few families cover most daily work.
| Family | Typical functions | What they do |
|---|---|---|
| String | `UPPER`, `LOWER`, `TRIM`, `LENGTH`, `SUBSTRING`, `REPLACE` | Reshape or inspect text |
| Numeric | `ROUND`, `ABS`, `FLOOR`, `CEILING`, `MOD` | Adjust or test numbers |
| Date and time | `CURRENT_DATE`, `EXTRACT` | Read or build date values |
| Conversion | `CAST` | Change a value's data type |
String functions
String functions often tidy data for display or comparison. The standard concatenation operator is ||.
SELECT UPPER(last_name) || ', ' || first_name AS display_name,
LENGTH(last_name) AS last_name_length
FROM employees;TRIM(' abc ') removes leading and trailing spaces. REPLACE(text, 'old', 'new') swaps substrings. SUBSTRING(text, start, length) counts positions from 1, not 0.
Numeric functions
ROUND(x, n) rounds to n decimal places. FLOOR rounds down and CEILING rounds up. ABS removes the sign. MOD(a, b) returns the remainder.
SELECT employee_id,
ROUND(salary / 12.0, 2) AS monthly_salary,
MOD(employee_id, 2) AS is_odd
FROM employees;The 12.0 is deliberate. In PostgreSQL and SQL Server, dividing two integers gives an integer, so 7 / 2 is 3. Writing one operand as a decimal forces decimal division. salary is already DECIMAL here, but the habit protects you when a column turns out to be an integer.
Date functions
CURRENT_DATE returns today's date and takes no parentheses. EXTRACT(field FROM value) pulls out a part such as YEAR, MONTH or DAY.
SELECT first_name,
hire_date,
EXTRACT(YEAR FROM hire_date) AS hire_year
FROM employees;Date arithmetic (adding days, finding the gap between two dates) is where databases differ most. Check your product's documentation for it.
Converting types with CAST
CAST(value AS type) is the standard way to convert a value. Use it when the types in an expression do not line up, or when you want control over precision.
SELECT CAST(salary AS DECIMAL(12, 2)) AS salary_fixed,
CAST('2024-03-15' AS DATE) AS sample_date,
CAST(employee_id AS VARCHAR(10)) || '-A' AS badge
FROM employees;A cast can fail at run time. CAST('abc' AS INTEGER) raises an error for the whole query, not just for one row. When the data is untrusted, filter or clean it first.
Nesting and evaluation order
You can place a function call as the argument of another. Evaluation goes from the innermost call outward, like ordinary function composition in a programming language.
SELECT UPPER(SUBSTRING(first_name, 1, 1))
|| LOWER(SUBSTRING(first_name, 2, LENGTH(first_name))) AS proper_first_name
FROM employees;For 'aLICE', the steps run in this order:
SUBSTRING(first_name, 1, 1)returns'a', andUPPERturns it into'A'.LENGTH(first_name)returns5, soSUBSTRING(first_name, 2, 5)returns'LICE', andLOWERturns it into'lice'.||joins the two pieces into'Alice'.
Deep nesting is hard to read. When an expression grows past two or three levels, split it across a subquery or a CTE, and give each step an alias. The alias chapters that follow cover how to do that.
Scalar functions versus aggregates
The two kinds of function can wrap each other, and the order matters.
SELECT department_id,
ROUND(AVG(salary), 2) AS avg_salary
FROM employees
GROUP BY department_id;Here the aggregate runs first. AVG(salary) produces one value per group, and ROUND is a scalar function applied to that group result. Writing AVG(ROUND(salary, 0)) is also legal, but it rounds every row before averaging, which gives a different answer.
You cannot put a scalar function's result in the select list next to an aggregate unless it is grouped or itself inside an aggregate. This query fails because last_name is neither grouped nor aggregated:
SELECT UPPER(last_name), COUNT(*)
FROM employees
GROUP BY department_id;The fix is to group by the same expression, or to aggregate it.
Functions and NULL
Most scalar functions return NULL when any argument is NULL. UPPER(NULL) is NULL, ROUND(NULL, 2) is NULL, and 'a' || NULL is NULL in standard SQL. The next chapters explain this in detail and show COALESCE as the tool to replace missing values. For now, remember the practical effect: one NULL column in a long chain of functions makes the whole result NULL.
Functions in WHERE and index use
You can filter on a function's result:
SELECT employee_id
FROM employees
WHERE UPPER(last_name) = 'SMITH';This works, but it has a cost. An ordinary index on last_name stores the raw values, so the database cannot use it to look up UPPER(last_name). It usually scans every row and calls the function on each one. A predicate that wraps an indexed column in a function is called non-sargable (it cannot use the index for searching).
There are two common fixes. You can rewrite the condition so the column stays bare:
-- Slow on a large table: function applied to the column
SELECT employee_id
FROM employees
WHERE EXTRACT(YEAR FROM hire_date) = 2024;
-- Faster: a range on the raw column can use an index on hire_date
SELECT employee_id
FROM employees
WHERE hire_date >= DATE '2024-01-01'
AND hire_date < DATE '2025-01-01';Or you can create a functional index (called an expression index in some products) on UPPER(last_name). PostgreSQL, Oracle and recent versions of MySQL support this. Then the first form is fast too, as long as the query's expression matches the index's expression exactly.
Determinism and surprises
A deterministic function returns the same output for the same input. UPPER and ROUND are deterministic. CURRENT_DATE and random-number functions are not. They can change between statements, and sometimes within one. Two practical consequences follow:
- Do not use a non-deterministic function where you need repeatable results, such as in a stored report that must reproduce.
- A functional index normally requires a deterministic function, because the index stores the computed value.
Dialect differences
The core ideas carry across databases, but the names and syntax shift.
| Task | PostgreSQL | MySQL | SQL Server | Oracle | Column | Column | Column | Column |
|---|---|---|---|---|---|---|---|---|
| Text length | `LENGTH` | `LENGTH` (bytes), `CHAR_LENGTH` | `LEN` | `LENGTH` | ||||
| Substring | `SUBSTRING` | `SUBSTRING` | `SUBSTRING` | `SUBSTR` | ||||
| Join text | `\ | \ | ` or `CONCAT` | `CONCAT` | `+` or `CONCAT` | `\ | \ | ` |
| Round up | `CEILING` or `CEIL` | `CEILING` or `CEIL` | `CEILING` | `CEIL` | ||||
| Current date | `CURRENT_DATE` | `CURRENT_DATE` | `CAST(GETDATE() AS DATE)` | `CURRENT_DATE` |
Two details cause real bugs. MySQL's LENGTH counts bytes, so a name with accented characters can report a larger number than you expect. SQL Server's SUBSTRING requires all three arguments, so SUBSTRING(first_name, 2) is an error there.
Practical rules
- Name the result of every computed column with an alias, so the output is readable.
- Prefer standard forms (
CAST,EXTRACT,CURRENT_DATE) over product-specific ones when you need portability. - Keep indexed columns bare on one side of a comparison in
WHERE. - Cast explicitly when mixing types instead of relying on implicit conversion.
- Do not assume a function treats
NULLthe way you want. Check it.
Exercise
A table orders has an indexed column created_at of type TIMESTAMP. A teammate writes WHERE CAST(created_at AS DATE) = DATE '2024-06-01' to find orders from one day, and the query is slow on a large table. Rewrite the condition so an index on created_at can be used.
Show answer
Compare the bare column against a half-open range: WHERE created_at >= TIMESTAMP '2024-06-01 00:00:00' AND created_at < TIMESTAMP '2024-06-02 00:00:00'. The original wraps the indexed column in CAST, which prevents the index from being used for the search. The range returns the same rows, including those late on June 1, and leaves the column untouched.
Exercise
Given salary as an INTEGER column with the value 100000, what does salary / 12 return in PostgreSQL, and how do you get a monthly figure rounded to 2 decimal places?
Show answer
salary / 12 returns 8333, because dividing two integers truncates in PostgreSQL. Use ROUND(salary / 12.0, 2), which returns 8333.33. Making one operand a decimal forces decimal division.