Movatterモバイル変換


[0]ホーム

URL:



Facebook
Postgres Pro
Facebook
Downloads
9.4. String Functions and Operators
Prev UpChapter 9. Functions and OperatorsHome Next

9.4. String Functions and Operators#

This section describes functions and operators for examining and manipulating string values. Strings in this context include values of the typescharacter,character varying, andtext. Except where noted, these functions and operators are declared to accept and return typetext. They will interchangeably acceptcharacter varying arguments. Values of typecharacter will be converted totext before the function or operator is applied, resulting in stripping any trailing spaces in thecharacter value.

SQL defines some string functions that use key words, rather than commas, to separate arguments. Details are inTable 9.9.PostgreSQL also provides versions of these functions that use the regular function invocation syntax (seeTable 9.10).

Note

The string concatenation operator (||) will accept non-string input, so long as at least one input is of string type, as shown inTable 9.9. For other cases, inserting an explicit coercion totext can be used to have non-string input accepted.

Table 9.9. SQL String Functions and Operators

Function/Operator

Description

Example(s)

text||texttext

Concatenates the two strings.

'Post' || 'greSQL'PostgreSQL

text||anynonarraytext

anynonarray||texttext

Converts 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 totext explicitly.)

'Value: ' || 42Value: 42

btrim (stringtext [,characterstext] ) →text

Removes the longest string containing only characters incharacters (a space by default) from the start and end ofstring.

btrim('xyxtrimyyx', 'xyz')trim

textIS [NOT] [form]NORMALIZEDboolean

Checks whether the string is in the specified Unicode normalization form. The optionalform key word specifies the form:NFC (the default),NFD,NFKC, orNFKD. This expression can only be used when the server encoding isUTF8. Note that checking for normalization using this expression is often faster than normalizing possibly already normalized strings.

U&'\0061\0308bc' IS NFD NORMALIZEDt

bit_length (text ) →integer

Returns number of bits in the string (8 times theoctet_length).

bit_length('jose')32

char_length (text ) →integer

character_length (text ) →integer

Returns number of characters in the string.

char_length('josé')4

lower (text ) →text

Converts the string to all lower case, according to the rules of the database's locale.

lower('TOM')tom

lpad (stringtext,lengthinteger [,filltext] ) →text

Extends thestring to lengthlength by prepending the charactersfill (a space by default). If thestring is already longer thanlength then it is truncated (on the right).

lpad('hi', 5, 'xy')xyxhi

ltrim (stringtext [,characterstext] ) →text

Removes the longest string containing only characters incharacters (a space by default) from the start ofstring.

ltrim('zzzytest', 'xyz')test

normalize (text [,form] ) →text

Converts the string to the specified Unicode normalization form. The optionalform key word specifies the form:NFC (the default),NFD,NFKC, orNFKD. This function can only be used when the server encoding isUTF8.

normalize(U&'\0061\0308bc', NFC)U&'\00E4bc'

octet_length (text ) →integer

Returns number of bytes in the string.

octet_length('josé')5 (if server encoding is UTF8)

octet_length (character ) →integer

Returns number of bytes in the string. Since this version of the function accepts typecharacter directly, it will not strip trailing spaces.

octet_length('abc '::character(4))4

overlay (stringtextPLACINGnewsubstringtextFROMstartinteger [FORcountinteger] ) →text

Replaces the substring ofstring that starts at thestart'th character and extends forcount characters withnewsubstring. Ifcount is omitted, it defaults to the length ofnewsubstring.

overlay('Txxxxas' placing 'hom' from 2 for 4)Thomas

position (substringtextINstringtext ) →integer

Returns first starting index of the specifiedsubstring withinstring, or zero if it's not present.

position('om' in 'Thomas')3

rpad (stringtext,lengthinteger [,filltext] ) →text

Extends thestring to lengthlength by appending the charactersfill (a space by default). If thestring is already longer thanlength then it is truncated.

rpad('hi', 5, 'xy')hixyx

rtrim (stringtext [,characterstext] ) →text

Removes the longest string containing only characters incharacters (a space by default) from the end ofstring.

rtrim('testxxzx', 'xyz')test

substring (stringtext [FROMstartinteger] [FORcountinteger] ) →text

Extracts the substring ofstring starting at thestart'th character if that is specified, and stopping aftercount characters if that is specified. Provide at least one ofstart andcount.

