バージョンごとのドキュメント一覧

9.4. 文字列関数と演算子 #

<title>String Functions and Operators</title>

This section describes functions and operators for examining and manipulating string values. Strings in this context include values of the types <type>character</type>, <type>character varying</type>, and <type>text</type>. Except where noted, these functions and operators are declared to accept and return type <type>text</type>. They will interchangeably accept <type>character varying</type> arguments. Values of type <type>character</type> will be converted to <type>text</type> before the function or operator is applied, resulting in stripping any trailing spaces in the <type>character</type> value. 本節では文字列の値の調査や操作のための関数と演算子について説明します。 ここでの文字列とはcharacterデータ型、character varyingデータ型、およびtextデータ型の値を含みます。 補足説明のない限り、下記に挙げている全ての関数はtext型を受付、また戻り値型として返すように宣言されています。 それらはcharacter varyingデータ型も同じように受け付けます。 character型の値は関数あるいは演算子に適用される前にtextに変換され、character値の末尾の空白が削除されることになります。

<acronym>SQL</acronym> defines some string functions that use key words, rather than commas, to separate arguments. Details are in <xref linkend="functions-string-sql"/>. <productname>PostgreSQL</productname> also provides versions of these functions that use the regular function invocation syntax (see <xref linkend="functions-string-other"/>). SQLでは引数の区切りにカンマではなくキーワードを使用する文字列関数をいくつか定義しています。 詳細については表 9.9を参照してください。 またPostgreSQLは、これらの関数に対して通常の関数呼び出し構文を使用するバージョンを提供します(表 9.10を参照してください)。

注記

The string concatenation operator (<literal>||</literal>) will accept non-string input, so long as at least one input is of string type, as shown in <xref linkend="functions-string-sql"/>. For other cases, inserting an explicit coercion to <type>text</type> can be used to have non-string input accepted. 文字列連結演算子(||)は表 9.9で示されるように、少なくともひとつの入力が文字列型であれば、依然として非文字列入力を受け付けます。 その他の場合には非文字列入力を受け付けるために、textへの明示的な変換を行うことが可能です。

表9.9 SQL文字列関数と演算子

<title><acronym>SQL</acronym> String Functions and Operators</title>

Function/Operator 関数/演算子

Description 説明

Example(s)

text || texttext

Concatenates the two strings. 2つの文字列を結合します。

'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 <literal>||</literal> operators. If you want to concatenate an array's text equivalent, cast it to <type>text</type> explicitly.) 非文字列の入力をテキストに変換したのちに2つの文字列を結合します。 (非文字列の入力は配列型であってはいけません。配列の||演算子との間で曖昧性が生じるからです。 配列のテキストあるいは類似のものを結合する場合は明示的にtextにキャストしてください。)

'Value: ' || 42Value: 42

btrim ( string text [, characters text ] ) → text

Removes the longest string containing only characters in <parameter>characters</parameter> (a space by default) from the start and end of <parameter>string</parameter>. stringからcharacters(空白一文字がデフォルト)に現れる文字のみを含む最長の文字列を先頭と末尾から取り除きます。

btrim('xyxtrimyyx', 'xyz')trim

text IS [NOT] [form] NORMALIZEDboolean

Checks whether the string is in the specified Unicode normalization form. The optional <parameter>form</parameter> key word specifies the form: <literal>NFC</literal> (the default), <literal>NFD</literal>, <literal>NFKC</literal>, or <literal>NFKD</literal>. This expression can only be used when the server encoding is <literal>UTF8</literal>. Note that checking for normalization using this expression is often faster than normalizing possibly already normalized strings. 文字列が指定したUnicode正規形の範囲かどうかをチェックします。 オプションのformキーワードは正規形を指定します。NFC (デフォルトです)、NFDNFKCあるいはNFKDです。 この式はサーバエンコーディングがUTF8のときだけ使用できます。 この式を用いた正規形のチェックは、しばしばすでに正規化されている可能性のある文字列を正規化するよりも高速であることに注意してください。

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

bit_length ( text ) → integer

Returns number of bits in the string (8 times the <function>octet_length</function>). 文字列中のビット数を返します(octet_lengthの8倍です。)

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 ( string text, length integer [, fill text ] ) → text

Extends the <parameter>string</parameter> to length <parameter>length</parameter> by prepending the characters <parameter>fill</parameter> (a space by default). If the <parameter>string</parameter> is already longer than <parameter>length</parameter> then it is truncated (on the right). 文字fill(デフォルトは空白文字)を文字列の前に追加して、stringlengthの長さにします。 stringが既にlengthの長さを超えている場合は(右側が)切り捨てられます。

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

