Skip to main content

PostgreSQL Reference

PostgreSQL Functions

Aggregates

See the official docs for more on all functions in this category. The table immediately below provides you the most commonly used PostgreSQL functions as considred on PostgreSQL Tutorial. Links to these functions take you to the function's reference on the PostgreSQL Tutorial site. Underneath the table below is a reproduction of what currently exists in the Postgres docs in a more palatable form.

FunctionDescription
COUNT()Count the number of rows in a table
AVG()Calculate the average value of a set
SUM()Calculate the sum of a set of values
MAX()Get the maximum value of a set
MIN()Get the minimum value of a set
STRING_AGG()Concatenate strings and place a separator between them
ARRAY_AGGReturn an array from a set of input values

The tables below all come from the Postgres docs.

General-Purpose Aggregate Functions


Syntaxarray_agg ( anynonarray ) → anyarray
DescriptionCollects all the input values, including nulls, into an array.
Partial modeNo


Syntaxarray_agg ( anyarray ) → anyarray
DescriptionConcatenates all the input arrays into an array of one higher dimension. (The inputs must all have the same dimensionality, and cannot be empty or null.)
Partial modeNo


Syntaxavg ( smallint ) → numeric
avg ( integer ) → numeric
avg ( bigint ) → numeric
avg ( numeric ) → numeric
avg ( real ) → double precision
avg ( double precision ) → double precision
avg ( interval ) → interval
DescriptionComputes the average (arithmetic mean) of all the non-null input values.
Partial modeYes


Syntaxbit_and ( smallint ) → smallint
bit_and ( integer ) → integer
bit_and ( bigint ) → bigint
bit_and ( bit ) → bit
DescriptionComputes the bitwise AND of all non-null input values.
Partial modeYes


Syntaxbit_or ( smallint ) → smallint
bit_or ( integer ) → integer
bit_or ( bigint ) → bigint
bit_or ( bit ) → bit
DescriptionComputes the bitwise OR of all non-null input values.
Partial modeYes


Syntaxbool_and ( boolean ) → boolean
DescriptionReturns true if all non-null input values are true, otherwise false.
Partial modeYes


Syntaxbool_or ( boolean ) → boolean
DescriptionReturns true if any non-null input value is true, otherwise false.
Partial modeYes


Syntaxcount ( * ) → bigint
DescriptionComputes the number of input rows.
Partial modeYes


Syntaxcount ( "any" ) → bigint
DescriptionComputes the number of input rows in which the input value is not null.
Partial modeYes


Syntaxevery ( boolean ) → boolean
DescriptionThis is the SQL standard's equivalent to bool_and.
Partial modeYes


Syntaxjson_agg ( anyelement ) → json
jsonb_agg ( anyelement ) → jsonb
DescriptionCollects all the input values, including nulls, into a JSON array. Values are converted to JSON as per to_json or to_jsonb.
Partial modeNo


Syntaxjson_object_agg ( key "any", value "any" ) → json
jsonb_object_agg ( key "any", value "any" ) → jsonb
DescriptionCollects all the key/value pairs into a JSON object. Key arguments are coerced to text; value arguments are converted as per to_json or to_jsonb. Values can be null, but not keys.
Partial modeNo


Syntaxmax ( see text ) → same as input type
DescriptionComputes the maximum of the non-null input values. Available for any numeric, string, date/time, or enum type, as well as inet, interval, money, oid, pg_lsn, tid, and arrays of any of these types.
Partial modeYes


Syntaxmin ( see text ) → same as input type
DescriptionComputes the minimum of the non-null input values. Available for any numeric, string, date/time, or enum type, as well as inet, interval, money, oid, pg_lsn, tid, and arrays of any of these types.
Partial modeYes