substring('Thomas' from 2 for 3)hom

substring('Thomas' from 3)omas

substring('Thomas' for 2)Th

substring (stringtextFROMpatterntext ) →text

Extracts the first substring matching POSIX regular expression; seeSection 9.7.3.

substring('Thomas' from '...$')mas

substring (stringtextSIMILARpatterntextESCAPEescapetext ) →text

substring (stringtextFROMpatterntextFORescapetext ) →text

Extracts the first substring matchingSQL regular expression; seeSection 9.7.2. The first form has been specified since SQL:2003; the second form was only in SQL:1999 and should be considered obsolete.

substring('Thomas' similar '%#"o_a#"_' escape '#')oma

trim ( [LEADING |TRAILING |BOTH] [characterstext]FROMstringtext ) →text

Removes the longest string containing only characters incharacters (a space by default) from the start, end, or both ends (BOTH is the default) ofstring.

trim(both 'xyz' from 'yxTomxx')Tom

trim ( [LEADING |TRAILING |BOTH] [FROM]stringtext [,characterstext] ) →text

This is a non-standard syntax fortrim().

trim(both from 'yxTomxx', 'xyz')Tom

unicode_assigned (text ) →boolean

Returnstrue if all characters in the string are assigned Unicode codepoints;false otherwise. This function can only be used when the server encoding isUTF8.

upper (text ) →text

Converts the string to all upper case, according to the rules of the database's locale.

upper('tom')TOM


Additional string manipulation functions and operators are available and are listed inTable 9.10. (Some of these are used internally to implement theSQL-standard string functions listed inTable 9.9.) There are also pattern-matching operators, which are described inSection 9.7, and operators for full-text search, which are described inChapter 12.

Table 9.10. Other String Functions and Operators

Function/Operator

Description

Example(s)

text^@textboolean

Returns true if the first string starts with the second string (equivalent to thestarts_with() function).

'alphabet' ^@ 'alph't

ascii (text ) →integer

Returns the numeric code of the first character of the argument. InUTF8 encoding, returns the Unicode code point of the character. In other multibyte encodings, the argument must be anASCII character.

ascii('x')120

chr (integer ) →text

Returns the character with the given code. InUTF8 encoding the argument is treated as a Unicode code point. In other multibyte encodings the argument must designate anASCII character.chr(0) is disallowed because text data types cannot store that character.

chr(65)A

concat (val1"any" [,val2"any" [, ...] ] ) →text

Concatenates the text representations of all the arguments. NULL arguments are ignored.

concat('abcde', 2, NULL, 22)abcde222

concat_ws (septext,val1"any" [,val2"any" [, ...] ] ) →text

Concatenates 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.

concat_ws(',', 'abcde', 2, NULL, 22)abcde,2,22

format (formatstrtext [,formatarg"any" [, ...] ] ) →text

Formats arguments according to a format string; seeSection 9.4.1. This function is similar to the C functionsprintf.

format('Hello %s, %1$s', 'World')Hello World, World

initcap (text ) →text

Converts 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.

initcap('hi THOMAS')Hi Thomas

left (stringtext,ninteger ) →text

Returns firstn characters in the string, or whenn is negative, returns all but last |n| characters.

left('abcde', 2)ab

length (text ) →integer

Returns the number of characters in the string.

length('jose')4

md5 (text ) →text

Computes the MD5hash of the argument, with the result written in hexadecimal.

md5('abc')900150983cd24fb0​d6963f7d28e17f72

parse_ident (qualified_identifiertext [,strict_modebooleanDEFAULTtrue ] ) →text[]

Splitsqualified_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 isfalse, 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 toname[].

parse_ident('"SomeSchema".someTable'){SomeSchema,sometable}

pg_client_encoding ( ) →name

Returns current client encoding name.

pg_client_encoding()UTF8

quote_ident (text ) →text

Returns the given string suitably quoted to be used as an identifier in anSQL 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 alsoExample 41.1.

quote_ident('Foo bar')"Foo bar"

quote_literal (text ) →text

Returns the given string suitably quoted to be used as a string literal in anSQL statement string. Embedded single-quotes and backslashes are properly doubled. Note thatquote_literal returns null on null input; if the argument might be null,quote_nullable is often more suitable. See alsoExample 41.1.

quote_literal(E'O\'Reilly')'O''Reilly'

quote_literal (anyelement ) →text