ltrim ( string text [, characters text ] ) → text

Removes the longest string containing only characters in <parameter>characters</parameter> (a space by default) from the start of <parameter>string</parameter>. stringからcharacters(空白一文字がデフォルト)に現れる文字のみを含む最長の文字列を先頭から取り除きます。

ltrim('zzzytest', 'xyz')test

normalize ( text [, form ] ) → text

Converts the string to the specified Unicode normalization form. The optional <parameter>form</parameter> key word specifies the form: <literal>NFC</literal> (the default), <literal>NFD</literal>, <literal>NFKC</literal>, or <literal>NFKD</literal>. This function can only be used when the server encoding is <literal>UTF8</literal>. 文字列を指定したUnicode正規形に変換します。 オプションのformキーワードは正規形を指定します。NFC (デフォルトです)、NFDNFKCあるいはNFKDです。 この式はサーバエンコーディングがUTF8のときだけ使用できます。

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

octet_length ( text ) → integer

Returns number of bytes in the string. 文字列のバイト数を返します。

octet_length('josé') <returnvalue>5</returnvalue> (if server encoding is UTF8) 5(サーバーエンコーディングがUTF8の場合)

octet_length ( character ) → integer

Returns number of bytes in the string. Since this version of the function accepts type <type>character</type> directly, it will not strip trailing spaces. 文字列のバイト数を返します。 このバージョンの関数は直接character型を受け付けるので、末尾の空白を削除しません。

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

overlay ( string text PLACING newsubstring text FROM start integer [ FOR count integer ] ) → text

Replaces the substring of <parameter>string</parameter> that starts at the <parameter>start</parameter>'th character and extends for <parameter>count</parameter> characters with <parameter>newsubstring</parameter>. If <parameter>count</parameter> is omitted, it defaults to the length of <parameter>newsubstring</parameter>. stringstart文字目からcount文字をnewsubstringで置き換えます。 countを省略するとnewsubstringの長さがデフォルトになります。

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

position ( substring text IN string text ) → integer

Returns first starting index of the specified <parameter>substring</parameter> within <parameter>string</parameter>, or zero if it's not present. string中のsubstringで指定する文字列の最初の開始位置を返します。0ならその文字列は存在しません。

position('om' in 'Thomas')3

rpad ( string text, length integer [, fill text ] ) → text

Extends the <parameter>string</parameter> to length <parameter>length</parameter> by appending the characters <parameter>fill</parameter> (a space by default). If the <parameter>string</parameter> is already longer than <parameter>length</parameter> then it is truncated. 文字fill(デフォルトは空白文字)を文字列に追加して、stringlengthの長さにします。 stringが既にlengthの長さを超えている場合は切り捨てられます。

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

rtrim ( string text [, characters text ] ) → text

Removes the longest string containing only characters in <parameter>characters</parameter> (a space by default) from the end of <parameter>string</parameter>. stringからcharacters(空白一文字がデフォルト)に現れる文字のみを含む最長の文字列を末尾から取り除きます。

rtrim('testxxzx', 'xyz')test

substring ( string text [ FROM start integer ] [ FOR count integer ] ) → text

Extracts the substring of <parameter>string</parameter> starting at the <parameter>start</parameter>'th character if that is specified, and stopping after <parameter>count</parameter> characters if that is specified. Provide at least one of <parameter>start</parameter> and <parameter>count</parameter>. startが指定されていればstart番目の文字で始まるstringの部分文字列を返します。 countが指定されていればcount数の文字を取り出します。 少なくともstartcountのどちらかを指定してください。

substring('Thomas' from 2 for 3)hom

substring('Thomas' from 3)omas

substring('Thomas' for 2)Th

substring ( string text FROM pattern text ) → text

Extracts the first substring matching POSIX regular expression; see <xref linkend="functions-posix-regexp"/>. POSIX正規表現にマッチする最初の部分文字列を返します。9.7.3を参照してください。

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

substring ( string text SIMILAR pattern text ESCAPE escape text ) → text

substring ( string text FROM pattern text FOR escape text ) → text

Extracts the first substring matching <acronym>SQL</acronym> regular expression; see <xref linkend="functions-similarto-regexp"/>. The first form has been specified since SQL:2003; the second form was only in SQL:1999 and should be considered obsolete. SQL正規表現にマッチする最初の部分文字列を返します。9.7.2を参照してください。 最初の形式はSQL:2003以降で指定されています。2番目の形式はSQL:1999でのみ指定されており、廃れていると考えるべきでしょう。

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

