SQL: Structured Query LanguageSQL FundamentalsScalar Functions

What is a scalar function?

Question 27 of 30 · Updated

On this page

A SQL scalar function returns a single value for each evaluation of its arguments. When used as an ordinary expression in a SELECT list, it can calculate or transform a value for each input row without grouping those rows together. Examples include ABS for absolute magnitude, TRIM for removing leading and trailing spaces, and CHAR_LENGTH for counting characters.

The word scalar describes the result of one evaluation, not the number of arguments or the number of rows returned by the whole query. A function may take zero, one or several arguments and still return a single value. A scalar function may also return NULL. It differs from an aggregate function, which summarizes a set of input rows, and from a set-returning function, which can produce multiple rows.

1. Basic syntax and purpose#

SQL
SELECT ABS(-8) AS magnitude, CHAR_LENGTH('SQL') AS characters, REPLACE('a-b', '-', '_') AS replaced;
magnitudecharactersreplaced
83

The PostgreSQL query returns one result row containing three values. ABS accepts a numeric argument and returns its absolute magnitude. CHAR_LENGTH counts characters in the string SQL. REPLACE accepts three arguments and substitutes the matching substring. All three are ordinary scalar functions.

Aliases such as magnitude describe the output columns, not a change to the function or its source data. A literal-only SELECT can demonstrate a function without querying a stored table in PostgreSQL. Some other database systems require a different form for such demonstrations.

Scalar functions are useful for presenting readable output, cleaning strings, calculating values, extracting parts of dates and performing conditional data transformations. Use the function that expresses the desired operation; not all functions have the same argument types, comparison rules or behavior across SQL dialects.

2. Common types of scalar functions#

CategoryExamplesTypical use
TextTRIM, CHAR_LENGTH, REPLACEClean a label, count characters, replace a substring
NumericABS, ROUNDCompute magnitude or round a numeric value
Text caseUPPER, LOWERProduce uppercase or lowercase text
Date and timeDATE_TRUNC (PostgreSQL)Truncate a timestamp to a chosen time unit
ConcatenationCONCATCombine text values
ConversionPostgreSQL TO_CHARFormat supported numeric or date/time values as text

These examples illustrate categories rather than an exhaustive or portable function catalog. Individual signatures, accepted argument types, precision and NULL rules must be checked in the relevant engine's documentation. Detailed CONCAT, case conversion and ROUND behavior are separate upcoming learning objectives; this lesson concentrates on the scalar-function concept.

3. Apply scalar functions to each row#

Consider a small inventory-adjustment dataset. The delta column records signed stock adjustments: negative values represent removal, positive values represent addition, and NULL means the adjustment is not recorded. The label may contain surrounding spaces or be missing.

idlabeldelta
1' Pen '-5
2'Notebook'12
3NULLNULL

The following query is independently executable in PostgreSQL. It uses a common table expression (CTE) with synthetic VALUES rows instead of a permanent table.

SQL
WITH items(id, label, delta) AS ( VALUES (1, ' Pen ', -5), (2, 'Notebook', 12), (3, NULL::text, NULL::integer) ) SELECT id, TRIM(label) AS clean_label, ABS(delta) AS magnitude FROM items ORDER BY id;
idclean_labelmagnitude
1Pen5
2Notebook12
3NULLNULL
Loading diagram…

The three rows remain three rows. The diagram shows the logical mapping from each row's delta to a scalar result. The optimizer may rearrange or eliminate physical function evaluations when that is legal; the diagram does not assert an exact number of internal calls.

The result contains two newly calculated columns, but the original label and delta values are not modified. ABS is appropriate for an absolute movement metric, but it is not appropriate if the report must preserve direction. A clean display label is similarly not evidence that the stored label has been cleaned. To persist a transformation, a separate authorized write or schema design would be needed.

4. Where can scalar functions appear in a query?#

Ordinary scalar functions can appear in the SELECT list, in predicates, in sorting expressions and in other contexts that accept compatible scalar expressions. A function is not itself a complete SQL statement; its surrounding statement determines the operation.

SELECT: produce calculated output#

The previous example used TRIM and ABS to generate display and reporting values. An ordinary SELECT expression does not inherently filter or group the input rows. Other clauses, such as WHERE, DISTINCT or LIMIT, can change the result cardinality independently.

WHERE: filter using a calculated value#

SQL
WITH items(id, label, delta) AS ( VALUES (1, ' Pen ', -5), (2, 'Notebook', 12), (3, NULL::text, NULL::integer) ) SELECT id FROM items WHERE ABS(delta) >= 10 ORDER BY id;

Result: id 2. Row 1 has absolute magnitude 5. Row 2 has magnitude 12 and passes the threshold. Row 3 has NULL magnitude, so the comparison is UNKNOWN and WHERE does not retain it. The function provides a value to the predicate; the WHERE clause is what removes rows.