Converts the given value to text and then quotes it as a literal. Embedded single-quotes and backslashes are properly doubled.

quote_literal(42.5)'42.5'

quote_nullable (text ) →text

Returns the given string suitably quoted to be used as a string literal in anSQL statement string; or, if the argument is null, returnsNULL. Embedded single-quotes and backslashes are properly doubled. See alsoExample 41.1.

quote_nullable(NULL)NULL

quote_nullable (anyelement ) →text

Converts the given value to text and then quotes it as a literal; or, if the argument is null, returnsNULL. Embedded single-quotes and backslashes are properly doubled.

quote_nullable(42.5)'42.5'

regexp_count (stringtext,patterntext [,startinteger [,flagstext ] ] ) →integer

Returns the number of times the POSIX regular expressionpattern matches in thestring; seeSection 9.7.3.

regexp_count('123456789012', '\d\d\d', 2)3

regexp_instr (stringtext,patterntext [,startinteger [,Ninteger [,endoptioninteger [,flagstext [,subexprinteger ] ] ] ] ] ) →integer

Returns the position withinstring where theN'th match of the POSIX regular expressionpattern occurs, or zero if there is no such match; seeSection 9.7.3.

regexp_instr('ABCDEF', 'c(.)(..)', 1, 1, 0, 'i')3

regexp_instr('ABCDEF', 'c(.)(..)', 1, 1, 0, 'i', 2)5

regexp_like (stringtext,patterntext [,flagstext ] ) →boolean

Checks whether a match of the POSIX regular expressionpattern occurs withinstring; seeSection 9.7.3.

regexp_like('Hello World', 'world$', 'i')t

regexp_match (stringtext,patterntext [,flagstext ] ) →text[]

Returns substrings within the first match of the POSIX regular expressionpattern to thestring; seeSection 9.7.3.

regexp_match('foobarbequebaz', '(bar)(beque)'){bar,beque}

regexp_matches (stringtext,patterntext [,flagstext ] ) →setof text[]

Returns substrings within the first match of the POSIX regular expressionpattern to thestring, or substrings within all such matches if theg flag is used; seeSection 9.7.3.

regexp_matches('foobarbequebaz', 'ba.', 'g')

 {bar} {baz}

regexp_replace (stringtext,patterntext,replacementtext [,startinteger ] [,flagstext ] ) →text

Replaces the substring that is the first match to the POSIX regular expressionpattern, or all such matches if theg flag is used; seeSection 9.7.3.

regexp_replace('Thomas', '.[mN]a.', 'M')ThM

regexp_replace (stringtext,patterntext,replacementtext,startinteger,Ninteger [,flagstext ] ) →text

Replaces the substring that is theN'th match to the POSIX regular expressionpattern, or all such matches ifN is zero; seeSection 9.7.3.

regexp_replace('Thomas', '.', 'X', 3, 2)ThoXas

regexp_split_to_array (stringtext,patterntext [,flagstext ] ) →text[]

Splitsstring using a POSIX regular expression as the delimiter, producing an array of results; seeSection 9.7.3.

regexp_split_to_array('hello world', '\s+'){hello,world}

regexp_split_to_table (stringtext,patterntext [,flagstext ] ) →setof text

Splitsstring using a POSIX regular expression as the delimiter, producing a set of results; seeSection 9.7.3.

regexp_split_to_table('hello world', '\s+')

 hello world

regexp_substr (stringtext,patterntext [,startinteger [,Ninteger [,flagstext [,subexprinteger ] ] ] ] ) →text

Returns the substring withinstring that matches theN'th occurrence of the POSIX regular expressionpattern, orNULL if there is no such match; seeSection 9.7.3.

regexp_substr('ABCDEF', 'c(.)(..)', 1, 1, 'i')CDEF

regexp_substr('ABCDEF', 'c(.)(..)', 1, 1, 'i', 2)EF

repeat (stringtext,numberinteger ) →text

Repeatsstring the specifiednumber of times.

repeat('Pg', 4)PgPgPgPg

replace (stringtext,fromtext,totext ) →text

Replaces all occurrences instring of substringfrom with substringto.

replace('abcdefabcdef', 'cd', 'XX')abXXefabXXef

reverse (text ) →text

Reverses the order of the characters in the string.

reverse('abcde')edcba

right (stringtext,ninteger ) →text