trim ( [ LEADING | TRAILING | BOTH ] [ characters text ] FROM string text ) → text

Removes the longest string containing only characters in <parameter>characters</parameter> (a space by default) from the start, end, or both ends (<literal>BOTH</literal> is the default) of <parameter>string</parameter>. stringからcharacters(空白一文字がデフォルト)に現れる文字のみを含む最長の文字列を先頭、末尾、あるいはその両方(BOTHがデフォルト)から取り除きます。

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

trim ( [ LEADING | TRAILING | BOTH ] [ FROM ] string text [, characters text ] ) → text

This is a non-standard syntax for <function>trim()</function>. これはtrim()の非標準構文です。

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

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 in <xref linkend="functions-string-other"/>. (Some of these are used internally to implement the <acronym>SQL</acronym>-standard string functions listed in <xref linkend="functions-string-sql"/>.) There are also pattern-matching operators, which are described in <xref linkend="functions-matching"/>, and operators for full-text search, which are described in <xref linkend="textsearch"/>. この他、表 9.10に列挙する文字列操作関数と演算子が使えます。 (そのいくつかは、表 9.9で列挙した標準SQLの文字列関数を実装するため、内部的に使用されます。) また、9.7で説明するしたパターンマッチ演算子と、第12章で説明する全文検索用の演算子もあります。

表9.10 その他の文字列操作関数と演算子

<title>Other String Functions and Operators</title>

Function/Operator 関数/演算子

Description 説明

Example(s)

text ^@ textboolean

Returns true if the first string starts with the second string (equivalent to the <function>starts_with()</function> function). 最初の文字列が2番目の文字列で始まる場合に真を返します(starts_with()関数と同じです)。

'alphabet' ^@ 'alph't

ascii ( text ) → integer

Returns the numeric code of the first character of the argument. In <acronym>UTF8</acronym> encoding, returns the Unicode code point of the character. In other multibyte encodings, the argument must be an <acronym>ASCII</acronym> character. 引数の最初の文字の数値コードを返します。 UTF8符号化方式ではその文字のUnicodeコードポイントを返します。 その他のマルチバイト符号化方式の場合、引数はASCII文字でなくてはなりません。

ascii('x')120

chr ( integer ) → text

Returns the character with the given code. In <acronym>UTF8</acronym> encoding the argument is treated as a Unicode code point. In other multibyte encodings the argument must designate an <acronym>ASCII</acronym> character. <literal>chr(0)</literal> is disallowed because text data types cannot store that character. 与えられたコードの文字を返します。 UTF8符号化方式では、引数はUnicodeコードポイントと見なされます。 その他のマルチバイト符号化方式の場合、引数は指定のASCII文字でなくてはなりません。 chr(0)は禁止されています。テキストデータ型はその文字を格納できないからです。

chr(65)A

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

Concatenates the text representations of all the arguments. NULL arguments are ignored. 引数をテキスト形式にしたものを結合します。 NULL引数は無視されます。

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

