NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RASTERIZEDDB SERVER / FUNCTIONS AND OPERATORS

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

FunctionReturnsWhat it does
COALESCE(a, b, …)common type of the argumentsThe first argument that is not NULL.
NULLIF(a, b)type of aNULL when a = b, otherwise a.
GREATEST(a, b, …)common typeThe largest argument, ignoring NULLs.
LEAST(a, b, …)common typeThe smallest argument, ignoring NULLs.
num_nulls(a, …)integerHow many arguments are NULL.
num_nonnulls(a, …)integerHow many arguments are not NULL.
CASE WHEN … THEN … [ELSE …] ENDcommon type of the armsThe first arm whose condition holds. Both the searched form and CASE x WHEN v THEN … work.
sql
SELECT COALESCE(NULL, 'fallback'),          -- fallback
       NULLIF(10, 10),                      -- NULL
       GREATEST(3, 7, 5),                   -- 7
       num_nulls(1, NULL, NULL);            -- 2

Operators

Comparison and pattern matching

OperatorWhat it does
=, <>, !=, <, >, <=, >=Ordinary comparisons.
IS NULL, IS NOT NULLNULL tests.
IS DISTINCT FROM, IS NOT DISTINCT FROMComparison that treats NULL as a value.
x BETWEEN a AND b, NOT BETWEENa <= 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 ILIKESQL patterns: % matches any run of characters, _ one character. ILIKE ignores case. ESCAPE 'c' sets the escape character.
SIMILAR TO, NOT SIMILAR TOSQL regular-expression patterns.
~, ~*, !~, !~*POSIX regular-expression match: case-sensitive, case-insensitive, and their negations. See Regular expressions.

Arithmetic

OperatorWhat 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.
-xNegation.

Date and time arithmetic:

ExpressionResult
date + integer, date - integerThe date that many days away.
date - dateThe number of days between them, as an integer.
date + interval, timestamp ± intervalA timestamp, moved by the interval (months and days move the calendar).
timestamp - timestampAn interval.
interval * number, interval / numberA scaled interval.
value AT TIME ZONE zoneConverts 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.

OperatorWhat it does
a & bBitwise AND.
a | bBitwise OR.
a # bBitwise XOR.
~aBitwise NOT.
a << n, a >> nShift left, shift right.

Text, arrays and documents

OperatorWhat it does
a || bConcatenates 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 rangesIntersection, 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.

sql
SELECT '42'::integer + 1,                        -- 43
       CAST('2026-03-01' AS date) + 30,          -- 2026-03-31
       (5 & 3) | 8,                              -- 9
       2 ^ 10;                                   -- 1024

Mathematical functions

FunctionReturnsWhat it does
abs(x)type of xAbsolute value.
ceil(x), ceiling(x)numeric for a numeric argument, otherwise double precisionSmallest integer not less than x.
floor(x)as ceilLargest integer not greater than x.
round(x)type of xRounds to the nearest integer.
round(x, n)numericRounds 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 roundTruncates toward zero, optionally to n places.
sign(x)as ceil-1, 0 or 1.
mod(a, b)type of the argumentsRemainder, the same as a % b.
div(a, b)numericInteger quotient, truncated toward zero.
sqrt(x)as ceilSquare root.
cbrt(x)double precisionCube root.
power(a, b), pow(a, b)numeric for numeric arguments, otherwise double precisiona raised to b.
exp(x)as powere raised to x.
ln(x)as powerNatural logarithm.
log(x)as powerBase-10 logarithm.
log(b, x)as powerLogarithm of x to base b.
log10(x)as powerBase-10 logarithm.
pi()double precisionπ.
degrees(x), radians(x)double precisionConverts radians to degrees, degrees to radians.
sin, cos, tan, cot, asin, acos, atandouble precisionTrigonometric functions, in radians.
atan2(y, x)double precisionArc tangent of y / x.
sinh, cosh, tanh, asinh, acosh, atanhdouble precisionHyperbolic functions.
random()double precisionA random value in [0, 1).
gcd(a, b), lcm(a, b)type of the argumentsGreatest common divisor, least common multiple.
factorial(n)numericn!.
width_bucket(x, low, high, count)integerWhich of count equal-width buckets between low and high holds x.
scale(x)integerNumber of decimal places in a numeric value.
min_scale(x)integerFewest places that represent the value exactly.
trim_scale(x)numericThe value with trailing fractional zeros removed.
isfinite(x)booleanWhether 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.

sql
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);  -- 5

String functions