Syntaxstring_agg ( value text, delimiter text ) → text
string_agg ( value bytea, delimiter bytea ) → bytea
DescriptionConcatenates the non-null input values into a string. Each value after the first is preceded by the corresponding delimiter (if it's not null).
Partial modeNo


Syntaxsum ( smallint ) → bigint
sum ( integer ) → bigint
sum ( bigint ) → numeric
sum ( numeric ) → numeric
sum ( real ) → real
sum ( double precision ) → double precision
sum ( interval ) → interval
sum ( money ) → money
DescriptionComputes the sum of the non-null input values.
Partial modeYes


Syntaxxmlagg ( xml ) → xml
DescriptionConcatenates the non-null XML input values (see Section 9.15.1.7).
Partial modeNo

Aggregate Functions for Statistics


Syntaxcorr ( Y double precision, X double precision ) → double precision
DescriptionComputes the correlation coefficient.
Partial modeYes


Syntaxcovar_pop ( Y double precision, X double precision ) → double precision
DescriptionComputes the population covariance.
Partial modeYes


Syntaxcovar_samp ( Y double precision, X double precision ) → double precision
DescriptionComputes the sample covariance.
Partial modeYes


Syntaxregr_avgx ( Y double precision, X double precision ) → double precision
DescriptionComputes the average of the independent variable, sum(X)/N.
Partial modeYes


Syntaxregr_avgy ( Y double precision, X double precision ) → double precision
DescriptionComputes the average of the dependent variable, sum(Y)/N.
Partial modeYes


Syntaxregr_count ( Y double precision, X double precision ) → double precision
DescriptionComputes the number of rows in which both inputs are non-null.
Partial modeYes


Syntaxregr_intercept ( Y double precision, X double precision ) → double precision
DescriptionComputes the y-intercept of the least-squares-fit linear equation determined by the (X, Y) pairs.
Partial modeYes


Syntaxregr_r2 ( Y double precision, X double precision ) → double precision
DescriptionComputes the square of the correlation coefficient.
Partial modeYes


Syntaxregr_slope ( Y double precision, X double precision ) → double precision
DescriptionComputes the slope of the least-squares-fit linear equation determined by the (X, Y) pairs.
Partial modeYes


Syntaxregr_sxx ( Y double precision, X double precision ) → double precision
DescriptionComputes the "sum of squares" of the independent variable, sum(X^2) - sum(X)^2/N.
Partial modeYes


Syntaxregr_sxy ( Y double precision, X double precision ) → double precision
DescriptionComputes the "sum of products" of independent times dependent variables, sum(X*Y) - sum(X) * sum(Y)/N.
Partial modeYes


Syntaxregr_syy ( Y double precision, X double precision ) → double precision
DescriptionComputes the "sum of squares" of the dependent variable, sum(Y^2) - sum(Y)^2/N.
Partial modeYes


Syntaxstddev ( numeric_type ) → double precision for real or double precision, otherwise numeric
DescriptionThis is a historical alias for stddev_samp.
Partial modeYes


Syntaxstddev_pop ( numeric_type ) → double precision for real or double precision, otherwise numeric
DescriptionComputes the population standard deviation of the input values.
Partial modeYes


Syntaxstddev_samp ( numeric_type ) → double precision for real or double precision, otherwise numeric
DescriptionComputes the sample standard deviation of the input values.
Partial modeYes


Syntaxvariance ( numeric_type ) → double precision for real or double precision, otherwise numeric
DescriptionThis is a historical alias for var_samp.
Partial modeYes


Syntaxvar_pop ( numeric_type ) → double precision for real or double precision, otherwise numeric
DescriptionComputes the population variance of the input values (square of the population standard deviation).
Partial modeYes


Syntaxvar_samp ( numeric_type ) → double precision for real or double precision, otherwise numeric
DescriptionComputes the sample variance of the input values (square of the sample standard deviation).
Partial modeYes

Ordered-Set Aggregate Functions


Syntaxmode () WITHIN GROUP ( ORDER BY anyelement ) → anyelement
DescriptionComputes the mode, the most frequent value of the aggregated argument (arbitrarily choosing the first one if there are multiple equally-frequent values). The aggregated argument must be of a sortable type.
Partial modeNo


Syntaxpercentile_cont ( fraction double precision ) WITHIN GROUP ( ORDER BY double precision ) → double precision
percentile_cont ( fraction double precision ) WITHIN GROUP ( ORDER BY interval ) → interval
DescriptionComputes the continuous percentile, a value corresponding to the specified fraction within the ordered set of aggregated argument values. This will interpolate between adjacent input items if needed.
Partial modeNo


Syntaxpercentile_cont ( fractions double precision[] ) WITHIN GROUP ( ORDER BY double precision ) → double precision[]
percentile_cont ( fractions double precision[] ) WITHIN GROUP ( ORDER BY interval ) → interval[]
DescriptionComputes multiple continuous percentiles. The result is an array of the same dimensions as the fractions parameter, with each non-null element replaced by the (possibly interpolated) value corresponding to that percentile.
Partial modeNo


Syntaxpercentile_disc ( fraction double precision ) WITHIN GROUP ( ORDER BY anyelement ) → anyelement
DescriptionComputes the discrete percentile, the first value within the ordered set of aggregated argument values whose position in the ordering equals or exceeds the specified fraction. The aggregated argument must be of a sortable type.
Partial modeNo


Syntaxpercentile_disc ( fractions double precision[] ) WITHIN GROUP ( ORDER BY anyelement ) → anyarray
DescriptionComputes multiple discrete percentiles. The result is an array of the same dimensions as the fractions parameter, with each non-null element replaced by the input value corresponding to that percentile. The aggregated argument must be of a sortable type.
Partial modeNo

Hypothetical-Set Aggregate Functions


Syntaxrank ( args ) WITHIN GROUP ( ORDER BY sorted_args ) → bigint
DescriptionComputes the rank of the hypothetical row, with gaps; that is, the row number of the first row in its peer group.
Partial modeNo


Syntaxdense_rank ( args ) WITHIN GROUP ( ORDER BY sorted_args ) → bigint
DescriptionComputes the rank of the hypothetical row, without gaps; this function effectively counts peer groups.
Partial modeNo


Syntaxpercent_rank ( args ) WITHIN GROUP ( ORDER BY sorted_args ) → double precision
DescriptionComputes the relative rank of the hypothetical row, that is (rank - 1) / (total rows - 1). The value thus ranges from 0 to 1 inclusive.
Partial modeNo


Syntaxcume_dist ( args ) WITHIN GROUP ( ORDER BY sorted_args ) → double precision
DescriptionComputes the cumulative distribution, that is (number of rows preceding or peers with hypothetical row) / (total rows). The value thus ranges from 1/N to 1.
Partial modeNo

Grouping Operations


SyntaxGROUPING ( group_by_expression(s) ) → integer
DescriptionReturns a bit mask indicating which GROUP BY expressions are not included in the current grouping set. Bits are assigned with the rightmost argument corresponding to the least-significant bit; each bit is 0 if the corresponding expression is included in the grouping criteria of the grouping set generating the current result row, and 1 if it is not included.

Strings

See the official docs for more on all functions in this category. The table immediately below provides you the most commonly used PostgreSQL functions as considred on PostgreSQL Tutorial. Links to these functions take you to the function's reference on the PostgreSQL Tutorial site. Underneath the table below is a reproduction of what currently exists in the Postgres docs in a more palatable form.

Function
Description
Example
Result
ASCIIReturn the ASCII code value of a character or Unicode code point of a UTF8 characterASCII('A')65
CHRConvert an ASCII code to a character or a Unicode code point to a UTF8 characterCHR(65)'A'
CONCATConcatenate two or more strings into oneCONCAT('A','B','C')'ABC'
CONCAT_WSConcatenate strings with a separatorCONCAT_WS(',','A','B','C')'A,B,C'
FORMATFormat arguments based on a format stringFORMAT('Hello %s','PostgreSQL')'Hello PostgreSQL'
INITCAPConvert words in a string to title caseINITCAP('hI tHERE')Hi There
LEFTReturn the first n character in a stringLEFT('ABC',1)'A'
LENGTHReturn the number of characters in a stringLENGTH('ABC')3
LOWERConvert a string to lowercaseLOWER('hI tHERE')'hi there'
LPADPad on the left a a string with a character to a certain lengthLPAD('123′, 5, '00')'00123'
LTRIMRemove the longest string that contains specified characters from the left of the input stringLTRIM('00123')'123'
MD5Return MD5 hash of a string in hexadecimalMD5('PostgreSQL MD5')f78fdb18bf39b23d42313edfaf7e0a44
POSITIONReturn the location of a substring in a stringPOSTION('B' in 'A B C')3
REGEXP_MATCHESMatch a POSIX regular expression against a string and returns the matching substringsSELECT REGEXP_MATCHES('ABC', '^(A)(..)$', 'g');{A,BC}
REGEXP_REPLACEReplace substrings that match a POSIX regular expression by a new substringREGEXP_REPLACE('John Doe','(.*) (.*)','\2, \1′);'Doe, John'
REPEATRepeat string the specified number of timesREPEAT('*', 5)'*****'
REPLACEReplace all occurrences in a string of substring from with substring toREPLACE('ABC','B','A')'AAC'
REVERSEReturn reversed stringREVERSE('ABC')'CBA'
RIGHTReturn last n characters in the string. When n is negative, return all but first `n` characters
RPADPad on the right of a string with a character to a certain lengthRPAD('ABC', 6, 'xo')'ABCxox'
RTRIMRemove the longest string that contains specified characters from the right of the input stringRTRIM('abcxxzx', 'xyz')'abc'
SPLIT_PARTSplit a string on a specified delimiter and return nth substringSPLIT_PART('2017-12-31′,'-',2)'12'
SUBSTRINGExtract a substring from a stringSUBSTRING('ABC',1,1)'A'
TRIMRemove the longest string that contains specified characters from the left, right or both of the input stringTRIM(' ABC ')'ABC'
UPPERConvert a string to uppercaseUPPER('hI tHERE')'HI THERE'
TO_CHARConverts a timestamp, an interval, an integer, a double precision, or a numeric value to a stringTO_CHAR(TIMESTAMP '2017-08-18 22:30:59', 'HH24:MI:SS')22:30:59
TO_NUMBERConverts a character string to a numeric valueTO_NUMBER('12,345.6-', '99G999D9S')-12345.6

What currently exists in the Postgres docs is listed below.

SQL String Functions and Operators


Syntaxtext || text → text
DescriptionConcatenates the two strings..
Example(s)'Post' || 'greSQL' → PostgreSQL


Syntaxtext || anynonarray → text
anynonarray || text → text
DescriptionConverts the non-string input to text, then concatenates the two strings. (The non-string input cannot be of an array type, because that would create ambiguity with the array || operators. If you want to concatenate an array's text equivalent, cast it to text explicitly.).
Example(s)'Value: ' || 42 → Value: 42


Syntaxtext IS [NOT] [form] NORMALIZED → boolean
DescriptionChecks whether the string is in the specified Unicode normalization form. The optional form key word specifies the form: NFC (the default), NFD, NFKC, or NFKD. This expression can only be used when the server encoding is UTF8. Note that checking for normalization using this expression is often faster than normalizing possibly already normalized strings.
Example(s)actualExamples


Syntaxbit_length ( text ) → integer
DescriptionReturns number of bits in the string (8 times the octet_length)
Example(s)bit_length('jose') → 32


Syntaxchar_length ( text ) → integer
character_length ( text ) → integer
DescriptionReturns number of characters in the string
Example(s)char_length('josé') → 4


Syntaxlower ( text ) → text
DescriptionConverts the string to all lower case, according to the rules of the database's locale
Example(s)lower('TOM') → tom


Syntaxnormalize ( text [, form ] ) → text
DescriptionConverts the string to the specified Unicode normalization form. The optional form key word specifies the form: NFC (the default), NFD, NFKC, or NFKD. This function can only be used when the server encoding is UTF8.
Example(s)normalize(U&'\0061\0308bc', NFC) → U&'\00E4bc'


Syntaxoctet_length ( text ) → integer
DescriptionReturns number of bytes in the string
Example(s)octet_length('josé') → 5 (if server encoding is UTF8)


Syntaxoctet_length ( character ) → integer
DescriptionReturns number of bytes in the string. Since this version of the function accepts type character directly, it will not strip trailing spaces
Example(s)octet_length('abc '::character(4)) → 4


Syntaxoverlay ( string text PLACING newsubstring text FROM start integer [ FOR count integer ] ) → text
DescriptionReplaces the substring of string that starts at the start'th character and extends for count characters with newsubstring. If count is omitted, it defaults to the length of newsubstring.
Example(s)overlay('Txxxxas' placing 'hom' from 2 for 4) → Thomas


Syntaxposition ( substring text IN string text ) → integer
DescriptionReturns starting index of specified substring within string, or zero if it's not present.
Example(s)position('om' in 'Thomas') → 3


Syntaxsubstring ( string text [ FROM start integer ] [ FOR count integer ] ) → text
DescriptionExtracts the substring of string starting at the start'th character if that is specified, and stopping after count characters if that is specified. Provide at least one of start and count.
Example(s)substring('Thomas' from 2 for 3) → hom
substring('Thomas' from 3) → omas
substring('Thomas' for 2) → Th


Syntaxsubstring ( string text FROM pattern text ) → text
DescriptionExtracts substring matching POSIX regular expression; see Section 9.7.3
Example(s)substring('Thomas' from '...$') → mas


Syntaxsubstring ( string text FROM pattern text FOR escape text ) → text
DescriptionExtracts substring matching SQL regular expression; see Section 9.7.2
Example(s)substring('Thomas' from '%#"o_a#"_' for '#') → oma


Syntaxtrim ( [ LEADING | TRAILING | BOTH ] [ characters text ] FROM string text ) → text
DescriptionRemoves the longest string containing only characters in characters (a space by default) from the start, end, or both ends (BOTH is the default) of string.
Example(s)trim(both 'xyz' from 'yxTomxx') → Tom


Syntaxtrim ( [ LEADING | TRAILING | BOTH ] [ FROM ] string text [, characters text ] ) → text
DescriptionThis is a non-standard syntax for trim().
Example(s)trim(both from 'yxTomxx', 'xyz') → Tom


Syntaxupper ( text ) → text
DescriptionConverts the string to all upper case, according to the rules of the database's locale.
Example(s)upper('tom') → TOM

Other String Functions

Additional string manipulation functions are available and are listed in the table below. Some of them are used internally to implement the SQL-standard string functions listed in the table above.


Syntaxascii ( text ) → integer
DescriptionReturns the numeric code of the first character of the argument. In UTF8 encoding, returns the Unicode code point of the character. In other multibyte encodings, the argument must be an ASCII character.
Example(s)ascii('x') → 120


Syntaxbtrim ( string text [, characters text ] ) → text
DescriptionRemoves the longest string containing only characters in characters (a space by default) from the start and end of string.
Example(s)btrim('xyxtrimyyx', 'xyz') → trim


Syntaxchr ( integer ) → text
DescriptionReturns the character with the given code. In UTF8 encoding the argument is treated as a Unicode code point. In other multibyte encodings the argument must designate an ASCII character. chr(0) is disallowed because text data types cannot store that character.
Example(s)chr(65) → A


Syntaxconcat ( val1 "any" [, val2 "any" [, ...] ] ) → text
DescriptionConcatenates the text representations of all the arguments. NULL arguments are ignored.
Example(s)concat('abcde', 2, NULL, 22) → abcde222


Syntaxconcat_ws ( sep text, val1 "any" [, val2 "any" [, ...] ] ) → text
DescriptionConcatenates all but the first argument, with separators. The first argument is used as the separator string, and should not be NULL. Other NULL arguments are ignored.
Example(s)concat_ws(',', 'abcde', 2, NULL, 22) → abcde,2,22


Syntaxformat ( formatstr text [, formatarg "any" [, ...] ] ) → text
DescriptionFormats arguments according to a format string; see Section 9.4.1. This function is similar to the C function sprintf.


Syntaxinitcap ( text ) → text
DescriptionConverts the first letter of each word to upper case and the rest to lower case. Words are sequences of alphanumeric characters separated by non-alphanumeric characters.
Example(s)initcap('hi THOMAS') → Hi Thomas


Syntaxleft ( string text, n integer ) → text
DescriptionReturns first n characters in the string, or when n is negative, returns all but last |n| characters.
Example(s)left('abcde', 2) → ab


Syntaxlength ( text ) → integer
DescriptionReturns the number of characters in the string.
Example(s)length('jose') → 4


Syntaxlpad ( string text, length integer [, fill text ] ) → text
DescriptionExtends the string to length length by prepending the characters fill (a space by default). If the string is already longer than length then it is truncated (on the right).
Example(s)lpad('hi', 5, 'xy') → xyxhi


Syntaxltrim ( string text [, characters text ] ) → text
DescriptionRemoves the longest string containing only characters in characters (a space by default) from the start of string.
Example(s)ltrim('zzzytest', 'xyz') → test


Syntaxmd5 ( text ) → text
DescriptionComputes the MD5 hash of the argument, with the result written in hexadecimal.
Example(s)md5('abc') → 900150983cd24fb0​d6963f7d28e17f72


Syntaxparse_ident ( qualified_identifier text [, strict_mode boolean DEFAULT true ] ) → text[]
DescriptionSplits qualified_identifier into an array of identifiers, removing any quoting of individual identifiers. By default, extra characters after the last identifier are considered an error; but if the second parameter is false, then such extra characters are ignored. (This behavior is useful for parsing names for objects like functions.) Note that this function does not truncate over-length identifiers. If you want truncation you can cast the result to name[].


Syntaxpg_client_encoding ( ) → name
DescriptionReturns current client encoding name.
Example(s)pg_client_encoding() → UTF8


Syntaxquote_ident ( text ) → text
DescriptionReturns the given string suitably quoted to be used as an identifier in an SQL statement string. Quotes are added only if necessary (i.e., if the string contains non-identifier characters or would be case-folded). Embedded quotes are properly doubled. See also Example 42.1.


Syntaxquote_literal ( text ) → text
DescriptionReturns the given string suitably quoted to be used as a string literal in an SQL statement string. Embedded single-quotes and backslashes are properly doubled. Note that quote_literal returns null on null input; if the argument might be null, quote_nullable is often more suitable. See also Example 42.1.
Example(s)quote_literal(E'O\'Reilly') → 'O''Reilly'


Syntaxquote_literal ( anyelement ) → text
DescriptionConverts the given value to text and then quotes it as a literal. Embedded single-quotes and backslashes are properly doubled.
Example(s)quote_literal(42.5) → '42.5'


Syntaxquote_nullable ( text ) → text
DescriptionReturns the given string suitably quoted to be used as a string literal in an SQL statement string; or, if the argument is null, returns NULL. Embedded single-quotes and backslashes are properly doubled. See also Example 42.1.
Example(s)quote_nullable(NULL) → NULL


Syntaxquote_nullable ( anyelement ) → text
DescriptionConverts the given value to text and then quotes it as a literal; or, if the argument is null, returns NULL. Embedded single-quotes and backslashes are properly doubled.
Example(s)quote_nullable(42.5) → '42.5'


Syntaxregexp_match ( string text, pattern text [, flags text ] ) → text[]
DescriptionReturns captured substring(s) resulting from the first match of a POSIX regular expression to the string; see Section 9.7.3.


Syntaxregexp_matches ( string text, pattern text [, flags text ] ) → setof text[]
DescriptionReturns captured substring(s) resulting from matching a POSIX regular expression to the string; see Section 9.7.3.


Syntaxregexp_replace ( string text, pattern text, replacement text [, flags text ] ) → text
DescriptionReplaces substring(s) matching a POSIX regular expression; see Section 9.7.3.
Example(s)regexp_replace('Thomas', '.[mN]a.', 'M') → ThM


Syntaxregexp_split_to_array ( string text, pattern text [, flags text ] ) → text[]
DescriptionSplits string using a POSIX regular expression as the delimiter; see Section 9.7.3.


Syntaxregexp_split_to_table ( string text, pattern text [, flags text ] ) → setof text
DescriptionSplits string using a POSIX regular expression as the delimiter; see Section 9.7.3.
Example(s)regexp_split_to_table('hello world', '\s+') → hello world


Syntaxrepeat ( string text, number integer ) → text
DescriptionRepeats string the specified number of times.
Example(s)repeat('Pg', 4) → PgPgPgPg


Syntaxreplace ( string text, from text, to text ) → text
DescriptionReplaces all occurrences in string of substring from with substring to.
Example(s)replace('abcdefabcdef', 'cd', 'XX') → abXXefabXXef


Syntaxreverse ( text ) → text
DescriptionReverses the order of the characters in the string.
Example(s)reverse('abcde') → edcba


Syntaxright ( string text, n integer ) → text
DescriptionReturns last n characters in the string, or when n is negative, returns all but first |n| characters.
Example(s)right('abcde', 2) → de


Syntaxrpad ( string text, length integer [, fill text ] ) → text
DescriptionExtends the string to length length by appending the characters fill (a space by default). If the string is already longer than length then it is truncated.
Example(s)rpad('hi', 5, 'xy') → hixyx


Syntaxrtrim ( string text [, characters text ] ) → text
DescriptionRemoves the longest string containing only characters in characters (a space by default) from the end of string.
Example(s)rtrim('testxxzx', 'xyz') → test


Syntaxsplit_part ( string text, delimiter text, n integer ) → text
DescriptionSplits string at occurrences of delimiter and returns the n'th field (counting from one).
Example(s)split_part('abc~@~def~@~ghi', '~@~', 2) → def


Syntaxstrpos ( string text, substring text ) → integer
DescriptionReturns starting index of specified substring within string, or zero if it's not present. (Same as position(substring in string), but note the reversed argument order.)
Example(s)strpos('high', 'ig') → 2


Syntaxsubstr ( string text, start integer [, count integer ] ) → text
DescriptionExtracts the substring of string starting at the start'th character, and extending for count characters if that is specified. (Same as substring(string from start for count).)
Example(s)substr('alphabet', 3) → phabet
substr('alphabet', 3, 2) → ph


Syntaxstarts_with ( string text, prefix text ) → boolean
DescriptionReturns true if string starts with prefix.
Example(s)starts_with('alphabet', 'alph') → t


Syntaxto_ascii ( string text ) → text
to_ascii ( string text, encoding name ) → text
to_ascii ( string text, encoding integer ) → text
DescriptionConverts string to ASCII from another encoding, which may be identified by name or number. If encoding is omitted the database encoding is assumed (which in practice is the only useful case). The conversion consists primarily of dropping accents. Conversion is only supported from LATIN1, LATIN2, LATIN9, and WIN1250 encodings. (See the unaccent module for another, more flexible solution.)
Example(s)to_ascii('Karél') → Karel


Syntaxto_hex ( integer ) → text
to_hex ( bigint ) → text
DescriptionConverts the number to its equivalent hexadecimal representation.
Example(s)to_hex(2147483647) → 7fffffff


Syntaxtranslate ( string text, from text, to text ) → text
DescriptionReplaces each character in string that matches a character in the from set with the corresponding character in the to set. If from is longer than to, occurrences of the extra characters in from are deleted.
Example(s)translate('12345', '143', 'ax') → a2x5

Math

See the official docs for more on all functions in this category. The table immediately below provides you the most commonly used PostgreSQL functions as considred on PostgreSQL Tutorial. Links to these functions take you to the function's reference on the PostgreSQL Tutorial site. Underneath the table below is a reproduction of what currently exists in the Postgres docs in a more palatable form.

Function
Description
ExampleResult
ABSCalculate the absolute value of a numberABS(-10)10
CBRTCalculate the cube root of a numberCBRT(8)2
CEILRound a number up to the nearest integer, which is greater than or equal to numberCEIL(-12.8)-12
CEILINGSame as CEILexampleresult
DEGREESConvert radians to degreesDEGREES(0.8)45.83662361
DIVReturn the integer quotient of two numeric valuesDIV(8,3)2
EXPReturn the exponential value in scientific notation of a numberEXP(1)2.718281828
FLOORRound a number down to the nearest integer, which is less than or equal to numberFLOOR(10.6)10
LNReturn the natural logarithm of a numeric valueLN(3)1.098612289
LOGReturn the base 10 logarithm of a numeric valueLOG(1000)3
LOGReturn the logarithm of a numeric value to a specified baseLOG(2, 64)6
MODDivide the first parameter by the second one and return the remainderMOD(10,4)1
PIReturn the value of PIPI()3.141592654
POWERRaise a numeric value to the power of a second numeric valuePOWER(5, 3)125
RADIANSConvert degrees to radiansRADIANS(60)1.047197551
ROUNDRound a number to the nearest integer or to a specified decimal placesROUND(10.3)10
SCALEReturn the number of decimal digits in the fractional partSCALE(1.234)3
SIGNReturn the sign (positive, negative) of a numeric valueSIGN(-1)-1
SQRTReturn the square root of a numeric valueSQRT(3.0)1.732050808
TRUNCTruncate a numeric value to a whole number of to the specified decimal placesTRUNC(12.3)12
WIDTH_BUCKETAssign values to buckets in an equi-width histogram
RANDOMReturn a random number that ranges from 0 to 10.968435665

All tables below appear in the official Postgres docs.

Mathematical Operators


Syntaxnumeric_type + numeric_type → numeric_type
DescriptionAddition
Example(s)2 + 3 → 5


Syntax+ numeric_type → numeric_type
DescriptionUnary plus (no operation)
Example(s)+ 3.5 → 3.5


Syntaxnumeric_type - numeric_type → numeric_type
DescriptionSubtraction
Example(s)2 - 3 → -1


Syntax- numeric_type → numeric_type
DescriptionNegation
Example(s)- (-4) → 4


Syntaxnumeric_type * numeric_type → numeric_type
DescriptionMultiplication
Example(s)2 * 3 → 6


Syntaxnumeric_type / numeric_type → numeric_type
DescriptionDivision (for integral types, division truncates the result towards zero)
Example(s)5.0 / 2 → 2.5000000000000000
5 / 2 → 2
(-5) / 2 → -2


Syntaxnumeric_type % numeric_type → numeric_type
DescriptionModulo (remainder); available for smallint, integer, bigint, and numeric
Example(s)5 % 4 → 1


Syntaxnumeric ^ numeric → numeric
double precision ^ double precision → double precision
DescriptionExponentiation (unlike typical mathematical practice, multiple uses of ^ will associate left to right)
Example(s)2 ^ 3 → 8
2 ^ 3 ^ 3 → 512


Syntax|/ double precision → double precision
DescriptionSquare root
Example(s)|/ 25.0 → 5


Syntax||/ double precision → double precision
DescriptionCube root
Example(s)||/ 64.0 → 4


Syntaxbigint ! → numeric
DescriptionFactorial (deprecated, use factorial() instead)
Example(s)5 ! → 120


Syntax!! bigint → numeric
DescriptionFactorial as a prefix operator (deprecated, use factorial() instead)
Example(s)!! 5 → 120


Syntax@ numeric_type → numeric_type
DescriptionAbsolute value
Example(s)@ -5.0 → 5


Syntaxintegral_type & integral_type → integral_type
DescriptionBitwise AND
Example(s)91 & 15 → 11


Syntaxintegral_type | integral_type → integral_type
DescriptionBitwise OR
Example(s)32 | 3 → 35


Syntaxintegral_type # integral_type → integral_type
DescriptionBitwise exclusive OR
Example(s)17 # 5 → 20


Syntax~ integral_type → integral_type
DescriptionBitwise NOT
Example(s)~1 → -2


Syntaxintegral_type << integer → integral_type
DescriptionBitwise shift left
Example(s)1 << 4 → 16


Syntaxintegral_type >> integer → integral_type
DescriptionBitwise shift right
Example(s)8 >> 2 → 2

Mathematical Functions


Syntaxabs ( numeric_type ) → numeric_type
DescriptionAbsolute value
Example(s)abs(-17.4) → 17.4


Syntaxcbrt ( double precision ) → double precision
DescriptionCube root
Example(s)cbrt(64.0) → 4


Syntaxceil ( numeric ) → numeric
ceil ( double precision ) → double precision
DescriptionNearest integer greater than or equal to argument
Example(s)ceil(42.2) → 43
ceil(-42.8) → -42


Syntaxceiling ( numeric ) → numeric
ceiling ( double precision ) → double precision
DescriptionNearest integer greater than or equal to argument (same as ceil)
Example(s)ceiling(95.3) → 96


Syntaxdegrees ( double precision ) → double precision
DescriptionConverts radians to degrees
Example(s)degrees(0.5) → 28.64788975654116


Syntaxdiv ( y numeric, x numeric ) → numeric
DescriptionInteger quotient of y/x (truncates towards zero)
Example(s)div(9,4) → 2


Syntaxexp ( numeric ) → numeric
exp ( double precision ) → double precision
DescriptionExponential (e raised to the given power)
Example(s)exp(1.0) → 2.7182818284590452


Syntaxfactorial ( bigint ) → numeric
DescriptionFactorial
Example(s)factorial(5) → 120


Syntaxfloor ( numeric ) → numeric
floor ( double precision ) → double precision
DescriptionNearest integer less than or equal to argument
Example(s)floor(42.8) → 42
floor(-42.8) → -43


Syntaxgcd ( numeric_type, numeric_type ) → numeric_type
DescriptionGreatest common divisor (the largest positive number that divides both inputs with no remainder); returns 0 if both inputs are zero; available for integer, bigint, and numeric
Example(s)gcd(1071, 462) → 21


Syntaxlcm ( numeric_type, numeric_type ) → numeric_type
DescriptionLeast common multiple (the smallest strictly positive number that is an integral multiple of both inputs); returns 0 if either input is zero; available for integer, bigint, and numeric
Example(s)lcm(1071, 462) → 23562


Syntaxln ( numeric ) → numeric
ln ( double precision ) → double precision
DescriptionNatural logarithm
Example(s)ln(2.0) → 0.6931471805599453


Syntaxlog ( numeric ) → numeric
log ( double precision ) → double precision
DescriptionBase 10 logarithm
Example(s)log(100) → 2


Syntaxlog10 ( numeric ) → numeric
log10 ( double precision ) → double precision
DescriptionBase 10 logarithm (same as log)
Example(s)log10(1000) → 3


Syntaxlog ( b numeric, x numeric ) → numeric
DescriptionLogarithm of x to base b
Example(s)log(2.0, 64.0) → 6.0000000000


Syntaxmin_scale ( numeric ) → integer
DescriptionMinimum scale (number of fractional decimal digits) needed to represent the supplied value precisely
Example(s)min_scale(8.4100) → 2


Syntaxmod ( y numeric_type, x numeric_type ) → numeric_type
DescriptionRemainder of y/x; available for smallint, integer, bigint, and numeric
Example(s)mod(9,4) → 1


Syntaxpi ( ) → double precision
DescriptionApproximate value of π
Example(s)pi() → 3.141592653589793


Syntaxpower ( a numeric, b numeric ) → numeric
power ( a double precision, b double precision ) → double precision
Descriptiona raised to the power of b
Example(s)power(9, 3) → 729


Syntaxradians ( double precision ) → double precision
DescriptionConverts degrees to radians
Example(s)radians(45.0) → 0.7853981633974483


Syntaxround ( numeric ) → numeric
round ( double precision ) → double precision
DescriptionRounds to nearest integer
Example(s)round(42.4) → 42


Syntaxround ( v numeric, s integer ) → numeric
DescriptionRounds v to s decimal places
Example(s)round(42.4382, 2) → 42.44


Syntaxscale ( numeric ) → integer
DescriptionScale of the argument (the number of decimal digits in the fractional part)
Example(s)scale(8.4100) → 4


Syntaxsign ( numeric ) → numeric
sign ( double precision ) → double precision
DescriptionSign of the argument (-1, 0, or +1)
Example(s)sign(-8.4) → -1


Syntaxsqrt ( numeric ) → numeric
sqrt ( double precision ) → double precision
DescriptionSquare root
Example(s)sqrt(2) → 1.4142135623730951


Syntaxtrim_scale ( numeric ) → numeric
DescriptionReduces the value's scale (number of fractional decimal digits) by removing trailing zeroes
Example(s)trim_scale(8.4100) → 8.41


Syntaxtrunc ( numeric ) → numeric
trunc ( double precision ) → double precision
DescriptionTruncates to integer (towards zero)
Example(s)trunc(42.8) → 42
trunc(-42.8) → -42


Syntaxtrunc ( v numeric, s integer ) → numeric
DescriptionTruncates v to s decimal places
Example(s)trunc(42.4382, 2) → 42.43


Syntaxwidth_bucket ( operand numeric, low numeric, high numeric, count integer ) → integer
width_bucket ( operand double precision, low double precision, high double precision, count integer ) → integer
DescriptionReturns the number of the bucket in which operand falls in a histogram having count equal-width buckets spanning the range low to high. Returns 0 or count+1 for an input outside that range.
Example(s)width_bucket(5.35, 0.024, 10.06, 5) → 3


Syntaxwidth_bucket ( operand anyelement, thresholds anyarray ) → integer
DescriptionReturns the number of the bucket in which operand falls given an array listing the lower bounds of the buckets. Returns 0 for an input less than the first lower bound. operand and the array elements can be of any type having standard comparison operators. The thresholds array must be sorted, smallest first, or unexpected results will be obtained.
Example(s)width_bucket(now(), array['yesterday', 'today', 'tomorrow']::timestamptz[]) → 2

Random Functions


Syntaxrandom ( ) → double precision
DescriptionReturns a random value in the range 0.0 <= x < 1.0
Example(s)random() → 0.897124072839091


Syntaxsetseed ( double precision ) → void
DescriptionSets the seed for subsequent random() calls; argument must be between -1.0 and 1.0, inclusive
Example(s)setseed(0.12345)

Trigonometric Functions


Syntaxacos ( double precision ) → double precision
DescriptionInverse cosine, result in radians
Example(s)acos(1) → 0


Syntaxacosd ( double precision ) → double precision
DescriptionInverse cosine, result in degrees
Example(s)acosd(0.5) → 60


Syntaxasin ( double precision ) → double precision
DescriptionInverse sine, result in radians
Example(s)asin(1) → 1.5707963267948966


Syntaxasind ( double precision ) → double precision
DescriptionInverse sine, result in degrees
Example(s)asind(0.5) → 30


Syntaxatan ( double precision ) → double precision
DescriptionInverse tangent, result in radians
Example(s)atan(1) → 0.7853981633974483


Syntaxatand ( double precision ) → double precision
DescriptionInverse tangent, result in degrees
Example(s)atand(1) → 45


Syntaxatan2 ( y double precision, x double precision ) → double precision
DescriptionInverse tangent of y/x, result in radians
Example(s)atan2(1,0) → 1.5707963267948966


Syntaxatan2d ( y double precision, x double precision ) → double precision
DescriptionInverse tangent of y/x, result in degrees
Example(s)atan2d(1,0) → 90


Syntaxcos ( double precision ) → double precision
DescriptionCosine, argument in radians
Example(s)cos(0) → 1


Syntaxcosd ( double precision ) → double precision
DescriptionCosine, argument in degrees
Example(s)cosd(60) → 0.5


Syntaxcot ( double precision ) → double precision
DescriptionCotangent, argument in radians
Example(s)cot(0.5) → 1.830487721712452


Syntaxcotd ( double precision ) → double precision
DescriptionCotangent, argument in degrees
Example(s)cotd(45) → 1


Syntaxsin ( double precision ) → double precision
DescriptionSine, argument in radians
Example(s)sin(1) → 0.8414709848078965


Syntaxsind ( double precision ) → double precision
DescriptionSine, argument in degrees
Example(s)sind(30) → 0.5


Syntaxtan ( double precision ) → double precision
DescriptionTangent, argument in radians
Example(s)tan(1) → 1.5574077246549023


Syntaxtand ( double precision ) → double precision
DescriptionTangent, argument in degrees
Example(s)tand(45) → 1

Hyperbolic Functions


Syntaxsinh ( double precision ) → double precision
DescriptionHyperbolic sine
Example(s)sinh(1) → 1.1752011936438014


Syntaxcosh ( double precision ) → double precision
DescriptionHyperbolic cosine
Example(s)cosh(0) → 1


Syntaxtanh ( double precision ) → double precision
DescriptionHyperbolic tangent
Example(s)tanh(1) → 0.7615941559557649


Syntaxasinh ( double precision ) → double precision
DescriptionInverse hyperbolic sine
Example(s)asinh(1) → 0.881373587019543


Syntaxacosh ( double precision ) → double precision
DescriptionInverse hyperbolic cosine
Example(s)acosh(1) → 0


Syntaxatanh ( double precision ) → double precision
DescriptionInverse hyperbolic tangent
Example(s)atanh(0.5) → 0.5493061443340548

Dates

See the official docs for more on all functions in this category. The table immediately below provides you the most commonly used PostgreSQL functions as considred on PostgreSQL Tutorial. Links to these functions take you to the function's reference on the PostgreSQL Tutorial site. Underneath the table below is a reproduction of what currently exists in the Postgres docs in a more palatable form.

FunctionReturn TypeDescription
AGEINTERVALCalculate ages between two timestamps and returns a "symbolic" result which uses years and months
AGEINTERVALCalculate ages between current date (at midnight) and a timestamp and returns a "symbolic" result which uses years and months
CLOCK_TIMESTAMPTIMESTAMPTZReturn the current date and time which changes during statement execution
CURRENT_DATEDATEReturn the current date
CURRENT_TIMETIMESTAMPTZReturn the current time
CURRENT_TIMESTAMPTIMESTAMPTZReturn the current date and time with time zone at which the current transaction starts
DATE_PARTDOUBLE PRECISIONGet a field of a timestamp or an interval e.g., year, month, day, etc.
DATE_TRUNCTIMESTAMPReturn a timestamp truncated to a specified precision
EXTRACTDOUBLE PRECISIONSame as DATE_PART() function
ISFINITEBOOLEANCheck if a date, a timestamp, or an interval is finite or not (not +/-infinity)
JUSTIFY_DAYSINTERVALAdjust interval so 30-day time periods are represented as months
JUSTIFY_HOURSINTERVALAdjust interval so 24-hour time periods are represented as days
JUSTIFY_INTERVALINTERVALAdjust interval using justify_days and justify_hours, with additional sign adjustments
LOCALTIMETIMEReturn the time at which the current transaction start
LOCALTIMESTAMPTIMESTAMPReturn the date and time at which the current transaction start
NOWTIMESTAMPTZReturn the date and time with time zone at which the current transaction start
STATEMENT_TIMESTAMPTIMESTAMPTZReturn the current date and time at which the current statement executes
TIMEOFDAYTEXTReturn the current date and time, like clock_timestamp, as a text string
TRANSACTION_TIMESTAMPTIMESTAMPTZSame as NOW() function
TO_DATEDATEConvert a string to a date
TO_TIMESTAMPTIMESTAMPTZConvert a string to a timestamp

The tables below appear in the official Postgres docs.


Syntaxdate + integer → date
DescriptionAdd a number of days to a date
Example(s)date '2001-09-28' + 7 → 2001-10-05


Syntaxdate + interval → timestamp
DescriptionAdd an interval to a date
Example(s)date '2001-09-28' + interval '1 hour' → 2001-09-28 01:00:00


Syntaxdate + time → timestamp
DescriptionAdd a time-of-day to a date
Example(s)date '2001-09-28' + time '03:00' → 2001-09-28 03:00:00


Syntaxinterval + interval → interval
DescriptionAdd intervals
Example(s)interval '1 day' + interval '1 hour' → 1 day 01:00:00


Syntaxtimestamp + interval → timestamp
DescriptionAdd an interval to a timestamp
Example(s)timestamp '2001-09-28 01:00' + interval '23 hours' → 2001-09-29 00:00:00


Syntaxtime + interval → time
DescriptionAdd an interval to a time
Example(s)time '01:00' + interval '3 hours' → 04:00:00


Syntax- interval → interval
DescriptionNegate an interval
Example(s)- interval '23 hours' → -23:00:00


Syntaxdate - date → integer
DescriptionSubtract dates, producing the number of days elapsed
Example(s)date '2001-10-01' - date '2001-09-28' → 3


Syntaxdate - integer → date
DescriptionSubtract a number of days from a date
Example(s)date '2001-10-01' - 7 → 2001-09-24


Syntaxdate - interval → timestamp
DescriptionSubtract an interval from a date
Example(s)date '2001-09-28' - interval '1 hour' → 2001-09-27 23:00:00


Syntaxtime - time → interval
DescriptionSubtract times
Example(s)time '05:00' - time '03:00' → 02:00:00


Syntaxtime - interval → time
DescriptionSubtract an interval from a time
Example(s)time '05:00' - interval '2 hours' → 03:00:00


Syntaxtimestamp - interval → timestamp
DescriptionSubtract an interval from a timestamp
Example(s)timestamp '2001-09-28 23:00' - interval '23 hours' → 2001-09-28 00:00:00


Syntaxinterval - interval → interval
DescriptionSubtract intervals
Example(s)interval '1 day' - interval '1 hour' → 1 day -01:00:00


Syntaxtimestamp - timestamp → interval
DescriptionSubtract timestamps (converting 24-hour intervals into days, similarly to justify_hours())
Example(s)timestamp '2001-09-29 03:00' - timestamp '2001-07-27 12:00' → 63 days 15:00:00


Syntaxinterval * double precision → interval
DescriptionMultiply an interval by a scalar
Example(s)interval '1 second' * 900 → 00:15:00
interval '1 day' * 21 → 21 days
interval '1 hour' * 3.5 → 03:30:00


Syntaxinterval / double precision → interval
DescriptionDivide an interval by a scalar
Example(s)interval '1 hour' / 1.5 → 00:40:00

Date/Time Functions


Syntaxage ( timestamp, timestamp ) → interval
DescriptionSubtract arguments, producing a “symbolic” result that uses years and months, rather than just days
Example(s)age(timestamp '2001-04-10', timestamp '1957-06-13') → 43 years 9 mons 27 days


Syntaxage ( timestamp ) → interval
DescriptionSubtract argument from current_date (at midnight)
Example(s)age(timestamp '1957-06-13') → 62 years 6 mons 10 days


Syntaxclock_timestamp ( ) → timestamp with time zone
DescriptionCurrent date and time (changes during statement execution); see Section 9.9.4
Example(s)clock_timestamp() → 2019-12-23 14:39:53.662522-05


Syntaxcurrent_date → date
DescriptionCurrent date; see Section 9.9.4
Example(s)current_date → 2019-12-23


Syntaxcurrent_time → time with time zone
DescriptionCurrent time of day; see Section 9.9.4
Example(s)current_time → 14:39:53.662522-05


Syntaxcurrent_time ( integer ) → time with time zone
DescriptionCurrent time of day, with limited precision; see Section 9.9.4
Example(s)current_time(2) → 14:39:53.66-05


Syntaxcurrent_timestamp → timestamp with time zone
DescriptionCurrent date and time (start of current transaction); see Section 9.9.4
Example(s)current_timestamp → 2019-12-23 14:39:53.662522-05


Syntaxcurrent_timestamp ( integer ) → timestamp with time zone
DescriptionCurrent date and time (start of current transaction), with limited precision; see Section 9.9.4
Example(s)current_timestamp(0) → 2019-12-23 14:39:53-05


Syntaxdate_part ( text, timestamp ) → double precision
DescriptionGet timestamp subfield (equivalent to extract); see Section 9.9.1
Example(s)date_part('hour', timestamp '2001-02-16 20:38:40') → 20


Syntaxdate_part ( text, interval ) → double precision
DescriptionGet interval subfield (equivalent to extract); see Section 9.9.1
Example(s)date_part('month', interval '2 years 3 months') → 3


Syntaxdate_trunc ( text, timestamp ) → timestamp
DescriptionTruncate to specified precision; see Section 9.9.2
Example(s)date_trunc('hour', timestamp '2001-02-16 20:38:40') → 2001-02-16 20:00:00


Syntaxdate_trunc ( text, timestamp with time zone, text ) → timestamp with time zone
DescriptionTruncate to specified precision in the specified time zone; see Section 9.9.2
Example(s)date_trunc('day', timestamptz '2001-02-16 20:38:40+00', 'Australia/Sydney') → 2001-02-16 13:00:00+00


Syntaxdate_trunc ( text, interval ) → interval
DescriptionTruncate to specified precision; see Section 9.9.2
Example(s)date_trunc('hour', interval '2 days 3 hours 40 minutes') → 2 days 03:00:00


Syntaxextract ( field from timestamp ) → double precision
DescriptionGet timestamp subfield; see Section 9.9.1
Example(s)extract(hour from timestamp '2001-02-16 20:38:40') → 20


Syntaxextract ( field from interval ) → double precision
DescriptionGet interval subfield; see Section 9.9.1
Example(s)extract(month from interval '2 years 3 months') → 3


Syntaxisfinite ( date ) → boolean
DescriptionTest for finite date (not +/-infinity)
Example(s)isfinite(date '2001-02-16') → true


Syntaxisfinite ( timestamp ) → boolean
DescriptionTest for finite timestamp (not +/-infinity)
Example(s)isfinite(timestamp 'infinity') → false


Syntaxisfinite ( interval ) → boolean
DescriptionTest for finite interval (currently always true)
Example(s)isfinite(interval '4 hours') → true


Syntaxjustify_days ( interval ) → interval
DescriptionAdjust interval so 30-day time periods are represented as months
Example(s)justify_days(interval '35 days') → 1 mon 5 days


Syntaxjustify_hours ( interval ) → interval
DescriptionAdjust interval so 24-hour time periods are represented as days
Example(s)justify_hours(interval '27 hours') → 1 day 03:00:00


Syntaxjustify_interval ( interval ) → interval
DescriptionAdjust interval using justify_days and justify_hours, with additional sign adjustments
Example(s)justify_interval(interval '1 mon -1 hour') → 29 days 23:00:00


Syntaxlocaltime → time
DescriptionCurrent time of day; see Section 9.9.4
Example(s)localtime → 14:39:53.662522


Syntaxlocaltime ( integer ) → time
DescriptionCurrent time of day, with limited precision; see Section 9.9.4
Example(s)localtime(0) → 14:39:53


Syntaxlocaltimestamp → timestamp
DescriptionCurrent date and time (start of current transaction); see Section 9.9.4
Example(s)localtimestamp → 2019-12-23 14:39:53.662522


Syntaxlocaltimestamp ( integer ) → timestamp
DescriptionCurrent date and time (start of current transaction), with limited precision; see Section 9.9.4
Example(s)localtimestamp(2) → 2019-12-23 14:39:53.66


Syntaxmake_date ( year int, month int, day int ) → date
DescriptionCreate date from year, month and day fields
Example(s)make_date(2013, 7, 15) → 2013-07-15


Syntaxmake_interval ( [ years int [, months int [, weeks int [, days int [, hours int [, mins int [, secs double precision ]]]]]]] ) → interval
DescriptionCreate interval from years, months, weeks, days, hours, minutes and seconds fields, each of which can default to zero
Example(s)make_interval(days => 10) → 10 days


Syntaxmake_time ( hour int, min int, sec double precision ) → time
DescriptionCreate time from hour, minute and seconds fields
Example(s)make_time(8, 15, 23.5) → 08:15:23.5


Syntaxmake_timestamp ( year int, month int, day int, hour int, min int, sec double precision ) → timestamp
DescriptionCreate timestamp from year, month, day, hour, minute and seconds fields
Example(s)make_timestamp(2013, 7, 15, 8, 15, 23.5) → 2013-07-15 08:15:23.5


Syntaxmake_timestamptz ( year int, month int, day int, hour int, min int, sec double precision [, timezone text ] ) → timestamp with time zone
DescriptionCreate timestamp with time zone from year, month, day, hour, minute and seconds fields; if timezone is not specified, the current time zone is used
Example(s)make_timestamptz(2013, 7, 15, 8, 15, 23.5) → 2013-07-15 08:15:23.5+01


Syntaxnow ( ) → timestamp with time zone
DescriptionCurrent date and time (start of current transaction); see Section 9.9.4
Example(s)now() → 2019-12-23 14:39:53.662522-05


Syntaxstatement_timestamp ( ) → timestamp with time zone
DescriptionCurrent date and time (start of current statement); see Section 9.9.4
Example(s)statement_timestamp() → 2019-12-23 14:39:53.662522-05


Syntaxtimeofday ( ) → text
DescriptionCurrent date and time (like clock_timestamp, but as a text string); see Section 9.9.4
Example(s)timeofday() → Mon Dec 23 14:39:53.662522 2019 EST


Syntaxtransaction_timestamp ( ) → timestamp with time zone
DescriptionCurrent date and time (start of current transaction); see Section 9.9.4
Example(s)transaction_timestamp() → 2019-12-23 14:39:53.662522-05


Syntaxto_timestamp ( double precision ) → timestamp with time zone
DescriptionConvert Unix epoch (seconds since 1970-01-01 00:00:00+00) to timestamp with time zone
Example(s)to_timestamp(1284352323) → 2010-09-13 04:32:03+00

Window Functions

See the official docs for more on all functions in this category. The table immediately below provides you the most commonly used PostgreSQL functions as considred on PostgreSQL Tutorial. Links to these functions take you to the function's reference on the PostgreSQL Tutorial site. Underneath the table below is a reproduction of what currently exists in the Postgres docs in a more palatable form.

The table immediately below lists all window functions provided by PostgreSQL. Note that some aggregate functions such as AVG(), MIN(), MAX(), SUM(), and COUNT() can be also used as window functions.

FunctionDescription
CUME_DISTReturn the relative rank of the current row
DENSE_RANKRank the current row within its partition without gaps
FIRST_VALUEReturn a value evaluated against the first row within its partition
LAGReturn a value evaluated at the row that is at a specified physical offset row before the current row within the partition
LAST_VALUEReturn a value evaluated against the last row within its partition
LEADReturn a value evaluated at the row that is offset rows after the current row within the partition
NTILEDivide rows in a partition as equally as possible and assign each row an integer starting from 1 to the argument value
NTH_VALUEReturn a value evaluated against the nth row in an ordered partition
PERCENT_RANKReturn the relative rank of the current row (rank-1) / (total rows – 1)
RANKRank the current row within its partition with gaps
ROW_NUMBERNumber the current row within its partition starting from 1

The following table is from the official Postgres docs.


Syntaxrow_number () → bigint
DescriptionReturns the number of the current row within its partition, counting from 1.


Syntaxrank () → bigint
DescriptionReturns the rank of the current row, with gaps; that is, the row_number of the first row in its peer group.


Syntaxdense_rank () → bigint
DescriptionReturns the rank of the current row, without gaps; this function effectively counts peer groups.


Syntaxpercent_rank () → double precision
DescriptionReturns the relative rank of the current row, that is (rank - 1) / (total partition rows - 1). The value thus ranges from 0 to 1 inclusive.


Syntaxcume_dist () → double precision
DescriptionReturns the cumulative distribution, that is (number of partition rows preceding or peers with current row) / (total partition rows). The value thus ranges from 1/N to 1.


Syntaxntile ( num_buckets integer ) → integer
DescriptionReturns an integer ranging from 1 to the argument value, dividing the partition as equally as possible.


Syntaxlag ( value anyelement [, offset integer [, default anyelement ]] ) → anyelement
DescriptionReturns value evaluated at the row that is offset rows before the current row within the partition; if there is no such row, instead returns default (which must be of the same type as value). Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to NULL.


Syntaxlead ( value anyelement [, offset integer [, default anyelement ]] ) → anyelement
DescriptionReturns value evaluated at the row that is offset rows after the current row within the partition; if there is no such row, instead returns default (which must be of the same type as value). Both offset and default are evaluated with respect to the current row. If omitted, offset defaults to 1 and default to NULL.


Syntaxfirst_value ( value anyelement ) → anyelement
DescriptionReturns value evaluated at the row that is the first row of the window frame.


Syntaxlast_value ( value anyelement ) → anyelement
DescriptionReturns value evaluated at the row that is the last row of the window frame.


Syntaxnth_value ( value anyelement, n integer ) → anyelement
DescriptionReturns value evaluated at the row that is the n'th row of the window frame (counting from 1); returns NULL if there is no such row.

Set Returning Functions

See the official docs for more on all functions in this category. Specifically, this section describes functions that possibly return more than one row. The most widely used functions in this class are series generating functions, as shown below:


Syntaxgenerate_series ( start integer, stop integer [, step integer ] ) → setof integer
generate_series ( start bigint, stop bigint [, step bigint ] ) → setof bigint
generate_series ( start numeric, stop numeric [, step numeric ] ) → setof numeric
DescriptionGenerates a series of values from start to stop, with a step size of step. step defaults to 1.


Syntaxgenerate_series ( start timestamp, stop timestamp, step interval ) → setof timestamp
generate_series ( start timestamp with time zone, stop timestamp with time zone, step interval ) → setof timestamp with time zone
DescriptionGenerates a series of values from start to stop, with a step size of step.

When step is positive, zero rows are returned if start is greater than stop. Conversely, when step is negative, zero rows are returned if start is less than stop. Zero rows are also returned if any input is NULL. It is an error for step to be zero. Some examples follow:

1. Generate series of sequential integers

SELECT * FROM GENERATE_SERIES(2,4);

yields

┌─────────────────┐
│ generate_series │
├─────────────────┤
│ 2 │
│ 3 │
│ 4 │
└─────────────────┘
(3 rows)

2. Generate series of sequential integers in reverse with a specified step size

SELECT * FROM GENERATE_SERIES(5,1,-2);

yields

┌─────────────────┐
│ generate_series │
├─────────────────┤
│ 5 │
│ 3 │
│ 1 │
└─────────────────┘
(3 rows)

3. Return 0 rows by specifying a stop value smaller than a start value

SELECT * FROM GENERATE_SERIES(4,3);

yields

┌─────────────────┐
│ generate_series │
├─────────────────┤
└─────────────────┘
(0 rows)

4. Specify a non-integer step size

SELECT GENERATE_SERIES(1.1, 4, 1.3);

yields

┌─────────────────┐
│ generate_series │
├─────────────────┤
│ 1.1 │
│ 2.4 │
│ 3.7 │
└─────────────────┘
(3 rows)

5. Generate sequential dates

-- this example relies on the date-plus-integer operator:
SELECT CURRENT_DATE + s.a AS dates FROM GENERATE_SERIES(0,14,7) AS s(a);

yields

┌────────────┐
│ dates │
├────────────┤
│ 2021-03-04 │
│ 2021-03-11 │
│ 2021-03-18 │
└────────────┘
(3 rows)

6. Generate range of timestamps between two specified timestamps using a given step size

SELECT * FROM GENERATE_SERIES('2008-03-01 00:00'::TIMESTAMP, '2008-03-04 12:00', '10 hours');

yields

┌─────────────────────┐
│ generate_series │
├─────────────────────┤
│ 2008-03-01 00:00:00 │
│ 2008-03-01 10:00:00 │
│ 2008-03-01 20:00:00 │
│ 2008-03-02 06:00:00 │
│ 2008-03-02 16:00:00 │
│ 2008-03-03 02:00:00 │
│ 2008-03-03 12:00:00 │
│ 2008-03-03 22:00:00 │
│ 2008-03-04 08:00:00 │
└─────────────────────┘
(9 rows)