concat_ws ( sep text, 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. 最初の引数以外をセパレータとともに結合します。 最初の引数はセパレータ文字列として使われ、NULLにすべきではありません。 それ以外のNULLの引数は無視されます。

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

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

Formats arguments according to a format string; see <xref linkend="functions-string-format"/>. This function is similar to the C function <function>sprintf</function>. 引数の書式をフォーマット文字列に従って整形します。 9.4.1を参照してください。 この関数はC言語関数のsprintfと似ています。

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 ( string text, n integer ) → text

Returns first <parameter>n</parameter> characters in the string, or when <parameter>n</parameter> is negative, returns all but last |<parameter>n</parameter>| characters. 文字列の先頭からn文字を返します。 nが負数の場合、文字列の末尾から|n|文字を切り取った文字列を返します。

left('abcde', 2)ab

length ( text ) → integer

Returns the number of characters in the string. 文字列内の文字数を返します。

length('jose')4

md5 ( text ) → text

Computes the MD5 <link linkend="functions-hash-note">hash</link> of the argument, with the result written in hexadecimal. 引数のMD5ハッシュ計算し、16進数で結果を返します。

md5('abc')900150983cd24fb0​d6963f7d28e17f72

parse_ident ( qualified_identifier text [, strict_mode boolean DEFAULT true ] ) → text[]

Splits <parameter>qualified_identifier</parameter> 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 <literal>false</literal>, 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 <type>name[]</type>. qualified_identifierを識別子の配列に分割し、個々の識別子に引用符があればそれを削除します。 デフォルトでは、最後の識別子の後に続く余分な文字はエラーとされますが、2番目のパラメータがfalseの場合は、そのような余分な文字は無視されます。 (この動作は、関数のようなオブジェクトに対して名前を解析するときに便利でしょう。) この関数は、長すぎる識別子を切り詰めないことに注意してください。 切り詰めが必要なときは、その結果をname[]にキャストすることができます。

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 an <acronym>SQL</acronym> 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 <xref linkend="plpgsql-quote-literal-example"/>. 与えられた文字列を、SQL問い合わせ文字列で識別子として使用できるように、適切な引用符を付けて返します。 引用符は、必要な場合(すなわち、文字列に識別子として使用できない文字が含まれる場合や、大文字変換される場合)にのみ追加されます。 埋め込まれた引用符は、適切に二重化されます。 例 43.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 an <acronym>SQL</acronym> statement string. Embedded single-quotes and backslashes are properly doubled. Note that <function>quote_literal</function> returns null on null input; if the argument might be null, <function>quote_nullable</function> is often more suitable. See also <xref linkend="plpgsql-quote-literal-example"/>. 与えられた文字列を、SQL問い合わせ文字列で文字リテラルとして使用できるように、適切な引用符を付けて返します。 埋め込まれた単一引用符およびバックスラッシュは、適切に二重化されます。 quote_literalはNULL入力に対してNULLを返すことに注意してください。引数がNULLとなる可能性がある場合、よりquote_nullableの方がしばしば適しています。 例 43.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 an <acronym>SQL</acronym> statement string; or, if the argument is null, returns <literal>NULL</literal>. Embedded single-quotes and backslashes are properly doubled. See also <xref linkend="plpgsql-quote-literal-example"/>. 与えられた文字列を、SQL問い合わせ文字列で文字列リテラルとして使用できるように、適切な引用符を付けて返します。 また、引数がNULLの場合、NULLを返します。 埋め込まれた単一引用符およびバックスラッシュは適切に二重化されます。 例 43.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, returns <literal>NULL</literal>. Embedded single-quotes and backslashes are properly doubled. 与えられた値をテキストに変換し、そしてリテラルとして引用符付けします。引数がNULLの場合はNULLを返します。 埋め込まれた単一引用符とバックスラッシュは適切に二重化されます。

quote_nullable(42.5)'42.5'

regexp_count ( string text, pattern text [, start integer [, flags text ] ] ) → integer

Returns the number of times the POSIX regular expression <parameter>pattern</parameter> matches in the <parameter>string</parameter>; see <xref linkend="functions-posix-regexp"/>. stringに対してPOSIX正規表現patternがマッチした回数を返します。9.7.3を参照してください。

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

regexp_instr ( string text, pattern text [, start integer [, N integer [, endoption integer [, flags text [, subexpr integer ] ] ] ] ] ) → integer

Returns the position within <parameter>string</parameter> where the <parameter>N</parameter>'th match of the POSIX regular expression <parameter>pattern</parameter> occurs, or zero if there is no such match; see <xref linkend="functions-posix-regexp"/>. POSIX正規表現patternN番目の一致が発生するstring内の位置を返します。一致がない場合は0を返します。9.7.3を参照してください。

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

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

regexp_like ( string text, pattern text [, flags text ] ) → boolean

Checks whether a match of the POSIX regular expression <parameter>pattern</parameter> occurs within <parameter>string</parameter>; see <xref linkend="functions-posix-regexp"/>. POSIX正規表現patternの一致がstring内にあるかどうかをチェックします。9.7.3を参照してください。

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

regexp_match ( string text, pattern text [, flags text ] ) → text[]

Returns substrings within the first match of the POSIX regular expression <parameter>pattern</parameter> to the <parameter>string</parameter>; see <xref linkend="functions-posix-regexp"/>. stringに対してPOSIX正規表現patternで最初にマッチした部分文字列を返します。より詳細は9.7.3を参照してください。

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

regexp_matches ( string text, pattern text [, flags text ] ) → setof text[]

Returns substrings within the first match of the POSIX regular expression <parameter>pattern</parameter> to the <parameter>string</parameter>, or substrings within all such matches if the <literal>g</literal> flag is used; see <xref linkend="functions-posix-regexp"/>. stringに対してPOSIX正規表現patternで最初にマッチした部分文字列、あるいはgフラグが設定されている場合には、一致したすべての部分文字列を返します。より詳細は9.7.3を参照してください。

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

 {bar}
 {baz}

regexp_replace ( string text, pattern text, replacement text [, start integer ] [, flags text ] ) → text

Replaces the substring that is the first match to the POSIX regular expression <parameter>pattern</parameter>, or all such matches if the <literal>g</literal> flag is used; see <xref linkend="functions-posix-regexp"/>. stringに対してPOSIX正規表現patternで最初の一致、あるいはgが指定された場合にはすべての一致の結果部分文字列を返します。9.7.3を参照してください。

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

regexp_replace ( string text, pattern text, replacement text, start integer, N integer [, flags text ] ) → text

Replaces the substring that is the <parameter>N</parameter>'th match to the POSIX regular expression <parameter>pattern</parameter>, or all such matches if <parameter>N</parameter> is zero; see <xref linkend="functions-posix-regexp"/>. POSIX正規表現patternN番目に一致する部分文字列、またはNが0の場合にすべて一致する部分文字列を置き換えます。9.7.3を参照してください。

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

regexp_split_to_array ( string text, pattern text [, flags text ] ) → text[]

Splits <parameter>string</parameter> using a POSIX regular expression as the delimiter, producing an array of results; see <xref linkend="functions-posix-regexp"/>. POSIX正規表現を区切り文字に使ってstringを分割し、結果の配列を生成します。 9.7.3を参照してください。

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

regexp_split_to_table ( string text, pattern text [, flags text ] ) → setof text

Splits <parameter>string</parameter> using a POSIX regular expression as the delimiter, producing a set of results; see <xref linkend="functions-posix-regexp"/>. POSIX正規表現を区切り文字に使ってstringを分割します。 詳しくは9.7.3を参照してください。

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

 hello
 world

regexp_substr ( string text, pattern text [, start integer [, N integer [, flags text [, subexpr integer ] ] ] ] ) → text

Returns the substring within <parameter>string</parameter> that matches the <parameter>N</parameter>'th occurrence of the POSIX regular expression <parameter>pattern</parameter>, or <literal>NULL</literal> if there is no such match; see <xref linkend="functions-posix-regexp"/>. POSIX正規表現patternN番目に一致するstring内の部分文字列を返します。一致しない場合はNULLを返します。 9.7.3を参照してください。

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

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

repeat ( string text, number integer ) → text

Repeats <parameter>string</parameter> the specified <parameter>number</parameter> of times. 指定されたnumberの数だけstringを繰り返します。

repeat('Pg', 4)PgPgPgPg

replace ( string text, from text, to text ) → text

Replaces all occurrences in <parameter>string</parameter> of substring <parameter>from</parameter> with substring <parameter>to</parameter>. stringに出現する全てのfrom部分文字列をto部分文字列に置換します。

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

reverse ( text ) → text

Reverses the order of the characters in the string. 文字列中の文字を逆順にします。

reverse('abcde')edcba

right ( string text, n integer ) → text

Returns last <parameter>n</parameter> characters in the string, or when <parameter>n</parameter> is negative, returns all but first |<parameter>n</parameter>| characters. 文字列の末尾からn文字を返します。 nが負数の場合は、文字列の先頭から|n|文字だけ切り取った文字列を返します。

right('abcde', 2)de

split_part ( string text, delimiter text, n integer ) → text

Splits <parameter>string</parameter> at occurrences of <parameter>delimiter</parameter> and returns the <parameter>n</parameter>'th field (counting from one), or when <parameter>n</parameter> is negative, returns the |<parameter>n</parameter>|'th-from-last field. stringdelimiterで分割し、その結果からn番目のフィールド(1から始まるように数える)を返します。 nが負なら最後から|n|番目のフィールドを返します。

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

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

starts_with ( string text, prefix text ) → boolean

Returns true if <parameter>string</parameter> starts with <parameter>prefix</parameter>. stringprefixで始まっていれば真を返します。

starts_with('alphabet', 'alph')t

string_to_array ( string text, delimiter text [, null_string text ] ) → text[]

Splits the <parameter>string</parameter> at occurrences of <parameter>delimiter</parameter> and forms the resulting fields into a <type>text</type> array. If <parameter>delimiter</parameter> is <literal>NULL</literal>, each character in the <parameter>string</parameter> will become a separate element in the array. If <parameter>delimiter</parameter> is an empty string, then the <parameter>string</parameter> is treated as a single field. If <parameter>null_string</parameter> is supplied and is not <literal>NULL</literal>, fields matching that string are replaced by <literal>NULL</literal>. See also <link linkend="function-array-to-string"><function>array_to_string</function></link>. stringdelimiterで区切り、結果のフィールドをtext配列に格納します。 delimiterNULLなら、stringの各文字が配列の別々の要素になります。 delimiterが空文字なら、stringは単一のフィールドとして扱われます。 null_stringが指定され、NULLでなければ、その文字列にマッチするフィールドはNULLで置き換えられます。 array_to_stringも参照してください。

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

string_to_table ( string text, delimiter text [, null_string text ] ) → setof text

Splits the <parameter>string</parameter> at occurrences of <parameter>delimiter</parameter> and returns the resulting fields as a set of <type>text</type> rows. If <parameter>delimiter</parameter> is <literal>NULL</literal>, each character in the <parameter>string</parameter> will become a separate row of the result. If <parameter>delimiter</parameter> is an empty string, then the <parameter>string</parameter> is treated as a single field. If <parameter>null_string</parameter> is supplied and is not <literal>NULL</literal>, fields matching that string are replaced by <literal>NULL</literal>. stringdelimiterで区切り、結果のフィールドをtextの行集合として返します。 delimiterNULLなら、結果はstringの各文字が別々の行になります。 delimiterが空文字なら、stringは単一のフィールドとして扱われます。 null_stringが指定され、NULLでなければ、その文字列にマッチするフィールドはNULLで置き換えられます。

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

 xx
 NULL
 zz

strpos ( string text, substring text ) → integer

Returns first starting index of the specified <parameter>substring</parameter> within <parameter>string</parameter>, or zero if it's not present. (Same as <literal>position(<parameter>substring</parameter> in <parameter>string</parameter>)</literal>, but note the reversed argument order.) string中の指定したsubstringの最初の開始位置を返します。substringが存在しなければゼロを返します。 (position(substring in string)と同じですが、引数の順序が逆であることに注意してください。)

strpos('high', 'ig')2

substr ( string text, start integer [, count integer ] ) → text

Extracts the substring of <parameter>string</parameter> starting at the <parameter>start</parameter>'th character, and extending for <parameter>count</parameter> characters if that is specified. (Same as <literal>substring(<parameter>string</parameter> from <parameter>start</parameter> for <parameter>count</parameter>)</literal>.) stringstart番目の文字から始まり、指定されている場合はcount文字だけ連続したが部分文字列を取り出します(substring(string from from for count)と同じです)。

substr('alphabet', 3)phabet

substr('alphabet', 3, 2)ph

to_ascii ( string text ) → text

to_ascii ( string text, encoding name ) → text

to_ascii ( string text, encoding integer ) → text

Converts <parameter>string</parameter> to <acronym>ASCII</acronym> from another encoding, which may be identified by name or number. If <parameter>encoding</parameter> 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 <literal>LATIN1</literal>, <literal>LATIN2</literal>, <literal>LATIN9</literal>, and <literal>WIN1250</literal> encodings. (See the <xref linkend="unaccent"/> module for another, more flexible solution.) stringを他の名前あるいは数で指定される符号化方式から、ASCIIに変換します。 encodingが省略されるとデータベースの符号化方式を指定したと見なします(これは実用的には唯一有用なケースです。) この変換は主にアクセントを削除するのが目的です。 LATIN1LATIN2LATIN9WIN1250符号化方式からの変換のみをサポートします。 (他のより柔軟な解決方法としては、unaccentモジュールを参照してください。)

to_ascii('Karél')Karel

to_hex ( integer ) → text

to_hex ( bigint ) → text

Converts the number to its equivalent hexadecimal representation. 数を同等の16進数表現に変換します。

to_hex(2147483647)7fffffff

translate ( string text, from text, to text ) → text

Replaces each character in <parameter>string</parameter> that matches a character in the <parameter>from</parameter> set with the corresponding character in the <parameter>to</parameter> set. If <parameter>from</parameter> is longer than <parameter>to</parameter>, occurrences of the extra characters in <parameter>from</parameter> are deleted. from集合内の文字と一致するstringにある全ての文字は、to集合内のそれに対応する文字に置き換えられます。 もしfromtoより長い場合、fromで指定される余分な文字に一致するものは削除されます。

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

unistr ( text ) → text

Evaluate escaped Unicode characters in the argument. Unicode characters can be specified as <literal>\<replaceable>XXXX</replaceable></literal> (4 hexadecimal digits), <literal>\+<replaceable>XXXXXX</replaceable></literal> (6 hexadecimal digits), <literal>\u<replaceable>XXXX</replaceable></literal> (4 hexadecimal digits), or <literal>\U<replaceable>XXXXXXXX</replaceable></literal> (8 hexadecimal digits). To specify a backslash, write two backslashes. All other characters are taken literally. 引数のエスケープされたUnicode文字を評価します。 Unicode文字は、\XXXX (16進4桁)、\+XXXXXX (16進6桁)、\uXXXX (16進4桁)、\UXXXXXXXX(16進8桁)で指定できます。 バックスラッシュを指定するには、2つのバックスラッシュを書きます。 それ以外の文字はそのまま扱われます。

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. サーバのエンコーディングがUTF-8でなければ、これらのエスケープシーケンスで指定されるUnicodeコードポイントがサーバの実際のエンコーディングに変換されます。 変換不可能ならばエラーが報告されます。

This function provides a (non-standard) alternative to string constants with Unicode escapes (see <xref linkend="sql-syntax-strings-uescape"/>). この関数はUnicodeエスケープシーケンス(4.1.2.3参照)に対する(非標準の)代替を提供します。

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

unistr('d\u0061t\U00000061')data


The <function>concat</function>, <function>concat_ws</function> and <function>format</function> functions are variadic, so it is possible to pass the values to be concatenated or formatted as an array marked with the <literal>VARIADIC</literal> keyword (see <xref linkend="xfunc-sql-variadic-functions"/>). The array's elements are treated as if they were separate ordinary arguments to the function. If the variadic array argument is NULL, <function>concat</function> and <function>concat_ws</function> return NULL, but <function>format</function> treats a NULL as a zero-element array. concatconcat_wsおよびformat関数はVariadicです。従って、キーワードVARIADICで標しをつけられた配列のように、値を連結またはフォーマットした形で受け渡すことが可能です(38.5.6を参照してください)。 配列の要素は関数に対して分割された通常の引数のように扱われます。 もしvariadic配列引数がNULLであれば、concatおよびconcat_wsはNULLを返しますが、formatはNULLを要素を持たない配列と扱います。

See also the aggregate function <function>string_agg</function> in <xref linkend="functions-aggregate"/>, and the functions for converting between strings and the <type>bytea</type> type in <xref linkend="functions-binarystring-conversions"/>. 9.21内のstring_agg集約関数と、文字列とbytea型を変換するための表 9.13内の関数も参照してください。

9.4.1. format #

The function <function>format</function> produces output formatted according to a format string, in a style similar to the C function <function>sprintf</function>. 関数formatは、C関数のsprintf同様の形式で、フォーマット文字列に従ってフォーマットされた出力を生成します。

format(formatstr text [, formatarg "any" [, ...] ])

<parameter>formatstr</parameter> is a format string that specifies how the result should be formatted. Text in the format string is copied directly to the result, except where <firstterm>format specifiers</firstterm> are used. Format specifiers act as placeholders in the string, defining how subsequent function arguments should be formatted and inserted into the result. Each <parameter>formatarg</parameter> 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). formatstrは結果がどのようにフォーマットされるかを指定するフォーマット文字列です。 フォーマット指示子が使用されている箇所を除き、フォーマット文字列のテキストは結果に直接コピーされます。 フォーマット指示子は文字列中のプレースホルダとして振舞い、その後に引き続く関数引数がどのようにフォーマットされ、どのように結果に挿入されるかを定義します。 それぞれのformatarg引数はそのデータ型に対する通常の出力規定に従ってテキストに変換され、その後フォーマット指示子に従って、結果文字列に挿入されます。