FunctionReturnsWhat it does
lower(s), upper(s)textLower 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)textFirst letter of each word upper case, the rest lower.
length(s), char_length(s), character_length(s)integerNumber of characters.
octet_length(s)integerNumber of bytes.
left(s, n), right(s, n)textFirst or last n characters. A negative n drops -n characters from the other end.
substr(s, start [, count]), substring(s, start [, count])textPart of a string, counting from 1.
substring(s FROM start FOR count)textStandard spelling of the above; either clause may be left out.
position(sub IN s)integerWhere sub first occurs in s (0 when it does not).
strpos(s, sub)integerSame as position, arguments the other way round.
starts_with(s, prefix)booleanWhether s begins with prefix.
replace(s, from, to)textReplaces every occurrence of from.
translate(s, from, to)textReplaces 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)textCharacters in reverse order.
repeat(s, n)texts repeated n times.
concat(a, …)textJoins the arguments, skipping NULLs.
concat_ws(sep, a, …)textJoins the arguments with sep, skipping NULLs.
split_part(s, delimiter, n)textThe nth field; a negative n counts from the end.
trim([LEADING | TRAILING | BOTH] [chars] FROM s)textRemoves chars (default: spaces) from one or both ends.
btrim(s [, chars]), ltrim(s [, chars]), rtrim(s [, chars])textFunction forms of trim.
lpad(s, length [, fill]), rpad(s, length [, fill])textPads (or cuts) to length characters.
ascii(s)integerCode point of the first character.
chr(n)textThe character with code point n.
format(template, …)textFormats like PostgreSQL's format: %s (value), %I (quoted identifier), %L (quoted literal), with optional positions such as %2$s.
quote_ident(s)texts quoted as an identifier when it needs quotes.
quote_literal(s)texts quoted as a string literal.
to_hex(n)textHexadecimal form of an integer.
md5(s)textMD5 digest as 32 hex digits.
sha224(b), sha256(b), sha384(b), sha512(b)byteaSHA-2 digests.
encode(b, format)textbytea as hex, base64 or escape text.
decode(s, format)byteahex or base64 text back to bytes.
convert_to(s, encoding)byteaText as bytes in UTF8, LATIN1 or SQL_ASCII.
convert_from(b, encoding)textBytes in one of those encodings as text.
get_byte(b, n)integerThe 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])textJoins array elements.
sql
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

FunctionReturnsWhat it does
regexp_like(s, pattern [, flags])booleanWhether pattern matches anywhere in s.
regexp_replace(s, pattern, replacement [, flags])textReplaces 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]])integerHow many times pattern matches.
regexp_substr(s, pattern [, start [, n [, flags [, group]]]])textThe 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 \M and [[:<:]], [[:>:]], and \n \t \r \f \v \a \e \uXXXX \UXXXXXXXX;
  • embedded options (?i) and similar at the start, and the flags i 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.

sql
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

FunctionReturnsWhat it does
now(), CURRENT_TIMESTAMP, transaction_timestamp()timestamptzStart of the current transaction. Same value for every call in the transaction.
statement_timestamp()timestamptzStart of the current statement.
clock_timestamp()timestamptzThe actual time, changing during a statement.
CURRENT_DATEdateToday's date, at the transaction's start.
CURRENT_TIMEtimetzTime of day at the transaction's start.
LOCALTIMESTAMPtimestampnow() without a time zone.
LOCALTIMEtimeTime 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

FunctionReturnsWhat it does
make_date(year, month, day)dateA date from its parts.
make_timestamp(year, month, day, hour, min, sec)timestampA timestamp from its parts.
make_interval(years, months, weeks, days, hours, mins, secs)intervalAn interval. Arguments are positional or named (make_interval(days => 3)); missing ones are 0.
EXTRACT(field FROM value)numericOne field of a date, timestamp, time or interval.
date_part(field, value)double precisionThe same, as a float.
date_trunc(unit, value)timestamptzThe value floored to microseconds, milliseconds, second, minute, hour, day, week, month, quarter or year.
age(a, b)intervala - b in years, months and days.
age(a)intervalTime from a to today's midnight.
justify_days(i), justify_hours(i), justify_interval(i)intervalRolls 30-day periods into months and 24-hour periods into days.
to_char(value, template)textFormats a date, timestamp or number.
to_date(text, template)dateParses a date.
to_timestamp(text, template)timestamptzParses a timestamp.
to_timestamp(seconds)timestamptzConverts 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' (or GMT, Z and 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 as INTERVAL '2 hours'.

Abbreviations such as 'CET' or 'EST' are refused. Use a full zone name instead.

sql
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:00

Array functions