ORDER BY: sort by a calculated value#

SQL
WITH items(id, label, delta) AS ( VALUES (1, ' Pen ', -5), (2, 'Notebook', 12), (3, NULL::text, NULL::integer) ) SELECT id, ABS(delta) AS magnitude FROM items ORDER BY ABS(delta) DESC NULLS LAST, id;
idmagnitude
212
15
3NULL

The result is ordered by descending absolute magnitude, with NULL values last and id as a tie-breaker. The explicit NULLS LAST syntax is supported by PostgreSQL but is not available in all engines. ABS does not itself determine the ordering of rows.

5. Nesting scalar functions#

A scalar result can serve as an argument to another compatible function. To measure the length of a label after removing surrounding spaces, nest TRIM inside CHAR_LENGTH:

SQL
WITH items(id, label, delta) AS ( VALUES (1, ' Pen ', -5), (2, 'Notebook', 12), (3, NULL::text, NULL::integer) ) SELECT id, CHAR_LENGTH(TRIM(label)) AS clean_length FROM items ORDER BY id;
idclean_length
13
28
3NULL

For row 1, TRIM(' Pen ') yields Pen and CHAR_LENGTH of Pen yields 3. For row 3, both operations propagate NULL. Think from the innermost expression outward to understand the value being computed. This is a logical dependency between expressions, not a promise about the engine's physical scheduling.

Nested functions can make concise transformations possible, but long expressions may become difficult to read. Use clear aliases, a subquery or a CTE when those improve the query's clarity. Do not assume that nesting automatically caches intermediate results or guarantees a particular execution order.

6. NULL handling: functions do not all behave the same#

Many ordinary built-in functions return NULL when a required argument is NULL. Others deliberately handle NULL arguments differently. The following PostgreSQL query shows the distinction:

SQL
SELECT ABS(NULL::integer) AS absent, CHAR_LENGTH('') AS empty_length, COALESCE(NULL::integer, 0) AS fallback, CONCAT('A', NULL::text, 'B') AS joined;
absentempty_lengthfallbackjoined
NULL00AB

ABS of an unknown integer is unknown. An empty string is a known text value of length zero, not NULL. COALESCE chooses the first non-NULL argument; PostgreSQL treats COALESCE as a special SQL expression rather than an ordinary callable function, but its scalar result illustrates an important alternative NULL policy. PostgreSQL CONCAT ignores NULL arguments in this example. Other SQL dialects can have different concatenation behavior.

Never assume that every scalar function propagates NULL. Check the particular function and data type. Replacing a missing adjustment with zero is appropriate only when that is an explicit business rule. Otherwise the distinction between an unknown measurement and a known zero may be lost.

7. Scalar functions versus aggregate functions#

PropertyOrdinary scalar functionOrdinary aggregate function
Logical inputArgument values in the expression's evaluation contextValues across a group of input rows
ResultOne value per evaluationOne aggregate value per group
SELECT with a simple row sourceDoes not by itself collapse rowsSummarizes selected rows
ExampleABS(delta)SUM(delta)
NULL behaviorDepends on functionDepends on aggregate
GROUP BY required?NoNo; an ungrouped aggregate summarizes the selected input

The distinction is about the operation, not whether a query returns one row. A scalar expression evaluated on a literal can produce one result row. An aggregate with GROUP BY can produce many result rows, one per group. A window function can compute an aggregate over a window while retaining input rows. Set-returning functions are yet another category; their result may contain zero or more rows per call.

Scalar and aggregate functions can appear together. For example, to compute the total absolute amount of recorded inventory movement:

SQL
WITH items(id, label, delta) AS ( VALUES (1, ' Pen ', -5), (2, 'Notebook', 12), (3, NULL::text, NULL::integer) ) SELECT SUM(ABS(delta)) AS total_magnitude, COUNT(*) AS rows FROM items;
total_magnituderows
173

ABS logically maps the recorded adjustments -5 and 12 to 5 and 12; NULL remains NULL. SUM summarizes those magnitudes to 17, and COUNT(*) counts all three input rows. This differs from taking ABS after summing signed adjustments: cancellation of positive and negative values would change the intended metric. Decide whether transformation should happen before or after aggregation based on the business question.

8. Argument types and return types#

A scalar function need not return the same type as its argument. Character-count functions accept text and return a number. Formatting functions may turn a number or date into text. Some functions are overloaded, meaning that different argument signatures can select different implementations and result types in PostgreSQL.

SQL
SELECT pg_typeof(ABS(-8))::text AS abs_type, pg_typeof(CHAR_LENGTH('SQL'))::text AS length_type, pg_typeof(TRIM(' SQL '))::text AS trim_type;
abs_typelength_typetrim_type
integerintegertext