Format specifiers are introduced by a <literal>%</literal> character and have the form フォーマット指示子は%文字で始まり、以下の形式をとります。

%[position][flags][width]type

where the component fields are: ここで要素フィールドとは以下になっています。

position (省略可能)

A string of the form <literal><parameter>n</parameter>$</literal> where <parameter>n</parameter> is the index of the argument to print. Index 1 means the first argument after <parameter>formatstr</parameter>. If the <parameter>position</parameter> is omitted, the default is to use the next argument in sequence. n$の形式の文字列で、nは出力する引数のインデックスです。 インデックス1はformatstrの後の最初の引数です。 positionが省略されると、一連の中の次の引数がデフォルトとして使用されます。

flags (省略可能)

Additional options controlling how the format specifier's output is formatted. Currently the only supported flag is a minus sign (<literal>-</literal>) which will cause the format specifier's output to be left-justified. This has no effect unless the <parameter>width</parameter> field is also specified. フォーマット指示子の出力がどのようにフォーマットされるかを制御する追加の任意の要素です。 現在、サポートされているflagはマイナス記号(-)のみで、フォーマット指示子の出力が左詰めになるようにします。 これはwidthフィールドが同時に指定されていない場合は効果がありません。

width (省略可能)

Specifies the <emphasis>minimum</emphasis> number of characters to use to display the format specifier's output. The output is padded on the left or right (depending on the <literal>-</literal> 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 (<literal>*</literal>) to use the next function argument as the width; or a string of the form <literal>*<parameter>n</parameter>$</literal> to use the <parameter>n</parameter>th function argument as the width. フォーマット指示子の出力を表示する最小文字数を指定します。 出力は、幅を満たすのに必要な空白が左または右(flagの-による)に埋め込まれます。 幅が小さすぎても出力が切り詰められることはなく、単に無視されます。 幅は次のいずれかでも指定できます。それらは、正の整数、幅としての次の関数引数として使用する星印 (*)、またはn番目の関数引数を幅として使用する*n$という形式の文字列です。

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 <literal>-</literal> flag had been specified) within a field of length <function>abs</function>(<parameter>width</parameter>). 幅を関数引数から取得する場合、その引数はフォーマット指示子の値に使用される引数より先に消費されます。 幅の引数が負の場合、フィールド長abs(width)の範囲内で結果は(あたかもflagで-が指定されたように)左詰めになります。