FunctionReturnsWhat it does
ARRAY[a, b, …]arrayBuilds an array. ARRAY[]::integer[] is an empty one.
a[i], a[lo:hi]element, arraySubscript and slice, counting from 1.
array_length(a, dim)integerLength of a dimension.
array_ndims(a)integerNumber of dimensions.
cardinality(a)integerTotal number of elements.
array_upper(a, dim), array_lower(a, dim)integerUpper and lower bound of a dimension.
array_dims(a)textBounds as text, such as [1:3].
array_append(a, x), array_prepend(x, a)arrayAdds an element at the end or the start.
array_cat(a, b)arrayJoins two arrays.
array_position(a, x [, start])integerPosition of the first x.
array_remove(a, x)arrayRemoves every x.
array_replace(a, x, y)arrayReplaces every x with y.
trim_array(a, n)arrayRemoves the last n elements.
array_fill(value, ARRAY[length])arrayA one-dimensional array of length copies of value.
string_to_array, array_to_stringSee String functions.

To turn an array into rows, use unnest in FROM (see Set-returning functions).

sql
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];                -- 20

Range functions

FunctionReturnsWhat it does
int4range(lo, hi [, bounds]), int8range, numrange, daterange, tsrange, tstzrangerangeBuilds a range. bounds is '[)' (the default), '[]', '(]' or '()'. A NULL bound is unbounded.
lower(r), upper(r)element typeThe lower or upper bound.
isempty(r)booleanWhether the range is empty.
lower_inc(r), upper_inc(r)booleanWhether a bound is inclusive.
lower_inf(r), upper_inf(r)booleanWhether a bound is unbounded.
range_merge(a, b)rangeThe smallest range that covers both.
sql
SELECT int4range(1, 5, '[]') @> 5,               -- true
       upper(int4range(1, 5)),                   -- 5
       int4range(1, 5) && int4range(4, 9);       -- true

UUID functions

FunctionReturnsWhat it does
gen_random_uuid(), uuid_generate_v4(), uuidv4()uuidA random version 4 UUID.
uuidv7()uuidA time-ordered version 7 UUID.
uuid_extract_version(u)smallintThe UUID's version, or NULL when it is not an RFC 9562 UUID.
uuid_extract_timestamp(u)timestamptzWhen 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:

FunctionReturnsWhat it does
jsonb_build_object(k, v, …), json_build_object(k, v, …)jsonb, jsonAn object from key/value pairs.
jsonb_build_array(…), json_build_array(…)jsonb, jsonAn array of the arguments.
to_jsonb(x), to_json(x)jsonb, jsonAny value as JSON.
jsonb_array_length(j), json_array_length(j)integerNumber of elements in a JSON array.
jsonb_typeof(j), json_typeof(j)textobject, array, string, number, boolean or null.
jsonb_set(target, path, value [, create_missing])jsonbtarget with the value at path replaced (or added).
jsonb_insert(target, path, value [, insert_after])jsonbtarget with value inserted at path.
jsonb_strip_nulls(j)jsonbRemoves object fields whose value is null.
jsonb_pretty(j)textIndented text form.
sql
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

FunctionReturnsWhat it does
jsonb_extract_path(j, key, …), json_extract_path(j, key, …)jsonb, jsonThe value at the path, the same as j #> ARRAY[key, …].
jsonb_extract_path_text(j, key, …), json_extract_path_text(j, key, …)textThe 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

FunctionReturnsWhat it does
nextval('seq')bigintAdvances the sequence and returns the new value.
currval('seq')bigintThe value nextval last returned for this sequence in this session.
setval('seq', n [, is_called])bigintSets the sequence's current value.
lastval()bigintThe 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.

FunctionReturnsWhat it does
count(*)bigintNumber of rows.
count(x)bigintNumber of non-NULL values.
sum(x)bigint for smallint/integer, numeric for bigint/numeric, float for floats, interval for intervalsSum of the values.
avg(x)numeric for exact types, double precision for floats, interval for intervalsAverage.
min(x), max(x)type of xSmallest and largest value.
stddev(x), stddev_samp(x), stddev_pop(x)numeric, or double precision for floatsSample or population standard deviation. stddev is stddev_samp.
variance(x), var_samp(x), var_pop(x)as stddevSample or population variance. variance is var_samp.
string_agg(s, delimiter)textNon-NULL text values joined with delimiter.
array_agg(x)arrayEvery value, NULL included, as an array.
json_agg(x), jsonb_agg(x)json, jsonbEvery value as a JSON array (NULL becomes null).
bool_and(b), every(b)booleanTrue when every non-NULL value is true.
bool_or(b)booleanTrue when any non-NULL value is true.
GROUPING(a, …)integerWith 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 BY inside the call, which decides the order for string_agg, array_agg, json_agg and jsonb_agg: string_agg(name, ', ' ORDER BY name);
  • FILTER (WHERE …), to fold only some rows: count(*) FILTER (WHERE status = 'failed').
sql
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;
text
 customer | orders | failed | spent | statuses
----------+--------+--------+-------+-------------
 ann      |      2 |      1 | 25.50 | paid,failed
 bob      |      1 |      0 | 12.25 | paid

Ordered-set aggregates

FunctionReturnsWhat it does
percentile_cont(f) WITHIN GROUP (ORDER BY x)double precisionThe 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 xThe first value whose position reaches fraction f.
mode() WITHIN GROUP (ORDER BY x)type of xThe 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 (…):

sql
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;
FunctionReturnsWhat it does
row_number()bigint1, 2, 3 … within the partition.
rank()bigintRank with gaps: 1, 1, 3.
dense_rank()bigintRank without gaps: 1, 1, 2.
percent_rank()double precision(rank - 1) / (rows in partition - 1).
cume_dist()double precisionFraction of the partition at or before this row.
ntile(n)integerWhich of n nearly equal buckets the row falls in, from 1.
lag(x [, offset [, default]])type of xThe value offset rows earlier (default 1).
lead(x [, offset [, default]])type of xThe value offset rows later.
first_value(x), last_value(x)type of xFirst or last value of the frame.
nth_value(x, n)type of xThe nth value of the frame.
sum, avg, count, min, maxas the aggregatesThe aggregate over the frame.

The window definition takes PARTITION BY, ORDER BY (with ASC/DESC and NULLS FIRST/NULLS LAST), and a frame:

  • ROWS, RANGE or GROUPS;
  • BETWEEN bounds from UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING, UNBOUNDED FOLLOWING;
  • EXCLUDE CURRENT ROW, EXCLUDE GROUP, EXCLUDE TIES or EXCLUDE 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).

FunctionRowsWhat it does
generate_series(start, stop [, step])integers, numeric values, or timestampsEvery value from start to stop. For timestamps or dates, step is an interval.
generate_subscripts(a, dim [, reverse])integerThe subscripts of one dimension of an array.
unnest(a [, b, …])one column per arrayThe elements of each array, side by side.
jsonb_each(j), jsonb_each_text(j)key, valueThe fields of an object.
jsonb_array_elements(j), jsonb_array_elements_text(j)valueThe elements of an array.
jsonb_object_keys(j)textThe keys of an object.
jsonb_to_record(j) AS t(col type, …), jsonb_to_recordset(j) AS t(col type, …)the listed columnsAn object (or an array of objects) as typed columns.
(VALUES (…), (…)) AS t(col, …)the listed columnsRows 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).

sql
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);
text
 letter | n
--------+---
 a      | 1
 b      | 2
 c      | 3

JSON 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

FunctionReturnsWhat it does
current_user, current_roletextThe role in effect (the one SET ROLE chose).
session_usertextThe role the session logged in as.
current_database(), current_catalogtextThe database the session is connected to.
current_schema()textAlways public.
current_schemas(include_implicit)text[]{pg_catalog,public} with true, {public} with false.
current_setting(name [, missing_ok])textA 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)textThe same as SET; returns the new value.
version()textThe server's version string.
pg_backend_pid()integerAn identifier for this connection.
pg_is_in_recovery()booleanAlways false.
pg_typeof(x)textThe 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.

sql
SELECT current_user, current_database(), current_setting('server_version_num');

Privilege checks, input checks and sleeping

FunctionReturnsWhat it does
has_table_privilege([role,] table, privilege)booleanWhether 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)booleanThe same for a column.
has_sequence_privilege([role,] sequence, privilege)booleanThe same for a sequence.
has_function_privilege([role,] function, 'EXECUTE')booleanWhether the role may call the function.
has_database_privilege([role,] database, privilege)booleanCONNECT and TEMPORARY on the current database.
pg_has_role([role,] other_role, 'MEMBER' | 'USAGE')booleanRole membership.
pg_input_is_valid(text, type)booleanWhether 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, \x and octal escapes, equivalence classes, ranges with a non-ASCII endpoint, a non-ASCII character in a case-insensitive pattern, and the flags x, p, w, b and e are 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_instr and regexp_split_to_table do not exist.
  • Regex functions that return positions or pieces. regexp_replace, regexp_count, regexp_substr and regexp_split_to_array refuse patterns with alternation (|), a non-greedy quantifier, or a quantified group such as (ab)+. Use them freely in ~ and regexp_like, which only answer yes or no.
  • to_char does 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_fill builds one-dimensional arrays only. Slicing a multidimensional array, and searching one with array_position, are refused.
  • decode reads hex and base64, not escape. convert_to and convert_from handle UTF8, LATIN1 and SQL_ASCII only.
  • lag and lead over a numeric column take no default value (the third argument).
  • Set-returning functions work in FROM only. 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, the jsonb delete operators - and #-, and the jsonb_path_* functions.
✓ page rendered in 199 µs axum + tera + htmx · no other javascript