SQL Expressions
Row filters and the SQL Console share the expression rules on this page. The dialect is modeled on PostgreSQL, and this page points out where SmoothCSV differs from it.
Row Filter Conditions
A row filter takes one condition, the part of a query that would follow WHERE, and shows the rows where it is true.
amount > 1000 AND status ILIKE 'open%'
A comparison with NULL is unknown, and an unknown condition hides the row. Test for NULL with IS NULL.
Subqueries, aggregates, window functions, and other files are available only in the SQL Console.
Referencing Columns
- Heading: the column heading, as in
amount > 1000. Put a heading that has spaces or other special characters in double quotes, and double a quote inside it:"First Name" LIKE 'John%',"say ""hi""". - Position:
c1,c2, and so on name columns by position, with or without a header row:c1 > 1000 AND c2 = 'Active'. rowid: the row’s position in the file, starting at 1 and counting header rows:rowid > 100. With one header row, the first data row is2, which matches the grid’s row numbers with the default numbering settings.
Names ignore case. When two headings differ only by case, write the heading’s own spelling; any other spelling is ambiguous.
Some headings cannot be used as names:
- When two columns share a heading, the first one takes it and the later ones are only
cN. - A heading spelled like a position name of the file (
c1up to the number of columns, in lowercase) or likerowid(in any case) refers to that position or to the row number, not to the column with that heading.
With more than one header row, the last header row names the columns. When Use Selected Row(s) as Column Names picks several rows, the name joins their non-empty cells with /, and a blank cell in an upper row takes the value to its left (2024 / id, 2024 / name).
Data Types
Every cell is text. An empty cell is empty text. A cell past the end of a short row is NULL in a file with Allow Different Column Count; otherwise short rows are padded with empty text.
A comparison, IN, or a simple CASE x WHEN … reads text as the type of the other side:
amount > 10compares numbersshipped > DATE '2024-01-05'compares datesamount > '10'compares text, in Unicode code point order, so'9' > '10'amount > budgetcompares text, because both sides are text. Cast one side to compare numbers:TRY_CAST(amount AS numeric) > budget
A string literal such as '10' has no type of its own and takes the type of the value it meets: LENGTH(name) > '3' compares numbers, active = 't' compares booleans, and 10 / '4' divides integers. Columns are text, not untyped, so amount > '10' still compares text.
Outside CAST, a cell that has to be read as a number, date, time, interval, or JSON but cannot be, such as a blank cell, is NULL, so a comparison with it is unknown. A string literal that cannot be read is an error, such as 'abc', or '2.5' against an integer.
How text is read as numbers and dates depends on Decimal Separator and Month and Day Order in Settings. They apply to all files and default to the system’s regional format (the browser language in the web app).
Mixed Types in CASE, COALESCE, and UNION
CASE, COALESCE, NULLIF, UNION, INTERSECT, EXCEPT, VALUES, IN lists, ARRAY, and the default of LAG and LEAD give their values one type:
- String and NULL literals take the type of the other values, and are text when every value is a literal:
CASE WHEN p THEN 1 ELSE '2' ENDis an integer, andSELECT 10 UNION SELECT '9'returns numbers. - Any text among the other values makes the result text, so
COALESCE(amount, 0)is text. - Integers with floating point make floating point, and dates with timestamps make timestamps.
Numbers
Text is read as a number with the selected Decimal Separator:
- With
.,1,234.5is 1234.5. - With
,,1.234,5is 1234.5, and1.5is not a number. - A value valid with either setting follows the selected one:
1,500is 1500 with., or 1.5 with,.
Digits may be grouped with the other separator or with spaces, including non-breaking spaces. Full-width digits and surrounding spaces are accepted. The whole value must be a number: $100, 12%, NaN, and Infinity are not numbers.
An integer that fits in 64 bits stays exact. Any other number is floating point (double precision). numeric and decimal are double precision too, not exact decimals.
A blank amount makes both amount > 0 and amount = 0 unknown, so the row stays hidden. amount = '' matches an empty cell, and amount IS NULL matches a missing cell.
Arithmetic:
- Integers stay integers, and division truncates toward zero:
7 / 2is3. Integer overflow is an error. - Text or floating point on either side makes the result floating point, so a cell
3divided by2is1.5. - A floating-point result that is not a finite number is NULL:
1e308 * 10is NULL. - Division by zero is an error.
Dates and Times
Text is read as a date in these forms, in comparisons, casts, and typed literals alike:
- A year first:
2026-03-05,2026/3/5,2026.03.05,20260305, or2026年3月5日 - An English month name:
5 Mar 2026,05-Mar-2026,March 5, 2026, orMar 5 2026 - A four-digit year last with
/or-: Month and Day Order in Settings chooses the order.03/05/2026is March 5 with month first, or May 3 with day first. A value that does not fit the chosen order is invalid; the order is never switched per value - A four-digit year last with
.: always day, month, year (05.03.2026is March 5)
Two-digit years, epoch, and Julian days are not accepted.
A time may follow the date after a space or T. A time is H:MM, optionally followed by seconds, fractional seconds, AM or PM, and an offset (Z, +09, +0900, or +09:00; not +9). A time alone uses the same form: TIME '2:30 PM' is 14:30:00.
Arithmetic:
- A date plus or minus an integer shifts by that many days.
- A date or timestamp plus or minus an interval is a timestamp:
DATE '2024-01-01' + INTERVAL '12 hours'is noon on that day. - Subtracting two dates returns a number of days.
- Subtracting two timestamps returns an interval of whole 24-hour days and the remaining time:
TIMESTAMP '2026-03-01 12:00' - TIMESTAMP '2026-01-01'is59 days 12:00:00.
Time Zones
A date or time without an offset is in the operating system’s time zone when it is converted to TIMESTAMPTZ (timestamp with time zone) or compared with one, with the offset in effect on that date. TIMESTAMPTZ values display in that zone, and converting them to dates or times, EXTRACT, TO_CHAR, and DATE_TRUNC use that zone too.
CURRENT_DATE, LOCALTIMESTAMP, and LOCALTIME use that zone’s clock. CURRENT_TIMESTAMP and NOW() return the current instant, and CURRENT_TIME includes an offset. A time without an offset converted to TIMETZ (time with time zone) takes the zone’s offset when execution starts.
Text read as a timestamp keeps the date and time it shows and drops the offset, as in PostgreSQL: '2026-03-10 03:00Z'::timestamp is 2026-03-10T03:00:00. DATE_TRUNC, EXTRACT, DATE_PART, AT TIME ZONE, and TIMEZONE read text this way, and so do AGE and DATE_BIN unless another argument is a TIMESTAMPTZ. To use the instant in the OS time zone, cast the text first: DATE_TRUNC('day', c::timestamptz).
Unlike PostgreSQL, which ignores the offset, a TIMESTAMP literal written with an offset is a TIMESTAMPTZ, as the SQL standard specifies.
At a daylight saving transition, a skipped local time uses the offset before the clock moves forward, and a repeated local time uses the offset after the clock moves back. Neither is an error. In New York, '2026-03-08 02:30'::timestamptz is 2026-03-08T03:30:00-04:00, and '2026-11-01 01:30'::timestamptz is 2026-11-01T01:30:00-05:00. Adding INTERVAL '1 day' to a TIMESTAMPTZ keeps the local time of day across a transition; adding INTERVAL '24 hours' adds 24 elapsed hours.
AT TIME ZONE converts between local timestamps and instants. TIMESTAMP '2026-07-15 12:00' AT TIME ZONE 'America/New_York' is the instant 16:00 UTC, and the same AT TIME ZONE applied to that instant returns the local timestamp 12:00. TIMEZONE(zone, value) is the same as value AT TIME ZONE zone. The zone can be:
- An IANA region name, such as
America/New_YorkorAsia/Tokyo. A region uses its offset on the timestamp’s date; for a time without a date, the offset when execution starts. - A fixed offset. Nine hours east of UTC is
INTERVAL '9 hours'or'-09:00': text offsets count west of UTC. - An abbreviation from PostgreSQL’s default set. Most, such as
EST,JST, andCEST, are fixed offsets all year; some, such asVET, follow a region. Unlike PostgreSQL, an abbreviation that regions use for different offsets, such asIST(India, Israel, and Ireland) orCST(North America, Cuba, and China), is an error. Write a region name such asAsia/Kolkatainstead.
Booleans, JSON, and Arrays
- Text reads as true when it is
true,t,yes,y,on, or1, and as false when it isfalse,f,no,n,off,0, or blank. A number is false when zero and true otherwise, includingCAST(0.5 AS boolean). Booleans compare only with booleans, and only with=and<>. jsonkeeps the text as written.jsonbstores a normalized value, as in PostgreSQL: object keys are sorted, and a repeated key keeps its last value.- Arrays do not keep an element type and cannot hold
jsonorjsonbvalues. Build an array withARRAY[1,2]; text such as'{1,2}'cannot be cast to an array, and only NULL casts to an array type such asint[]. - Comparing or ordering
json,jsonb, or arrays is an error.
Values as Text
Results show values in these forms, and UPDATE and INSERT write them the same way. A cast to text, or a function that takes text, gives the same text: CONCAT('a', true) is atrue.
| Type | Text |
|---|---|
| Number | The selected decimal separator, no grouping: 1234.5, or 1234,5 with , |
| Boolean | true or false |
| Date | ISO 8601: 2026-03-05 |
| Timestamp | T between the date and time: 2024-01-02T03:04:05 |
TIMESTAMPTZ |
The OS time zone with a numeric offset, +00:00 in UTC: 2026-03-08T03:30:00-04:00 |
| Interval | PostgreSQL’s default format: 1 year 2 mons -3 days +04:05:06, 36:00:00. Casting this text back to interval keeps the months, days, and time |
| Array | PostgreSQL’s brace notation with each element in these forms: {{1,2},{3,4}}, {"a,b",NULL,"NULL",""}, {true,false} (PostgreSQL shows {t,f}) |
jsonb |
Normalized: {"a": 1, "b": 2} |
In TO_CHAR and TO_NUMBER templates, D (decimal separator) and G (grouping) follow the Decimal Separator setting, while . and , stay fixed.
Casts
CAST(x AS type) and x::type report an error for a value that cannot be converted. TRY_CAST(x AS type) returns NULL instead. Text is read with the same rules as in a comparison.
CAST('123' AS bigint) -- 123
TRY_CAST('abc' AS bigint) -- NULL
CAST('yes' AS boolean) -- true
CAST('2024-03-14' AS date)
CAST('15:30:00' AS time)
CAST('2024-03-14 15:30:00' AS timestamp)
amount::double precision > 10
- An integer cast rounds ties away from zero:
2.5becomes3, and-2.5becomes-3.ROUNDrounds the same way. - Text casts to an integer only when it spells one:
'1e3'becomes1000and'2.0'becomes2, but'2.5'is an error (NULL inTRY_CAST). - A cast between types that never convert, such as
datetobigint, is an error before the statement runs, inTRY_CASTtoo. - A function argument that takes an integer, such as the count of
LEFT, the positions ofSUBSTRING, or the digits ofROUND, accepts text that an integer cast accepts and whole floating-point numbers. Any other value, such as'2.5'or a fractionalamount + 0.5, gives NULL, or an error when written as a literal.
A precision or length written with the type applies as in PostgreSQL:
numeric(p, s)anddecimal(p, s)round tosdecimal places, with ties away from zero:CAST(1.2345 AS decimal(10, 2))is1.23. A value with more thanp - sdigits before the decimal point is an error inCASTand NULL inTRY_CAST. The result is still double precision, soCAST(12 AS numeric(4, 2))is12, not12.00.varchar(n)keeps the firstncharacters.timestamp(p),timestamptz(p),time(p),timetz(p), andinterval(p)round the seconds topdecimal places.- An interval with fields, such as
interval dayorinterval hour to minute, drops the units below the last field, and reads a number without a unit in the last field:CAST('1' AS interval day)is1 day. char(n)andcharare not supported, because PostgreSQL pads them with spaces. Usevarchar(n)ortext.
These names select the same types:
bigint,integer,intdouble precision,float,real,numeric,decimal,numbertext,varchar,stringbooleandate,time,timestamp,timestamp with time zone,time with time zoneintervaljsonjsonb
Literals
Strings use single quotes. Double a quote to include one ('it''s').
Numbers always use . for the decimal point, whatever the Decimal Separator setting. A whole number is an integer (123), and one outside the 64-bit range is an error. A number with a decimal point or an exponent is floating point (1.5, 1e3). Integers can also be hexadecimal (0x10 is 16), binary (0b10 is 2), or octal (0o10 is 8), and underscores can group digits (1_000, 0xFF_FF).
DATE '2024-03-14'
TIME '15:30:00.123'
TIMETZ '14:30+09:00'
TIMESTAMP '2024-03-14 15:30:00'
INTERVAL '1 day'
INTERVAL '2 weeks'
INTERVAL '1-2' YEAR TO MONTH
INTERVAL '1 02:30' DAY TO MINUTE
TRUE
FALSE
NULL
Dates and times use the forms in Dates and Times.
An interval names its units inside the string, or gives fields after it. The fields are year, month, day, hour, minute, and second. A bare number at the end of the string is in the last field: INTERVAL '1' DAY TO HOUR is one hour, INTERVAL '1 0' DAY TO HOUR is one day, and INTERVAL '1 day 2' DAY TO HOUR is one day and two hours.
Operators
| Operator | Meaning |
|---|---|
=, <>, !=, <, >, <=, >= |
Comparison. Unknown when either side is NULL |
IS NULL, IS NOT NULL |
NULL test |
IS DISTINCT FROM, IS NOT DISTINCT FROM |
Comparison that treats NULL as a value |
AND, OR, NOT |
Boolean combination |
BETWEEN, NOT BETWEEN |
Inclusive range, low bound first |
BETWEEN SYMMETRIC, NOT BETWEEN SYMMETRIC |
Inclusive range, bounds in either order |
IN, NOT IN |
Membership. Each element is compared as with = |
x op ANY (ARRAY[…]), x op ALL (ARRAY[…]) |
Compare x with each listed value using a comparison operator, LIKE, or ILIKE. Write the values in ARRAY[…]; the SQL Console also takes a subquery. SOME is a synonym for ANY |
LIKE, NOT LIKE, ILIKE, NOT ILIKE |
Pattern. % is any text, _ is one character. ESCAPE sets the escape character. LIKE is case-sensitive, and ILIKE ignores case |
SIMILAR TO, NOT SIMILAR TO |
Match the whole text against a SQL pattern, with % and _ wildcards and regular expression constructs such as alternation, groups, and character classes. A period matches a literal period. The escape is a backslash; ESCAPE changes it, and ESCAPE '' turns it off |
~, ~*, !~, !~* |
Regular expression. * ignores case |
|| |
Concatenate both values as text, even when both are numbers. NULL when either side is NULL. With an array, join arrays or add an element. With two jsonb values, merge objects or join arrays |
+, -, *, /, % |
Arithmetic |
:: |
Cast |
arr[i], arr[i][j] |
Array element as text, counting from 1. Supply one index per dimension. A NULL index, an out-of-range index or the wrong number of indices gives NULL. Slices such as arr[1:2] are unsupported |
->, ->> |
JSON field or element. -> returns JSON, ->> returns text |
#> , #>> |
JSON path, written as a text array such as '{address,city}' |
As in PostgreSQL, ||, the regular expression operators, and the JSON operators apply after arithmetic and before comparisons, LIKE, IN, and BETWEEN. 'Total: ' || n * 2 joins the result of n * 2, and a || b = 'ab' compares the joined text. Among themselves they apply left to right, so a pattern built with || needs parentheses: name ~ ('^' || prefix).
CASE WHEN condition THEN result ELSE other END evaluates only the selected result. A string literal in any branch is still read as the result type before the filter or query runs, so CASE WHEN false THEN 'abc' ELSE 1 END is an error.
ANY is true when at least one comparison is true, and ALL is false when at least one is false. Otherwise, if any comparison is unknown, the result is NULL. For an empty array, ANY is false and ALL is true.
With -> and ->>, text looks up an object key and an integer picks an array element. A cell is text, so j -> c looks up the key "1" when c is 1. Write j -> c::bigint to use the cell as a position.
|| with arrays and jsonb follows PostgreSQL: ARRAY[1, 2] || 3 is {1,2,3}, and '{"a": 1}'::jsonb || '{"b": 2}' is {"a": 1, "b": 2}, with a key on the right replacing the same key on the left. A cell is text, so j::jsonb || c joins the text of c; write c::jsonb to merge it. Two json values, or json and jsonb, cannot be joined: cast both sides to jsonb to merge them, or to text to join the text.
Regular Expressions
The regular expression operators and pattern functions use PostgreSQL’s syntax and return PostgreSQL’s results, with these differences:
\band\Bare errors, as PostgreSQL reads them as a backspace and a backslash. For word boundaries, use\y(a boundary),\Y(not a boundary),\mand\M(the start and end of a word), or[[:<:]]and[[:>:]].- Backreferences (
\1), lookahead, and lookbehind are not supported. - When groups could split a match in more than one way, they take the split a backtracking engine tries first.
REGEXP_MATCH('abcd', '(a|ab)(c|bcd)(d*)')returns{a,bcd,""}, where PostgreSQL returns{ab,c,d}. The whole match is the same. - Word boundaries count combining marks as part of a word.
A match starts as early as possible and is the longest one there: REGEXP_SUBSTR('abcd', 'a|ab') returns ab. When the first quantifier in the pattern is lazy, such as *?, it is the shortest one. . matches a newline. \d and [[:digit:]] match only 0 to 9, and \w matches letters, digits of any script, and _. In REGEXP_REPLACE, \1 through \9 insert captures and \& inserts the whole match.
Pattern functions take these flags. A pattern can also start with flags, as in (?i)abc.
icase-insensitive,ccase-sensitivemandn:^and$match at line breaks, and.and[^…]stay within a linep:.and[^…]stay within a lines:.matches a newline (the default)w:^and$match at line breaks, and.matches a newlinexignores whitespace and#comments in the pattern, andtrestores the defaultqtreats the pattern as literal textg, onREGEXP_REPLACEonly with noN, replaces every match
Functions
Function names ignore case.
String functions
| Function | Description |
|---|---|
LENGTH(string), CHAR_LENGTH, CHARACTER_LENGTH |
Number of characters. Numbers are read as text, so LENGTH(42) is 2 |
OCTET_LENGTH(string) |
UTF-8 byte length |
BIT_LENGTH(string) |
UTF-8 byte length times 8 |
LOWER(string), UPPER(string), INITCAP(string) |
LOWER and UPPER use Unicode case mappings regardless of locale. For example, UPPER('straße') returns STRASSE. INITCAP capitalizes each word |
TRIM(string), LTRIM, RTRIM, BTRIM |
Remove spaces, or the characters given as the second argument. TRIM also accepts LEADING, TRAILING, and BOTH |
SUBSTRING(string, start [, length]) |
Characters from start (1-based). SUBSTRING(string FROM start FOR length) is the same. Unlike PostgreSQL, a text start, such as a column, is a position, never a regular expression. For a pattern, use REGEXP_SUBSTR, which returns the whole match rather than the first capture group |
LEFT(string, n), RIGHT(string, n) |
First or last n characters |
CONCAT(value, …) |
Join text, skipping NULL |
CONCAT_WS(separator, value, …) |
Join with a separator, skipping NULL values. A NULL separator returns NULL |
REPLACE(string, from, to) |
Replace each from |
QUOTE_IDENT(string) |
Quote a SQL identifier when needed, including keywords reserved by SmoothCSV. Double any double quotes |
QUOTE_LITERAL(value), QUOTE_NULLABLE(value) |
Quote a SQL literal, escaping quotes and backslashes. For NULL, QUOTE_LITERAL returns SQL NULL and QUOTE_NULLABLE returns the text NULL |
STRPOS(string, substring) |
1-based character position, or 0 |
POSITION(substring IN string) |
Same result as STRPOS |
STARTS_WITH(string, prefix) |
Boolean |
LPAD(string, length [, fill]), RPAD |
Pad to length characters |
REPEAT(string, n) |
Repeat |
REVERSE(string) |
Reverse characters |
SPLIT_PART(string, delimiter, n) |
Field n. 1 is the first field; a negative n counts from the end |
STRING_TO_ARRAY(string, delimiter [, null_string]) |
Split into an array of text. A NULL delimiter splits into characters, and an empty delimiter keeps the string whole. Fields equal to null_string become SQL NULL. An empty input returns {} |
OVERLAY(string PLACING new FROM start [FOR length]) |
Replace a span. start is 1-based |
CHR(code), ASCII(string) |
Character from a code point, and the first character’s code point |
MD5(string) |
MD5 hex digest of the UTF-8 bytes |
UNACCENT(string) |
Remove accents. Letters that are not a base letter plus an accent, such as ø, ł and ß, become the closest base letters (o, l, ss) |
UNISTR(string) |
Interpret Unicode escapes |
TO_HEX(n), TO_BIN(n), TO_OCT(n) |
Integer in that base |
Numeric functions
| Function | Description |
|---|---|
ABS(n) |
Absolute value |
CEIL(n), CEILING(n) |
Round up |
FLOOR(n) |
Round down |
ROUND(n [, digits]) |
Round. Ties away from zero |
TRUNC(n [, digits]) |
Truncate toward zero |
MOD(n, divisor) |
Remainder |
POWER(base, exponent) |
Power |
SQRT(n) |
Square root |
CBRT(n) |
Cube root |
LN(n) |
Natural logarithm |
LOG(n), LOG10(n) |
Base-10 logarithm |
LOG(base, n) |
Logarithm in the given base |
EXP(n) |
Euler’s number raised to the given power |
SIGN(n) |
−1, 0, or 1 according to the sign |
PI() |
π |
DEGREES(radians), RADIANS(degrees) |
Convert between radians and degrees |
SIN(n), COS(n), TAN(n) |
Trigonometric functions with angles in radians |
ASIN(n), ACOS(n), ATAN(n), ATAN2(y, x) |
Inverse trigonometric functions, returning angles in radians |
DIV(n, divisor) |
Quotient truncated toward zero. Two bigint arguments return a bigint and raise an error if the quotient exceeds its range. Other numeric inputs return a double |
GCD(a, b), LCM(a, b) |
Greatest common divisor and least common multiple |
WIDTH_BUCKET(n, start, end, count) |
Index of the equal-width bucket from start toward end. Buckets are numbered from 1. Values before the start return 0. Values at or past the end return count + 1. Three bigint inputs use floating-point boundaries. With fractional inputs, buckets use decimal boundaries, so WIDTH_BUCKET(0.29, 0, 1, 100) returns 30 |
RANDOM() |
A random number from 0 inclusive to 1 exclusive, drawn for each row |
A result that is not a finite number is NULL: SQRT(-1) and POWER(0, -1) are NULL, so SQRT(amount) > 0 does not match a negative amount. The same rule applies to LN(0), ACOS(2), and floating-point overflow. Underflow can produce zero, as in EXP(-1000). Division by zero, including LOG(1, 10), raises an error.
Conditional functions
| Function | Description |
|---|---|
COALESCE(value, …) |
First non-NULL argument |
NULLIF(value, other) |
NULL when the two arguments are equal |
NUM_NULLS(value, …), NUM_NONNULLS(value, …) |
Count the arguments that are SQL NULL or non-NULL, respectively |
GREATEST(value, …), LEAST(value, …) |
Largest or smallest argument, compared as with < and > and ignoring NULL. NULL only when every argument is NULL. GREATEST(amount, 0) compares numbers and returns floating point; GREATEST(amount, '0') compares text |
Pattern functions
See Regular Expressions for the pattern syntax and flags.
| Function | Description |
|---|---|
REGEXP_LIKE(string, pattern [, flags]) |
True when the pattern matches |
REGEXP_SPLIT_TO_ARRAY(string, pattern [, flags]) |
Split at pattern matches and return an array of text. Empty matches at the ends or just after a match are ignored |
LIKE_ESCAPE(pattern, escape) |
Convert a pattern with a custom escape character to one that uses backslashes for LIKE or ILIKE. Pass '' if the input pattern has no escape character |
REGEXP_REPLACE(string, pattern, replacement [, flags]), REGEXP_REPLACE(string, pattern, replacement, start [, N [, flags]]) |
Start at character start (default 1). Replace the first match by default, the Nth match if N is positive, or all matches if N is 0 |
REGEXP_MATCH(string, pattern [, flags]) |
Array of captures, or of the whole match when the pattern has none. NULL when there is no match. (REGEXP_MATCH('a-b', '(a)-(b)'))[2] returns b |
REGEXP_SUBSTR(string, pattern [, start [, occurrence [, flags [, subexpr]]]]) |
The matched text, or NULL when there is no match or capture. Use subexpr 0 for the whole match (default) or 1 and up for a capture group |
REGEXP_COUNT(string, pattern [, start [, flags]]) |
How many matches |
REGEXP_INSTR(string, pattern [, start [, occurrence [, option [, flags [, subexpr]]]]]) |
1-based position, or 0 when there is no match or capture. Use subexpr 0 for the whole match (default) or 1 and up for a capture group. option 0 returns the position where that text starts, and 1 returns the position just after it |
Date and time functions
| Function | Description |
|---|---|
EXTRACT(field FROM value), DATE_PART(field, value) |
A field such as year, quarter, month, day, hour, minute, second, dow, doy, or epoch |
DATE_TRUNC(field, value) |
Truncate to that field |
DATE_BIN(stride, source, origin) |
Start of the bin containing the source timestamp, aligned to the origin. The stride must be positive and contain no months or years |
TIMEZONE(zone, value) |
Same as value AT TIME ZONE zone. See Time Zones |
JUSTIFY_DAYS(interval) |
Convert groups of 30 days to months |
JUSTIFY_HOURS(interval) |
Convert groups of 24 hours to days |
JUSTIFY_INTERVAL(interval) |
Convert hours and days the same way and align the signs of the interval’s fields |
ISFINITE(value) |
Whether a date, timestamp, or interval is finite. All supported values of these types are finite |
AGE(later, earlier), AGE(earlier) |
Interval between the two timestamps. One argument measures from that value to midnight today |
MAKE_DATE(year, month, day) |
Date |
MAKE_TIME(hour, minute, second) |
Time |
MAKE_TIMESTAMP(year, month, mday, hour, min, sec) |
Timestamp |
MAKE_TIMESTAMPTZ(year, month, mday, hour, min, sec [, timezone]) |
Interpret a local timestamp in the supplied zone or the operating system’s zone and return the instant. A signed offset such as '+09:00' counts east of UTC |
MAKE_INTERVAL(years, months, weeks, days, hours, mins, secs) |
Interval. Trailing arguments may be omitted |
TO_CHAR(value, template) |
Format a number, date, time, timestamp, or interval with PostgreSQL’s template patterns. Text is read as a number, so cast a date cell first: TO_CHAR(TRY_CAST(x AS timestamp), 'YYYY'). A number is rounded at the last digit the template shows, half away from zero, as ROUND does: TO_CHAR(0.125, 'FM990.00') is '0.13'. TM gives English names. L (the locale’s currency symbol) is an error; write the symbol in double quotes instead, as in '"$"999' |
TO_NUMBER(text, template) |
Read a number laid out as the template says, one digit for each 9 or 0: TO_NUMBER('12.3', '99') is 12. L is an error, as in TO_CHAR |
TO_DATE(text, template), TO_TIMESTAMP(text, template) |
Parse with a template. TZ reads a time zone abbreviation as AT TIME ZONE does, so IST is an error. TO_TIMESTAMP(seconds) reads Unix seconds |
CURRENT_DATE, CURRENT_TIME, LOCALTIME, LOCALTIMESTAMP, CURRENT_TIMESTAMP, NOW() |
Date or time at the start of execution. See Time Zones |
MAKE_DATE, MAKE_TIMESTAMP, MAKE_TIMESTAMPTZ and MAKE_INTERVAL accept named arguments, as in MAKE_INTERVAL(mins => 5, secs => 30).
JSON functions
| Function | Description |
|---|---|
ARRAY_TO_JSON(arr) |
Convert an SQL array to a JSON array |
JSON_ARRAY_LENGTH(json) |
Elements in a JSON array |
JSON_TYPEOF(json) |
object, array, string, number, boolean, or null |
TO_JSON(value), TO_JSONB(value) |
Convert a value to json or jsonb. Text becomes a JSON string. SQL NULL stays NULL |
JSON_STRIP_NULLS(json) |
Remove object fields with null values at any depth. Keep null array elements |
JSON_BUILD_ARRAY(value, …), JSON_BUILD_OBJECT(key, value, …) |
Build a json array or object |
JSONB_BUILD_ARRAY(value, …), JSONB_BUILD_OBJECT(key, value, …) |
Build a jsonb array or object. For duplicate keys, keep the last value |
JSON_EXTRACT_PATH(json, key, …), JSON_EXTRACT_PATH_TEXT(json, key, …) |
Value at a path, as JSON or as text |
JSON functions and operators that read a JSON document also take jsonb. Convert an SQL array first, as in JSON_ARRAY_LENGTH(TO_JSON(ARRAY[10,20])). JSON indices start at 0. -> and #> return jsonb from jsonb.
Other functions
| Function | Description |
|---|---|
FORMAT(template, value, …) |
FORMAT('%s items', n). %s is text, %I is a quoted identifier, %L is a quoted literal |
GEN_RANDOM_UUID() |
A random version 4 UUID generated for each row as lowercase, hyphenated text |