type (必須)

The type of format conversion to use to produce the format specifier's output. The following types are supported: フォーマット指示子の出力を生成するのに使用されるフォーマット変換の型。 以下の型がサポートされています。

  • <literal>s</literal> formats the argument value as a simple string. A null value is treated as an empty string. sは引数の値を単純文字列にフォーマットします。 NULL値は空文字列として扱われます。

  • <literal>I</literal> treats the argument value as an SQL identifier, double-quoting it if necessary. It is an error for the value to be null (equivalent to <function>quote_ident</function>). Iは、引数をSQLの識別子として取り扱い、必要ならそれを二重引用符で括ります。 NULL値はエラーです(quote_identと同等です)。

  • <literal>L</literal> quotes the argument value as an SQL literal. A null value is displayed as the string <literal>NULL</literal>, without quotes (equivalent to <function>quote_nullable</function>). Lは引数値をSQLリテラルとして引用符が付けられます。 NULL値は引用符無しの文字列NULLとなります(quote_nullableと同等です)。

In addition to the format specifiers described above, the special sequence <literal>%%</literal> may be used to output a literal <literal>%</literal> character. 上記で説明したフォーマット指示子に加え、特別の並びの%%がリテラル%文字を出力するために使用することもできます。

Here are some examples of the basic format conversions: 基本的なフォーマット変換の例を幾つか下記に紹介します。