These are the observed types for the specific PostgreSQL expressions, not universal return-type rules. The pg_typeof diagnostic function and double-colon cast syntax are PostgreSQL-specific. Different numeric input types can select different ABS signatures. Applying a numeric function to arbitrary text can fail when the engine cannot resolve a compatible signature or perform a valid conversion.

Choose explicit conversions when the type and semantics are important. For example, a formatted currency string is useful for display but may be unsuitable for further numeric aggregation. Keep numeric values numeric for computation and format them when preparing presentation output. Detailed type coercion and function-specific numeric precision are separate topics.

9. Built-in versus user-defined scalar functions#

ABS and TRIM are built-in operations supplied by the database. A user-defined function is a function created by a database developer to encapsulate reusable logic. It may return a scalar value, return a set of rows, or have another declared return type. Not every database function is a scalar function.

Supabase's official Database Functions guide demonstrates a PostgreSQL function with a single text return value, using RETURNS text, and separately demonstrates a function returning SETOF rows. Those examples illustrate the distinction between declaring a single result and declaring a row set. The SQL function facility can also perform operations beyond simple value transformation; a scalar return type by itself does not guarantee absence of side effects.

No custom database function is needed for the exercises in this article. Creating and deploying functions introduces additional concerns such as permissions, volatility, security context and maintainability. These belong to later database-programming lessons. The official guide was consulted for the return-type distinction; no user-defined functions were installed or executed.

10. Practical considerations#

Performance: A scalar function in SELECT may have to perform work for each qualifying row. A function applied to a column in a WHERE predicate can sometimes prevent use of a conventional index on the unmodified column. For example, an ordinary index on delta does not automatically provide an efficient access path for ABS(delta) >= 10. Depending on the engine and predicate, an equivalent index-friendly condition or a suitable expression index may help. Query planners may also use other strategies. Measure with representative data before optimizing; no performance benchmark was performed.

Determinism: Some scalar functions are deterministic for particular argument values, while others depend on time, randomness, session settings or database state. A single-value result does not imply determinism, immutability or permission to cache the result indefinitely. Be particularly careful when using user-defined functions with side effects or when designing indexes on expressions.

Portability: Standard-looking names do not ensure identical semantics everywhere. Character length versus byte length, collation, date formatting, rounding and NULL handling can vary across engines. For portable applications, choose supported operations and test target dialects. The executable examples here were verified in PostgreSQL only.

Data semantics: A function can alter the meaning of values even when it produces a technically valid result. Taking absolute values discards sign, trimming may remove significant spaces, and text formatting may obscure type information. Transform data according to a clearly defined requirement, not simply because a function is available.

11. Common interview mistakes#

MistakeCorrect interpretation
A scalar function accepts exactly one argumentScalar refers to its single result, not its argument count
A scalar function always returns one query rowIt returns one value per evaluation; overall query cardinality depends on clauses
Every scalar function returns a non-NULL valueA scalar result can be NULL
Every function returns NULL for NULL inputFunction-specific rules differ
Applying a function in SELECT changes the tableOrdinary read-only expressions calculate result values
SUM and ABS are both scalar because they output one valueSUM summarizes a group; ABS transforms an argument value
A function always returns the input's typeReturn types follow the selected signature
A scalar function must be deterministicSingle-value return and determinism are separate properties

Interview-ready answer: A scalar function is a SQL function that returns a single value for each evaluation of its arguments. In a simple SELECT query, expressions such as ABS(delta) and TRIM(label) calculate a value for each input row without grouping the rows. A scalar function can accept several arguments, return NULL, and return a different data type from its input. Unlike scalar functions, ordinary aggregate functions such as SUM summarize a collection of rows. Scalar functions can be nested, used in predicates and combined with aggregates.

Quick checks: Is ABS(-8) scalar? Yes, its result is 8. Can a scalar function take three arguments? Yes, REPLACE is an example. Can a scalar function be used in WHERE? Yes, when its result participates in a valid predicate. Does CHAR_LENGTH(TRIM(label)) return two values? No; the inner scalar result becomes an argument to the outer function. Does SUM(ABS(delta)) preserve individual rows? No, SUM is an ordinary aggregate in that expression.

12. Validation and authoritative references#

Eight read-only PostgreSQL statements were executed successfully: literal function calls; row-level TRIM and ABS; WHERE filtering; nested functions; NULL handling; scalar-plus-aggregate composition; function-based ordering; and result-type inspection. All returned the results shown. No permanent tables or custom functions were created and no production business records were accessed or modified. The Mermaid diagram was structurally checked and stored in the exact triple-backtick mermaid code-block format. Full Mermaid parser validation and public-page rendering were unavailable.

Official Supabase Database Functions documentation was retrieved through the documentation connector. External PostgreSQL reference destinations below were not independently live fetched because web browsing was unavailable under the established offline research exception. Other-engine syntax, illustrative categories and performance considerations were not independently tested.

Related questions

Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning