40 String and Numeric Functions
PostgreSQL ships with hundreds of built-in functions. The string and math families cover most day-to-day needs: case conversion, padding, trimming, splitting, replacing, hashing; rounding, absolute value, modulus, exponentiation, random. Get comfortable with the common ones and you will reach for them constantly.
What you’ll learn
- Common string functions:
upper,lower,length,substring,position,trim,replace,split_part - String concatenation with
||andconcat - Regex with
~,~*,regexp_replace,regexp_match - Common numeric functions:
abs,round,ceil,floor,mod,power,random - The
\dfmeta-command to discover more
Example
substring has two forms: the SQL-standard substring(str FROM start FOR n) and the function-call style substring(str, start, n). Both are 1-based.
concat and || differ on NULL: 'a' || NULL is NULL (any operand makes the whole expression NULL), while concat('a', NULL, 'b') returns 'ab' — concat treats NULLs as empty strings. Pick the behavior you want explicitly.
The regex operators ~ and ~* are matching shortcuts. regexp_replace(text, pattern, replacement [, flags]) is the workhorse for substitutions; the 'g' flag means “replace all matches” (default is first only). regexp_match returns the captured groups.
Numeric functions are mostly self-explanatory. random() returns a double precision in [0, 1); use floor(random() * n)::integer for integers from 0 through n − 1. A direct cast rounds instead of truncating. For cryptographically secure random, use gen_random_bytes from pgcrypto.
Run the example
To run:
Common pitfalls
- Confusing
substringindexing with zero-based languages — PostgreSQL is 1-based. replaceis a literal-string replacement, not a regex. For regex, useregexp_replace.random()is not cryptographically secure. For security-sensitive cases, usepgcrypto’sgen_random_bytes.lengthcounts characters;octet_lengthcounts bytes. They differ for multibyte text (UTF-8).round(numeric)rounds ties away from zero:round(0.5)is1andround(-0.5)is-1.round(double precision)commonly rounds ties to even, with platform-dependent behavior.
In interactive psql, \df *upper* lists every function with “upper” in the name. \df+ upper shows the source/owner. Excellent way to discover what is available.
Build a label: SELECT upper(name) || ' [' || length(name) || ']' FROM fruits;. Round all averages: SELECT customer_id, round(avg(total), 2) FROM orders_example GROUP BY customer_id;. Use regex to find names starting with a vowel: SELECT name FROM fruits WHERE name ~* '^[aeiou]';.
Downloads
SQL file: string-and-numeric-functions.sql · All lesson files · Setup guide