Functions and operators
This page lists the built-in functions and operators you can use in SQL sent to RasterizedDB, grouped by what they work on. The names, argument forms and results follow PostgreSQL. A function that is not listed here is not available, and calling it fails with an error such as function '<name>' is not supported yet.
You can call functions in the select list, in WHERE, ORDER BY and GROUP BY, in CASE arms, and in INSERT/UPDATE values. Aggregates and window functions have their own rules, covered in their sections below. To write your own functions, see user functions.
Unless a row says otherwise, a function returns NULL when any argument is NULL. The exceptions are the same as PostgreSQL's: concat, concat_ws, format, the JSON builders, num_nulls and num_nonnulls, and COALESCE.
Conditional expressions
| Function | Returns | What it does |
|---|---|---|
COALESCE(a, b, …) | common type of the arguments | The first argument that is not NULL. |
NULLIF(a, b) | type of a | NULL when a = b, otherwise a. |
GREATEST(a, b, …) | common type | The largest argument, ignoring NULLs. |
LEAST(a, b, …) | common type | The smallest argument, ignoring NULLs. |
num_nulls(a, …) | integer | How many arguments are NULL. |
num_nonnulls(a, …) | integer | How many arguments are not NULL. |
CASE WHEN … THEN … [ELSE …] END | common type of the arms | The first arm whose condition holds. Both the searched form and CASE x WHEN v THEN … work. |
SELECT COALESCE(NULL, 'fallback'), -- fallback
NULLIF(10, 10), -- NULL
GREATEST(3, 7, 5), -- 7
num_nulls(1, NULL, NULL); -- 2Operators
Comparison and pattern matching
| Operator | What it does |
|---|---|
=, <>, !=, <, >, <=, >= | Ordinary comparisons. |
IS NULL, IS NOT NULL | NULL tests. |
IS DISTINCT FROM, IS NOT DISTINCT FROM | Comparison that treats NULL as a value. |
x BETWEEN a AND b, NOT BETWEEN | a <= x AND x <= b. |
x IN (…), NOT IN (…) | Membership in a list or a subquery. |
x op ANY (array), x op ALL (array) | Compares x with each element of an array. |
LIKE, NOT LIKE, ILIKE, NOT ILIKE | SQL patterns: % matches any run of characters, _ one character. ILIKE ignores case. ESCAPE 'c' sets the escape character. |
SIMILAR TO, NOT SIMILAR TO | SQL regular-expression patterns. |
~, ~*, !~, !~* | POSIX regular-expression match: case-sensitive, case-insensitive, and their negations. See Regular expressions. |
Arithmetic
| Operator | What it does |
|---|---|
+, -, *, / | Addition, subtraction, multiplication, division. Integer division truncates, as in PostgreSQL. |
% | Remainder. Works on integers, numeric and floats. |
^ | Power, the same as power(a, b). Groups left to right: 2 ^ 3 ^ 2 is 64. |
-x | Negation. |
Date and time arithmetic:
| Expression | Result |
|---|---|
date + integer, date - integer | The date that many days away. |
date - date | The number of days between them, as an integer. |
date + interval, timestamp ± interval | A timestamp, moved by the interval (months and days move the calendar). |
timestamp - timestamp | An interval. |
interval * number, interval / number | A scaled interval. |
value AT TIME ZONE zone | Converts between timestamptz and wall-clock time in zone. See Date and time. |
Bitwise
These work on integers (the result has the wider operand's type) and on bit strings of the same length.
| Operator | What it does |
|---|---|
a & b | Bitwise AND. |
a | b | Bitwise OR. |
a # b | Bitwise XOR. |
~a | Bitwise NOT. |
a << n, a >> n | Shift left, shift right. |
Text, arrays and documents
| Operator | What it does |
|---|---|
a || b | Concatenates text, appends arrays, or merges two jsonb values. |
->, ->>, #>, #>> | JSON path access. See JSON and JSONB. |
@>, <@ | Contains, is contained by: jsonb documents, arrays, ranges and geometric types. |
&& | Overlaps: arrays, ranges and geometric types. |
?, ?|, ?& | jsonb key exists, any key exists, all keys exist. |
@@ | Text-search match. See Full-text search and collations. |
<<=, >>= | Network is contained by or equal, contains or equal (inet/cidr). |
<<, >> | For networks, strictly contained by and strictly contains. For ranges, strictly left of and strictly right of. |
&<, &>, -|- | Ranges: does not extend to the right of, does not extend to the left of, is adjacent to. |
*, +, - on ranges | Intersection, union and difference of two ranges. |
Overlap and containment between geometric shapes are answered on their bounding boxes, not exact geometry. See Limits.
Casts
value::type and CAST(value AS type) mean the same thing. See Tables and data types for the types you can cast to.
SELECT '42'::integer + 1, -- 43
CAST('2026-03-01' AS date) + 30, -- 2026-03-31
(5 & 3) | 8, -- 9
2 ^ 10; -- 1024Mathematical functions
| Function | Returns | What it does |
|---|---|---|
abs(x) | type of x | Absolute value. |
ceil(x), ceiling(x) | numeric for a numeric argument, otherwise double precision | Smallest integer not less than x. |
floor(x) | as ceil | Largest integer not greater than x. |
round(x) | type of x | Rounds to the nearest integer. |
round(x, n) | numeric | Rounds to n decimal places (n may be negative). x must be exact (integer or numeric); a float needs a cast, as in PostgreSQL. |
trunc(x), trunc(x, n) | as round | Truncates toward zero, optionally to n places. |
sign(x) | as ceil | -1, 0 or 1. |
mod(a, b) | type of the arguments | Remainder, the same as a % b. |
div(a, b) | numeric | Integer quotient, truncated toward zero. |
sqrt(x) | as ceil | Square root. |
cbrt(x) | double precision | Cube root. |
power(a, b), pow(a, b) | numeric for numeric arguments, otherwise double precision | a raised to b. |
exp(x) | as power | e raised to x. |
ln(x) | as power | Natural logarithm. |
log(x) | as power | Base-10 logarithm. |
log(b, x) | as power | Logarithm of x to base b. |
log10(x) | as power | Base-10 logarithm. |
pi() | double precision | π. |
degrees(x), radians(x) | double precision | Converts radians to degrees, degrees to radians. |
sin, cos, tan, cot, asin, acos, atan | double precision | Trigonometric functions, in radians. |
atan2(y, x) | double precision | Arc tangent of y / x. |
sinh, cosh, tanh, asinh, acosh, atanh | double precision | Hyperbolic functions. |
random() | double precision | A random value in [0, 1). |
gcd(a, b), lcm(a, b) | type of the arguments | Greatest common divisor, least common multiple. |
factorial(n) | numeric | n!. |
width_bucket(x, low, high, count) | integer | Which of count equal-width buckets between low and high holds x. |
scale(x) | integer | Number of decimal places in a numeric value. |
min_scale(x) | integer | Fewest places that represent the value exactly. |
trim_scale(x) | numeric | The value with trailing fractional zeros removed. |
isfinite(x) | boolean | Whether a date, timestamp or interval is finite. |
numeric results of exp, ln, log and power are computed to PostgreSQL's display scale. A result that would need more than 38 digits, or more than 38 decimal places, is refused rather than rounded.
SELECT round(2.567, 2), -- 2.57
trunc(-7.9), -- -7
div(17, 5), -- 3
mod(17, 5), -- 2
width_bucket(42, 0, 100, 10); -- 5String functions
| Function | Returns | What it does |
|---|---|---|
lower(s), upper(s) | text | Lower or upper case, Unicode-aware (upper('straße') is STRAßE). On a range, these return its lower and upper bound instead (see Ranges). |
initcap(s) | text | First letter of each word upper case, the rest lower. |
length(s), char_length(s), character_length(s) | integer | Number of characters. |
octet_length(s) | integer | Number of bytes. |
left(s, n), right(s, n) | text | First or last n characters. A negative n drops -n characters from the other end. |
substr(s, start [, count]), substring(s, start [, count]) | text | Part of a string, counting from 1. |
substring(s FROM start FOR count) | text | Standard spelling of the above; either clause may be left out. |
position(sub IN s) | integer | Where sub first occurs in s (0 when it does not). |
strpos(s, sub) | integer | Same as position, arguments the other way round. |
starts_with(s, prefix) | boolean | Whether s begins with prefix. |
replace(s, from, to) | text | Replaces every occurrence of from. |
translate(s, from, to) | text | Replaces each character of from with the matching one in to; characters with no match are removed. |
overlay(s PLACING r FROM start [FOR count]) | text (or bytea) | Replaces count characters starting at start with r. |
reverse(s) | text | Characters in reverse order. |
repeat(s, n) | text | s repeated n times. |
concat(a, …) | text | Joins the arguments, skipping NULLs. |
concat_ws(sep, a, …) | text | Joins the arguments with sep, skipping NULLs. |
split_part(s, delimiter, n) | text | The nth field; a negative n counts from the end. |
trim([LEADING | TRAILING | BOTH] [chars] FROM s) | text | Removes chars (default: spaces) from one or both ends. |
btrim(s [, chars]), ltrim(s [, chars]), rtrim(s [, chars]) | text | Function forms of trim. |
lpad(s, length [, fill]), rpad(s, length [, fill]) | text | Pads (or cuts) to length characters. |
ascii(s) | integer | Code point of the first character. |
chr(n) | text | The character with code point n. |
format(template, …) | text | Formats like PostgreSQL's format: %s (value), %I (quoted identifier), %L (quoted literal), with optional positions such as %2$s. |
quote_ident(s) | text | s quoted as an identifier when it needs quotes. |
quote_literal(s) | text | s quoted as a string literal. |
to_hex(n) | text | Hexadecimal form of an integer. |
md5(s) | text | MD5 digest as 32 hex digits. |
sha224(b), sha256(b), sha384(b), sha512(b) | bytea | SHA-2 digests. |
encode(b, format) | text | bytea as hex, base64 or escape text. |
decode(s, format) | bytea | hex or base64 text back to bytes. |
convert_to(s, encoding) | bytea | Text as bytes in UTF8, LATIN1 or SQL_ASCII. |
convert_from(b, encoding) | text | Bytes in one of those encodings as text. |
get_byte(b, n) | integer | The byte at offset n (from 0). |
string_to_array(s, delimiter [, null_string]) | text[] | Splits text into an array. |
array_to_string(a, delimiter [, null_string]) | text | Joins array elements. |
SELECT left('Hello World', -2), -- Hello Wor
split_part('a,b,c', ',', -1), -- c
translate('abcabc', 'ab', 'x'), -- xcxc
initcap('hello wORLD foo-bar'), -- Hello World Foo-Bar
overlay('Txxxxas' PLACING 'hom' FROM 2 FOR 4), -- Thomas
concat('a', NULL, 1), -- a1
trim(LEADING 'x' FROM 'xxabc'), -- abc
to_hex(255), -- ff
encode(sha256('abc'::bytea), 'hex');Regular expressions
| Function | Returns | What it does |
|---|---|---|
regexp_like(s, pattern [, flags]) | boolean | Whether pattern matches anywhere in s. |
regexp_replace(s, pattern, replacement [, flags]) | text | Replaces the first match, or every match with flag g. \1…\9 in the replacement insert groups, \& the whole match. |
regexp_count(s, pattern [, start [, flags]]) | integer | How many times pattern matches. |
regexp_substr(s, pattern [, start [, n [, flags [, group]]]]) | text | The nth match, or one of its groups. |
regexp_split_to_array(s, pattern [, flags]) | text[] | Splits s at each match. |
The operators ~, ~*, !~ and !~* work anywhere a condition does, including the select list.
The pattern language is PostgreSQL's. What works:
- literals,
.,^,$,\A,\Z, groups( )and(?: ), alternation|; - quantifiers
*,+,?,{m},{m,},{m,n}(counts up to 255) and their non-greedy forms; - bracket expressions with ASCII ranges and the classes
[:digit:],[:xdigit:],[:alpha:],[:alnum:],[:upper:],[:lower:],[:space:],[:blank:],[:punct:],[:cntrl:],[:graph:],[:print:]; - the escapes
\d \D \s \S \w \W, the word boundaries\y \Y \m \Mand[[:<:]],[[:>:]], and\n \t \r \f \v \a \e \uXXXX \UXXXXXXXX; - embedded options
(?i)and similar at the start, and the flagsi c n m s t q.
As in PostgreSQL, \b is a backspace and not a word boundary, and . matches a newline unless you pass flag n.
SELECT 'order-1234' ~ '^order-[0-9]+$', -- true
regexp_replace('a1b22c333', '[0-9]+', '#', 'g'), -- a#b#c#
regexp_count('banana', 'an'), -- 2
regexp_split_to_array('a, b,c', ',\s*'); -- {a,b,c}Date and time
Current date and time
| Function | Returns | What it does |
|---|---|---|
now(), CURRENT_TIMESTAMP, transaction_timestamp() | timestamptz | Start of the current transaction. Same value for every call in the transaction. |
statement_timestamp() | timestamptz | Start of the current statement. |
clock_timestamp() | timestamptz | The actual time, changing during a statement. |
CURRENT_DATE | date | Today's date, at the transaction's start. |
CURRENT_TIME | timetz | Time of day at the transaction's start. |
LOCALTIMESTAMP | timestamp | now() without a time zone. |
LOCALTIME | time | Time of day without a time zone. |
CURRENT_TIME, CURRENT_TIMESTAMP, LOCALTIME and LOCALTIMESTAMP accept a precision: LOCALTIMESTAMP(0) drops the fractional seconds.
Building, reading and formatting dates
| Function | Returns | What it does |
|---|---|---|
make_date(year, month, day) | date | A date from its parts. |
make_timestamp(year, month, day, hour, min, sec) | timestamp | A timestamp from its parts. |
make_interval(years, months, weeks, days, hours, mins, secs) | interval | An interval. Arguments are positional or named (make_interval(days => 3)); missing ones are 0. |
EXTRACT(field FROM value) | numeric | One field of a date, timestamp, time or interval. |
date_part(field, value) | double precision | The same, as a float. |
date_trunc(unit, value) | timestamptz | The value floored to microseconds, milliseconds, second, minute, hour, day, week, month, quarter or year. |
age(a, b) | interval | a - b in years, months and days. |
age(a) | interval | Time from a to today's midnight. |
justify_days(i), justify_hours(i), justify_interval(i) | interval | Rolls 30-day periods into months and 24-hour periods into days. |
to_char(value, template) | text | Formats a date, timestamp or number. |
to_date(text, template) | date | Parses a date. |
to_timestamp(text, template) | timestamptz | Parses a timestamp. |
to_timestamp(seconds) | timestamptz | Converts Unix epoch seconds. |
Fields for EXTRACT and date_part: year, month, day, hour, minute, second, milliseconds, microseconds, dow, isodow, doy, quarter, week, isoyear, decade, century, millennium, epoch. Plurals and short forms (years, mon, hrs, ms, us and so on) are accepted.
to_char template patterns for dates and timestamps: YYYY, Y,YYY, YYY, YY, Y, IYYY, IYY, IY, I, IW, ID, IDDD, CC, MM, DD, DDD, D, W, WW, Q, J, HH24, HH12, HH, MI, SS, SSSS, SSSSS, MS, US, FF1 to FF6, AM/PM, A.M./P.M., AD/BC, A.D./B.C., MONTH, MON, DAY, DY, RM, with the FM prefix and ordinal suffixes. For numbers: 9, 0, ., ,, D, G and FM.
to_date and to_timestamp read YYYY, YY, MM, DD, HH24, HH12, HH, MI, SS, MS, US, AM/PM, MON and MONTH.
Time zones
ts AT TIME ZONE zone converts a timestamptz to the wall-clock time in zone, or reads a wall-clock timestamp as being in zone. The zone can be:
- a full IANA name, such as
'Europe/Berlin'or'America/New_York'; 'UTC'(orGMT,Zand similar);- an offset such as
'+02:00'or'UTC+5', using the POSIX sign convention that PostgreSQL uses, where'UTC+5'means five hours west of Greenwich; - an
interval, such asINTERVAL '2 hours'.
Abbreviations such as 'CET' or 'EST' are refused. Use a full zone name instead.
SELECT EXTRACT(YEAR FROM '2026-03-23 10:11:12'::timestamp), -- 2026
date_trunc('month', '2026-03-23 10:11:12+00'::timestamptz), -- 2026-03-01 00:00:00+00
to_char('2026-03-05'::date, 'FMDay, DD Mon YYYY'), -- Thursday, 05 Mar 2026
make_interval(days => 3, hours => 4), -- 3 days 04:00:00
'2026-07-01 12:00:00+00'::timestamptz AT TIME ZONE 'Europe/Berlin'; -- 2026-07-01 14:00:00Array functions
| Function | Returns | What it does |
|---|---|---|
ARRAY[a, b, …] | array | Builds an array. ARRAY[]::integer[] is an empty one. |
a[i], a[lo:hi] | element, array | Subscript and slice, counting from 1. |
array_length(a, dim) | integer | Length of a dimension. |
array_ndims(a) | integer | Number of dimensions. |
cardinality(a) | integer | Total number of elements. |
array_upper(a, dim), array_lower(a, dim) | integer | Upper and lower bound of a dimension. |
array_dims(a) | text | Bounds as text, such as [1:3]. |
array_append(a, x), array_prepend(x, a) | array | Adds an element at the end or the start. |
array_cat(a, b) | array | Joins two arrays. |
array_position(a, x [, start]) | integer | Position of the first x. |
array_remove(a, x) | array | Removes every x. |
array_replace(a, x, y) | array | Replaces every x with y. |
trim_array(a, n) | array | Removes the last n elements. |
array_fill(value, ARRAY[length]) | array | A one-dimensional array of length copies of value. |
string_to_array, array_to_string | See String functions. |
To turn an array into rows, use unnest in FROM (see Set-returning functions).
SELECT array_append(ARRAY[1, 2], 3), -- {1,2,3}
array_position(ARRAY['a', 'b'], 'b'), -- 2
cardinality(ARRAY[1, 2, 3]), -- 3
(ARRAY[10, 20, 30])[2]; -- 20Range functions
| Function | Returns | What it does |
|---|---|---|
int4range(lo, hi [, bounds]), int8range, numrange, daterange, tsrange, tstzrange | range | Builds a range. bounds is '[)' (the default), '[]', '(]' or '()'. A NULL bound is unbounded. |
lower(r), upper(r) | element type | The lower or upper bound. |
isempty(r) | boolean | Whether the range is empty. |
lower_inc(r), upper_inc(r) | boolean | Whether a bound is inclusive. |
lower_inf(r), upper_inf(r) | boolean | Whether a bound is unbounded. |
range_merge(a, b) | range | The smallest range that covers both. |
SELECT int4range(1, 5, '[]') @> 5, -- true
upper(int4range(1, 5)), -- 5
int4range(1, 5) && int4range(4, 9); -- trueUUID functions
| Function | Returns | What it does |
|---|---|---|
gen_random_uuid(), uuid_generate_v4(), uuidv4() | uuid | A random version 4 UUID. |
uuidv7() | uuid | A time-ordered version 7 UUID. |
uuid_extract_version(u) | smallint | The UUID's version, or NULL when it is not an RFC 9562 UUID. |
uuid_extract_timestamp(u) | timestamptz | When a version 1 or 7 UUID was made; NULL for other versions. |
Each row gets its own value: INSERT … SELECT gen_random_uuid(), … puts a distinct UUID in every row.
JSON functions
The full guide to JSON is JSON and JSONB. The functions:
| Function | Returns | What it does |
|---|---|---|
jsonb_build_object(k, v, …), json_build_object(k, v, …) | jsonb, json | An object from key/value pairs. |
jsonb_build_array(…), json_build_array(…) | jsonb, json | An array of the arguments. |
to_jsonb(x), to_json(x) | jsonb, json | Any value as JSON. |
jsonb_array_length(j), json_array_length(j) | integer | Number of elements in a JSON array. |
jsonb_typeof(j), json_typeof(j) | text | object, array, string, number, boolean or null. |
jsonb_set(target, path, value [, create_missing]) | jsonb | target with the value at path replaced (or added). |
jsonb_insert(target, path, value [, insert_after]) | jsonb | target with value inserted at path. |
jsonb_strip_nulls(j) | jsonb | Removes object fields whose value is null. |
jsonb_pretty(j) | text | Indented text form. |
SELECT jsonb_build_object('id', 7, 'tags', jsonb_build_array('a', 'b')),
jsonb_set('{"a": 1}'::jsonb, '{b}', '2'::jsonb), -- {"a": 1, "b": 2}
jsonb_insert('{"a": [0, 1, 2]}'::jsonb, '{a,1}', '"new"'::jsonb); -- {"a": [0, "new", 1, 2]}Path extraction functions
| Function | Returns | What it does |
|---|---|---|
jsonb_extract_path(j, key, …), json_extract_path(j, key, …) | jsonb, json | The value at the path, the same as j #> ARRAY[key, …]. |
jsonb_extract_path_text(j, key, …), json_extract_path_text(j, key, …) | text | The same, as text (#>>). |
Text search functions
to_tsvector, to_tsquery, plainto_tsquery, phraseto_tsquery, websearch_to_tsquery, the @@ operator and ts_rank are described in Full-text search and collations.
Sequence functions
| Function | Returns | What it does |
|---|---|---|
nextval('seq') | bigint | Advances the sequence and returns the new value. |
currval('seq') | bigint | The value nextval last returned for this sequence in this session. |
setval('seq', n [, is_called]) | bigint | Sets the sequence's current value. |
lastval() | bigint | The value the most recent nextval in this session returned. |
Creating sequences is covered in Schemas, views and other objects.
Aggregate functions
Aggregates fold a group of rows into one value. Use them with GROUP BY, or over the whole result without it. See Querying data for GROUP BY, HAVING, ROLLUP, CUBE and GROUPING SETS.
| Function | Returns | What it does |
|---|---|---|
count(*) | bigint | Number of rows. |
count(x) | bigint | Number of non-NULL values. |
sum(x) | bigint for smallint/integer, numeric for bigint/numeric, float for floats, interval for intervals | Sum of the values. |
avg(x) | numeric for exact types, double precision for floats, interval for intervals | Average. |
min(x), max(x) | type of x | Smallest and largest value. |
stddev(x), stddev_samp(x), stddev_pop(x) | numeric, or double precision for floats | Sample or population standard deviation. stddev is stddev_samp. |
variance(x), var_samp(x), var_pop(x) | as stddev | Sample or population variance. variance is var_samp. |
string_agg(s, delimiter) | text | Non-NULL text values joined with delimiter. |
array_agg(x) | array | Every value, NULL included, as an array. |
json_agg(x), jsonb_agg(x) | json, jsonb | Every value as a JSON array (NULL becomes null). |
bool_and(b), every(b) | boolean | True when every non-NULL value is true. |
bool_or(b) | boolean | True when any non-NULL value is true. |
GROUPING(a, …) | integer | With ROLLUP, CUBE or GROUPING SETS: a bit mask of the listed keys that the current row does not group by. |
Every aggregate accepts:
DISTINCT, to fold each distinct value once:count(DISTINCT customer_id);ORDER BYinside the call, which decides the order forstring_agg,array_agg,json_aggandjsonb_agg:string_agg(name, ', ' ORDER BY name);FILTER (WHERE …), to fold only some rows:count(*) FILTER (WHERE status = 'failed').
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, status TEXT, total NUMERIC(10,2));
INSERT INTO orders VALUES (1, 'ann', 'paid', 20.00), (2, 'ann', 'failed', 5.50), (3, 'bob', 'paid', 12.25);
SELECT customer,
count(*) AS orders,
count(*) FILTER (WHERE status = 'failed') AS failed,
sum(total) AS spent,
string_agg(status, ',' ORDER BY id) AS statuses
FROM orders
GROUP BY customer
ORDER BY customer; customer | orders | failed | spent | statuses
----------+--------+--------+-------+-------------
ann | 2 | 1 | 25.50 | paid,failed
bob | 1 | 0 | 12.25 | paidOrdered-set aggregates
| Function | Returns | What it does |
|---|---|---|
percentile_cont(f) WITHIN GROUP (ORDER BY x) | double precision | The value at fraction f (0 to 1) of the ordered values, interpolated. percentile_cont(0.5) is the median. |
percentile_disc(f) WITHIN GROUP (ORDER BY x) | type of x | The first value whose position reaches fraction f. |
mode() WITHIN GROUP (ORDER BY x) | type of x | The most frequent non-NULL value. |
Window functions
A window function adds a column computed from the rows around each row, without folding them. It is written with OVER (…):
SELECT id, customer, total,
row_number() OVER (PARTITION BY customer ORDER BY id) AS n,
sum(total) OVER (PARTITION BY customer ORDER BY id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM orders;| Function | Returns | What it does |
|---|---|---|
row_number() | bigint | 1, 2, 3 … within the partition. |
rank() | bigint | Rank with gaps: 1, 1, 3. |
dense_rank() | bigint | Rank without gaps: 1, 1, 2. |
percent_rank() | double precision | (rank - 1) / (rows in partition - 1). |
cume_dist() | double precision | Fraction of the partition at or before this row. |
ntile(n) | integer | Which of n nearly equal buckets the row falls in, from 1. |
lag(x [, offset [, default]]) | type of x | The value offset rows earlier (default 1). |
lead(x [, offset [, default]]) | type of x | The value offset rows later. |
first_value(x), last_value(x) | type of x | First or last value of the frame. |
nth_value(x, n) | type of x | The nth value of the frame. |
sum, avg, count, min, max | as the aggregates | The aggregate over the frame. |
The window definition takes PARTITION BY, ORDER BY (with ASC/DESC and NULLS FIRST/NULLS LAST), and a frame:
ROWS,RANGEorGROUPS;BETWEENbounds fromUNBOUNDED PRECEDING,n PRECEDING,CURRENT ROW,n FOLLOWING,UNBOUNDED FOLLOWING;EXCLUDE CURRENT ROW,EXCLUDE GROUP,EXCLUDE TIESorEXCLUDE NO OTHERS.
An aggregate window call can also take FILTER (WHERE …). A window call can sit inside a larger expression, such as total - lag(total) OVER (ORDER BY id). As in PostgreSQL, the ranking functions, ntile, lag and lead ignore the frame. More on windows in Querying data.
Set-returning functions
These produce rows and go in FROM, like a table. Each can take WITH ORDINALITY, which adds a numbered column, and an alias with column names: AS t(n).
| Function | Rows | What it does |
|---|---|---|
generate_series(start, stop [, step]) | integers, numeric values, or timestamps | Every value from start to stop. For timestamps or dates, step is an interval. |
generate_subscripts(a, dim [, reverse]) | integer | The subscripts of one dimension of an array. |
unnest(a [, b, …]) | one column per array | The elements of each array, side by side. |
jsonb_each(j), jsonb_each_text(j) | key, value | The fields of an object. |
jsonb_array_elements(j), jsonb_array_elements_text(j) | value | The elements of an array. |
jsonb_object_keys(j) | text | The keys of an object. |
jsonb_to_record(j) AS t(col type, …), jsonb_to_recordset(j) AS t(col type, …) | the listed columns | An object (or an array of objects) as typed columns. |
(VALUES (…), (…)) AS t(col, …) | the listed columns | Rows written inline. |
An argument can be a column of a table earlier in the FROM list, which makes the call run once per row of that table (an implicit LATERAL).
SELECT d::date AS day
FROM generate_series('2026-03-01'::timestamp, '2026-03-05'::timestamp, '1 day'::interval) AS g(d);
SELECT * FROM unnest(ARRAY['a', 'b', 'c']) WITH ORDINALITY AS t(letter, n); letter | n
--------+---
a | 1
b | 2
c | 3JSON forms of the set-returning functions
json_each, json_each_text, json_array_elements, json_array_elements_text and json_object_keys work like their jsonb_ counterparts on json values, keeping the text and member order as written.
Session and system information
| Function | Returns | What it does |
|---|---|---|
current_user, current_role | text | The role in effect (the one SET ROLE chose). |
session_user | text | The role the session logged in as. |
current_database(), current_catalog | text | The database the session is connected to. |
current_schema() | text | Always public. |
current_schemas(include_implicit) | text[] | {pg_catalog,public} with true, {public} with false. |
current_setting(name [, missing_ok]) | text | A run-time setting's value, as SHOW reports it. An unknown name is an error unless missing_ok is true, which returns NULL. |
set_config(name, value, is_local) | text | The same as SET; returns the new value. |
version() | text | The server's version string. |
pg_backend_pid() | integer | An identifier for this connection. |
pg_is_in_recovery() | boolean | Always false. |
pg_typeof(x) | text | The PostgreSQL type name of x. |
The pg_get_… functions (pg_get_indexdef, pg_get_constraintdef, pg_get_expr, pg_get_userbyid, format_type and similar) exist for client tools and drivers that read the system catalogues. obj_description, col_description and shobj_description always return NULL, because comments are not stored.
SELECT current_user, current_database(), current_setting('server_version_num');Privilege checks, input checks and sleeping
| Function | Returns | What it does |
|---|---|---|
has_table_privilege([role,] table, privilege) | boolean | Whether the role holds the privilege (SELECT, INSERT, …, optionally WITH GRANT OPTION). The role defaults to the current one. |
has_column_privilege([role,] table, column, privilege) | boolean | The same for a column. |
has_sequence_privilege([role,] sequence, privilege) | boolean | The same for a sequence. |
has_function_privilege([role,] function, 'EXECUTE') | boolean | Whether the role may call the function. |
has_database_privilege([role,] database, privilege) | boolean | CONNECT and TEMPORARY on the current database. |
pg_has_role([role,] other_role, 'MEMBER' | 'USAGE') | boolean | Role membership. |
pg_input_is_valid(text, type) | boolean | Whether the text would cast to the type without an error. |
pg_sleep(seconds) | Waits that many seconds (fractions allowed). | |
pg_sleep_for(interval) | Waits for an interval. | |
pg_sleep_until(timestamptz) | Waits until a moment. |
The privilege functions are answered only when their arguments are literals. The pg_sleep functions work only as items of a SELECT with no FROM, such as SELECT pg_sleep(1.5).
Limits
- Regular expressions. Back-references, look-ahead and look-behind,
\xand octal escapes, equivalence classes, ranges with a non-ASCII endpoint, a non-ASCII character in a case-insensitive pattern, and the flagsx,p,w,bandeare refused. The locale-dependent parts (\w,\s, word boundaries, most character classes, case-insensitive matching) are refused on text that contains non-ASCII characters.regexp_match,regexp_matches,regexp_instrandregexp_split_to_tabledo not exist. - Regex functions that return positions or pieces.
regexp_replace,regexp_count,regexp_substrandregexp_split_to_arrayrefuse patterns with alternation (|), a non-greedy quantifier, or a quantified group such as(ab)+. Use them freely in~andregexp_like, which only answer yes or no. to_chardoes not format intervals, and refuses template patterns outside the lists above, including time-zone patterns.- Time zones. Abbreviations (
CET,EST,PST) are refused; use full names. - Geometric operators
@>,<@and&&compare bounding boxes. A polygon inside another's bounding box but outside the polygon itself counts as contained, where PostgreSQL says it is not. array_fillbuilds one-dimensional arrays only. Slicing a multidimensional array, and searching one witharray_position, are refused.decodereadshexandbase64, notescape.convert_toandconvert_fromhandleUTF8,LATIN1andSQL_ASCIIonly.lagandleadover anumericcolumn take no default value (the third argument).- Set-returning functions work in
FROMonly. Calling one inside an expression in the select list is refused. Each call can produce at most 1,000,000 rows. - Not available:
ts_rank_cd,json_object_agg,jsonb_object_agg,bit_and,bit_or, thejsonbdelete operators-and#-, and thejsonb_path_*functions.