SELECT format('Hello %s', 'World');
Result: Hello World

SELECT 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 using <parameter>width</parameter> fields and the <literal>-</literal> flag: widthフィールドと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 of <parameter>position</parameter> fields: 以下の例はpositionフィールドの使い方を示しています。

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

SELECT format('|%*2$s|', 'foo', 10, 'bar');
Result: |       bar|

SELECT format('|%1$*2$s|', 'foo', 10, 'bar');
Result: |       foo|

Unlike the standard C function <function>sprintf</function>, <productname>PostgreSQL</productname>'s <function>format</function> function allows format specifiers with and without <parameter>position</parameter> fields to be mixed in the same format string. A format specifier without a <parameter>position</parameter> field always uses the next argument after the last argument consumed. In addition, the <function>format</function> function does not require all function arguments to be used in the format string. For example: 標準C関数sprintfとは違って、PostgreSQLformat関数は、同一のフォーマット文字列の中でpositionフィールドがあるフォーマット指示子と、それがないフォーマット指示子の混在を許容します。 positionフィールドが無いフォーマット指示子は常に最終の引数が消費された後に次の引数を使用します。 さらに、format関数はフォーマット文字列で使用されるべき全ての関数引数を要求しません。 例を示します。

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

The <literal>%I</literal> and <literal>%L</literal> format specifiers are particularly useful for safely constructing dynamic SQL statements. See <xref linkend="plpgsql-quote-literal-example"/>. %I および %Lのフォーマット指示子は特に動的SQL命令を安全に構築する場合に便利です。 例 43.1を参照してください。