Returns lastn characters in the string, or whenn is negative, returns all but first |n| characters.

right('abcde', 2)de

split_part (stringtext,delimitertext,ninteger ) →text

Splitsstring at occurrences ofdelimiter and returns then'th field (counting from one), or whenn is negative, returns the |n|'th-from-last field.

split_part('abc~@~def~@~ghi', '~@~', 2)def

split_part('abc,def,ghi,jkl', ',', -2)ghi

starts_with (stringtext,prefixtext ) →boolean

Returns true ifstring starts withprefix.

starts_with('alphabet', 'alph')t

string_to_array (stringtext,delimitertext [,null_stringtext] ) →text[]

Splits thestring at occurrences ofdelimiter and forms the resulting fields into atext array. Ifdelimiter isNULL, each character in thestring will become a separate element in the array. Ifdelimiter is an empty string, then thestring is treated as a single field. Ifnull_string is supplied and is notNULL, fields matching that string are replaced byNULL. See alsoarray_to_string.

string_to_array('xx~~yy~~zz', '~~', 'yy'){xx,NULL,zz}

string_to_table (stringtext,delimitertext [,null_stringtext] ) →setof text

Splits thestring at occurrences ofdelimiter and returns the resulting fields as a set oftext rows. Ifdelimiter isNULL, each character in thestring will become a separate row of the result. Ifdelimiter is an empty string, then thestring is treated as a single field. Ifnull_string is supplied and is notNULL, fields matching that string are replaced byNULL.

string_to_table('xx~^~yy~^~zz', '~^~', 'yy')

 xx NULL zz

strpos (stringtext,substringtext ) →integer

Returns first starting index of the specifiedsubstring withinstring, or zero if it's not present. (Same asposition(substring instring), but note the reversed argument order.)

strpos('high', 'ig')2

substr (stringtext,startinteger [,countinteger] ) →text

Extracts the substring ofstring starting at thestart'th character, and extending forcount characters if that is specified. (Same assubstring(string fromstart forcount).)

substr('alphabet', 3)phabet

substr('alphabet', 3, 2)ph

to_ascii (stringtext ) →text

to_ascii (stringtext,encodingname ) →text

to_ascii (stringtext,encodinginteger ) →text

Convertsstring toASCII from another encoding, which may be identified by name or number. Ifencoding 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 fromLATIN1,LATIN2,LATIN9, andWIN1250 encodings. (See theunaccent module for another, more flexible solution.)

to_ascii('Karél')Karel

to_bin (integer ) →text

to_bin (bigint ) →text

Converts the number to its equivalent two's complement binary representation.

to_bin(2147483647)1111111111111111111111111111111

to_bin(-1234)11111111111111111111101100101110

to_hex (integer ) →text

to_hex (bigint ) →text

Converts the number to its equivalent two's complement hexadecimal representation.

to_hex(2147483647)7fffffff

to_hex(-1234)fffffb2e

to_oct (integer ) →text

to_oct (bigint ) →text

Converts the number to its equivalent two's complement octal representation.

to_oct(2147483647)17777777777

to_oct(-1234)37777775456

translate (stringtext,fromtext,totext ) →text

Replaces each character instring that matches a character in thefrom set with the corresponding character in theto set. Iffrom is longer thanto, occurrences of the extra characters infrom are deleted.

translate('12345', '143', 'ax')a2x5

unistr (text ) →text

Evaluate escaped Unicode characters in the argument. Unicode characters can be specified as\XXXX (4 hexadecimal digits),\+XXXXXX (6 hexadecimal digits),\uXXXX (4 hexadecimal digits), or\UXXXXXXXX (8 hexadecimal digits). To specify a backslash, write two backslashes. All other characters are taken literally.

If the server encoding is not UTF-8, the Unicode code point identified by one of these escape sequences is converted to the actual server encoding; an error is reported if that's not possible.

This function provides a (non-standard) alternative to string constants with Unicode escapes (seeSection 4.1.2.3).

unistr('d\0061t\+000061')data

unistr('d\u0061t\U00000061')data


Theconcat,concat_ws andformat functions are variadic, so it is possible to pass the values to be concatenated or formatted as an array marked with theVARIADIC keyword (seeSection 36.5.6). The array's elements are treated as if they were separate ordinary arguments to the function. If the variadic array argument is NULL,concat andconcat_ws return NULL, butformat treats a NULL as a zero-element array.

See also the aggregate functionstring_agg inSection 9.21, and the functions for converting between strings and thebytea type inTable 9.13.

9.4.1. format#

The functionformat produces output formatted according to a format string, in a style similar to the C functionsprintf.

format(formatstrtext [,formatarg"any" [, ...] ])

formatstr is a format string that specifies how the result should be formatted. Text in the format string is copied directly to the result, except whereformat specifiers are used. Format specifiers act as placeholders in the string, defining how subsequent function arguments should be formatted and inserted into the result. Eachformatarg argument is converted to text according to the usual output rules for its data type, and then formatted and inserted into the result string according to the format specifier(s).

Format specifiers are introduced by a% character and have the form

%[position][flags][width]type

where the component fields are:

position (optional)

A string of the formn$ wheren is the index of the argument to print. Index 1 means the first argument afterformatstr. If theposition is omitted, the default is to use the next argument in sequence.

flags (optional)

Additional options controlling how the format specifier's output is formatted. Currently the only supported flag is a minus sign (-) which will cause the format specifier's output to be left-justified. This has no effect unless thewidth field is also specified.

width (optional)

Specifies theminimum number of characters to use to display the format specifier's output. The output is padded on the left or right (depending on the- flag) with spaces as needed to fill the width. A too-small width does not cause truncation of the output, but is simply ignored. The width may be specified using any of the following: a positive integer; an asterisk (*) to use the next function argument as the width; or a string of the form*n$ to use thenth function argument as the width.

If the width comes from a function argument, that argument is consumed before the argument that is used for the format specifier's value. If the width argument is negative, the result is left aligned (as if the- flag had been specified) within a field of lengthabs(width).

type (required)

The type of format conversion to use to produce the format specifier's output. The following types are supported:

  • s formats the argument value as a simple string. A null value is treated as an empty string.

  • I treats the argument value as an SQL identifier, double-quoting it if necessary. It is an error for the value to be null (equivalent toquote_ident).

  • L quotes the argument value as an SQL literal. A null value is displayed as the stringNULL, without quotes (equivalent toquote_nullable).

In addition to the format specifiers described above, the special sequence%% may be used to output a literal% character.

Here are some examples of the basic format conversions:

SELECT format('Hello %s', 'World');Result:Hello WorldSELECT format('Testing %s, %s, %s, %%', 'one', 'two', 'three');Result:Testing one, two, three, %SELECT format('INSERT INTO %I VALUES(%L)', 'Foo bar', E'O\'Reilly');Result:INSERT INTO "Foo bar" VALUES('O''Reilly')SELECT format('INSERT INTO %I VALUES(%L)', 'locations', 'C:\Program Files');Result:INSERT INTO locations VALUES('C:\Program Files')

Here are examples usingwidth fields and the- flag:

SELECT format('|%10s|', 'foo');Result:|       foo|SELECT format('|%-10s|', 'foo');Result:|foo       |SELECT format('|%*s|', 10, 'foo');Result:|       foo|SELECT format('|%*s|', -10, 'foo');Result:|foo       |SELECT format('|%-*s|', 10, 'foo');Result:|foo       |SELECT format('|%-*s|', -10, 'foo');Result:|foo       |

These examples show use ofposition fields:

SELECT format('Testing %3$s, %2$s, %1$s', 'one', 'two', 'three');Result:Testing three, two, oneSELECT format('|%*2$s|', 'foo', 10, 'bar');Result:|       bar|SELECT format('|%1$*2$s|', 'foo', 10, 'bar');Result:|       foo|

Unlike the standard C functionsprintf,PostgreSQL'sformat function allows format specifiers with and withoutposition fields to be mixed in the same format string. A format specifier without aposition field always uses the next argument after the last argument consumed. In addition, theformat function does not require all function arguments to be used in the format string. For example:

SELECT format('Testing %3$s, %2$s, %s', 'one', 'two', 'three');Result:Testing three, two, three

The%I and%L format specifiers are particularly useful for safely constructing dynamic SQL statements. SeeExample 41.1.


Prev Up Next
9.3. Mathematical Functions and Operators Home 9.5. Binary String Functions and Operators
pdfepub
Go to PostgreSQL 17
By continuing to browse this website, you agree to the use of cookies. Go toPrivacy Policy.

[8]ページ先頭

©2009-2025 Movatter.jp