2 9.4. String Functions and Operators #
6 This section describes functions and operators for examining and
7 manipulating string values. Strings in this context include values of
8 the types character, character varying, and text. Except where noted,
9 these functions and operators are declared to accept and return type
10 text. They will interchangeably accept character varying arguments.
11 Values of type character will be converted to text before the function
12 or operator is applied, resulting in stripping any trailing spaces in
15 SQL defines some string functions that use key words, rather than
16 commas, to separate arguments. Details are in Table 9.9. PostgreSQL
17 also provides versions of these functions that use the regular function
18 invocation syntax (see Table 9.10).
22 The string concatenation operator (||) will accept non-string input, so
23 long as at least one input is of string type, as shown in Table 9.9.
24 For other cases, inserting an explicit coercion to text can be used to
25 have non-string input accepted.
27 Table 9.9. SQL String Functions and Operators
37 Concatenates the two strings.
39 'Post' || 'greSQL' → PostgreSQL
41 text || anynonarray → text
43 anynonarray || text → text
45 Converts the non-string input to text, then concatenates the two
46 strings. (The non-string input cannot be of an array type, because that
47 would create ambiguity with the array || operators. If you want to
48 concatenate an array's text equivalent, cast it to text explicitly.)
50 'Value: ' || 42 → Value: 42
52 btrim ( string text [, characters text ] ) → text
54 Removes the longest string containing only characters in characters (a
55 space by default) from the start and end of string.
57 btrim('xyxtrimyyx', 'xyz') → trim
59 text IS [NOT] [form] NORMALIZED → boolean
61 Checks whether the string is in the specified Unicode normalization
62 form. The optional form key word specifies the form: NFC (the default),
63 NFD, NFKC, or NFKD. This expression can only be used when the server
64 encoding is UTF8. Note that checking for normalization using this
65 expression is often faster than normalizing possibly already normalized
68 U&'\0061\0308bc' IS NFD NORMALIZED → t
70 bit_length ( text ) → integer
72 Returns number of bits in the string (8 times the octet_length).
74 bit_length('jose') → 32
76 char_length ( text ) → integer
78 character_length ( text ) → integer
80 Returns number of characters in the string.
82 char_length('josé') → 4
86 Converts the string to all lower case, according to the rules of the
91 lpad ( string text, length integer [, fill text ] ) → text
93 Extends the string to length length by prepending the characters fill
94 (a space by default). If the string is already longer than length then
95 it is truncated (on the right).
97 lpad('hi', 5, 'xy') → xyxhi
99 ltrim ( string text [, characters text ] ) → text
101 Removes the longest string containing only characters in characters (a
102 space by default) from the start of string.
104 ltrim('zzzytest', 'xyz') → test
106 normalize ( text [, form ] ) → text
108 Converts the string to the specified Unicode normalization form. The
109 optional form key word specifies the form: NFC (the default), NFD,
110 NFKC, or NFKD. This function can only be used when the server encoding
113 normalize(U&'\0061\0308bc', NFC) → U&'\00E4bc'
115 octet_length ( text ) → integer
117 Returns number of bytes in the string.
119 octet_length('josé') → 5 (if server encoding is UTF8)
121 octet_length ( character ) → integer
123 Returns number of bytes in the string. Since this version of the
124 function accepts type character directly, it will not strip trailing
127 octet_length('abc '::character(4)) → 4
129 overlay ( string text PLACING newsubstring text FROM start integer [
130 FOR count integer ] ) → text
132 Replaces the substring of string that starts at the start'th character
133 and extends for count characters with newsubstring. If count is
134 omitted, it defaults to the length of newsubstring.
136 overlay('Txxxxas' placing 'hom' from 2 for 4) → Thomas
138 position ( substring text IN string text ) → integer
140 Returns first starting index of the specified substring within string,
141 or zero if it's not present.
143 position('om' in 'Thomas') → 3
145 rpad ( string text, length integer [, fill text ] ) → text
147 Extends the string to length length by appending the characters fill (a
148 space by default). If the string is already longer than length then it
151 rpad('hi', 5, 'xy') → hixyx
153 rtrim ( string text [, characters text ] ) → text
155 Removes the longest string containing only characters in characters (a
156 space by default) from the end of string.
158 rtrim('testxxzx', 'xyz') → test
160 substring ( string text [ FROM start integer ] [ FOR count integer ] )
163 Extracts the substring of string starting at the start'th character if
164 that is specified, and stopping after count characters if that is
165 specified. Provide at least one of start and count.
167 substring('Thomas' from 2 for 3) → hom
169 substring('Thomas' from 3) → omas
171 substring('Thomas' for 2) → Th
173 substring ( string text FROM pattern text ) → text
175 Extracts the first substring matching POSIX regular expression; see
178 substring('Thomas' from '...$') → mas
180 substring ( string text SIMILAR pattern text ESCAPE escape text ) →
183 substring ( string text FROM pattern text FOR escape text ) → text
185 Extracts the first substring matching SQL regular expression; see
186 Section 9.7.2. The first form has been specified since SQL:2003; the
187 second form was only in SQL:1999 and should be considered obsolete.
189 substring('Thomas' similar '%#"o_a#"_' escape '#') → oma
191 trim ( [ LEADING | TRAILING | BOTH ] [ characters text ] FROM string
194 Removes the longest string containing only characters in characters (a
195 space by default) from the start, end, or both ends (BOTH is the
198 trim(both 'xyz' from 'yxTomxx') → Tom
200 trim ( [ LEADING | TRAILING | BOTH ] [ FROM ] string text [, characters
203 This is a non-standard syntax for trim().
205 trim(both from 'yxTomxx', 'xyz') → Tom
207 unicode_assigned ( text ) → boolean
209 Returns true if all characters in the string are assigned Unicode
210 codepoints; false otherwise. This function can only be used when the
211 server encoding is UTF8.
213 upper ( text ) → text
215 Converts the string to all upper case, according to the rules of the
220 Additional string manipulation functions and operators are available
221 and are listed in Table 9.10. (Some of these are used internally to
222 implement the SQL-standard string functions listed in Table 9.9.) There
223 are also pattern-matching operators, which are described in
224 Section 9.7, and operators for full-text search, which are described in
227 Table 9.10. Other String Functions and Operators
235 text ^@ text → boolean
237 Returns true if the first string starts with the second string
238 (equivalent to the starts_with() function).
240 'alphabet' ^@ 'alph' → t
242 ascii ( text ) → integer
244 Returns the numeric code of the first character of the argument. In
245 UTF8 encoding, returns the Unicode code point of the character. In
246 other multibyte encodings, the argument must be an ASCII character.
250 chr ( integer ) → text
252 Returns the character with the given code. In UTF8 encoding the
253 argument is treated as a Unicode code point. In other multibyte
254 encodings the argument must designate an ASCII character. chr(0) is
255 disallowed because text data types cannot store that character.
259 concat ( val1 "any" [, val2 "any" [, ...] ] ) → text
261 Concatenates the text representations of all the arguments. NULL
262 arguments are ignored.
264 concat('abcde', 2, NULL, 22) → abcde222
266 concat_ws ( sep text, val1 "any" [, val2 "any" [, ...] ] ) → text
268 Concatenates all but the first argument, with separators. The first
269 argument is used as the separator string, and should not be NULL. Other
270 NULL arguments are ignored.
272 concat_ws(',', 'abcde', 2, NULL, 22) → abcde,2,22
274 format ( formatstr text [, formatarg "any" [, ...] ] ) → text
276 Formats arguments according to a format string; see Section 9.4.1. This
277 function is similar to the C function sprintf.
279 format('Hello %s, %1$s', 'World') → Hello World, World
281 initcap ( text ) → text
283 Converts the first letter of each word to upper case and the rest to
284 lower case. Words are sequences of alphanumeric characters separated by
285 non-alphanumeric characters.
287 initcap('hi THOMAS') → Hi Thomas
289 casefold ( text ) → text
291 Performs case folding of the input string according to the collation.
292 Case folding is similar to case conversion, but the purpose of case
293 folding is to facilitate case-insensitive matching of strings, whereas
294 the purpose of case conversion is to convert to a particular cased
295 form. This function can only be used when the server encoding is UTF8.
297 Ordinarily, case folding simply converts to lowercase, but there may be
298 exceptions depending on the collation. For instance, some characters
299 have more than two lowercase variants, or fold to uppercase.
301 Case folding may change the length of the string. For instance, in the
302 PG_UNICODE_FAST collation, ß (U+00DF) folds to ss.
304 casefold can be used for Unicode Default Caseless Matching. It does not
305 always preserve the normalized form of the input string (see
308 The libc provider doesn't support case folding, so casefold is
311 left ( string text, n integer ) → text
313 Returns first n characters in the string, or when n is negative,
314 returns all but last |n| characters.
316 left('abcde', 2) → ab
318 length ( text ) → integer
320 Returns the number of characters in the string.
326 Computes the MD5 hash of the argument, with the result written in
329 md5('abc') → 900150983cd24fb0d6963f7d28e17f72
331 parse_ident ( qualified_identifier text [, strict_mode boolean DEFAULT
334 Splits qualified_identifier into an array of identifiers, removing any
335 quoting of individual identifiers. By default, extra characters after
336 the last identifier are considered an error; but if the second
337 parameter is false, then such extra characters are ignored. (This
338 behavior is useful for parsing names for objects like functions.) Note
339 that this function does not truncate over-length identifiers. If you
340 want truncation you can cast the result to name[].
342 parse_ident('"SomeSchema".someTable') → {SomeSchema,sometable}
344 pg_client_encoding ( ) → name
346 Returns current client encoding name.
348 pg_client_encoding() → UTF8
350 quote_ident ( text ) → text
352 Returns the given string suitably quoted to be used as an identifier in
353 an SQL statement string. Quotes are added only if necessary (i.e., if
354 the string contains non-identifier characters or would be case-folded).
355 Embedded quotes are properly doubled. See also Example 41.1.
357 quote_ident('Foo bar') → "Foo bar"
359 quote_literal ( text ) → text
361 Returns the given string suitably quoted to be used as a string literal
362 in an SQL statement string. Embedded single-quotes and backslashes are
363 properly doubled. Note that quote_literal returns null on null input;
364 if the argument might be null, quote_nullable is often more suitable.
365 See also Example 41.1.
367 quote_literal(E'O\'Reilly') → 'O''Reilly'
369 quote_literal ( anyelement ) → text
371 Converts the given value to text and then quotes it as a literal.
372 Embedded single-quotes and backslashes are properly doubled.
374 quote_literal(42.5) → '42.5'
376 quote_nullable ( text ) → text
378 Returns the given string suitably quoted to be used as a string literal
379 in an SQL statement string; or, if the argument is null, returns NULL.
380 Embedded single-quotes and backslashes are properly doubled. See also
383 quote_nullable(NULL) → NULL
385 quote_nullable ( anyelement ) → text
387 Converts the given value to text and then quotes it as a literal; or,
388 if the argument is null, returns NULL. Embedded single-quotes and
389 backslashes are properly doubled.
391 quote_nullable(42.5) → '42.5'
393 regexp_count ( string text, pattern text [, start integer [, flags text
396 Returns the number of times the POSIX regular expression pattern
397 matches in the string; see Section 9.7.3.
399 regexp_count('123456789012', '\d\d\d', 2) → 3
401 regexp_instr ( string text, pattern text [, start integer [, N integer
402 [, endoption integer [, flags text [, subexpr integer ] ] ] ] ] ) →
405 Returns the position within string where the N'th match of the POSIX
406 regular expression pattern occurs, or zero if there is no such match;
409 regexp_instr('ABCDEF', 'c(.)(..)', 1, 1, 0, 'i') → 3
411 regexp_instr('ABCDEF', 'c(.)(..)', 1, 1, 0, 'i', 2) → 5
413 regexp_like ( string text, pattern text [, flags text ] ) → boolean
415 Checks whether a match of the POSIX regular expression pattern occurs
416 within string; see Section 9.7.3.
418 regexp_like('Hello World', 'world$', 'i') → t
420 regexp_match ( string text, pattern text [, flags text ] ) → text[]
422 Returns substrings within the first match of the POSIX regular
423 expression pattern to the string; see Section 9.7.3.
425 regexp_match('foobarbequebaz', '(bar)(beque)') → {bar,beque}
427 regexp_matches ( string text, pattern text [, flags text ] ) → setof
430 Returns substrings within the first match of the POSIX regular
431 expression pattern to the string, or substrings within all such matches
432 if the g flag is used; see Section 9.7.3.
434 regexp_matches('foobarbequebaz', 'ba.', 'g') →
438 regexp_replace ( string text, pattern text, replacement text [, flags
441 Replaces the substring that is the first match to the POSIX regular
442 expression pattern, or all such matches if the g flag is used; see
445 regexp_replace('Thomas', '.[mN]a.', 'M') → ThM
447 regexp_replace ( string text, pattern text, replacement text, start
448 integer [, N integer [, flags text ] ] ) → text
450 Replaces the substring that is the N'th match to the POSIX regular
451 expression pattern, or all such matches if N is zero, with the search
452 beginning at the start'th character of string. If N is omitted, it
453 defaults to 1. See Section 9.7.3.
455 regexp_replace('Thomas', '.', 'X', 3, 2) → ThoXas
457 regexp_replace(string=>'hello world', pattern=>'l', replacement=>'XX',
458 start=>1, "N"=>2) → helXXo world
460 regexp_split_to_array ( string text, pattern text [, flags text ] ) →
463 Splits string using a POSIX regular expression as the delimiter,
464 producing an array of results; see Section 9.7.3.
466 regexp_split_to_array('hello world', '\s+') → {hello,world}
468 regexp_split_to_table ( string text, pattern text [, flags text ] ) →
471 Splits string using a POSIX regular expression as the delimiter,
472 producing a set of results; see Section 9.7.3.
474 regexp_split_to_table('hello world', '\s+') →
478 regexp_substr ( string text, pattern text [, start integer [, N integer
479 [, flags text [, subexpr integer ] ] ] ] ) → text
481 Returns the substring within string that matches the N'th occurrence of
482 the POSIX regular expression pattern, or NULL if there is no such
483 match; see Section 9.7.3.
485 regexp_substr('ABCDEF', 'c(.)(..)', 1, 1, 'i') → CDEF
487 regexp_substr('ABCDEF', 'c(.)(..)', 1, 1, 'i', 2) → EF
489 repeat ( string text, number integer ) → text
491 Repeats string the specified number of times.
493 repeat('Pg', 4) → PgPgPgPg
495 replace ( string text, from text, to text ) → text
497 Replaces all occurrences in string of substring from with substring to.
499 replace('abcdefabcdef', 'cd', 'XX') → abXXefabXXef
501 reverse ( text ) → text
503 Reverses the order of the characters in the string.
505 reverse('abcde') → edcba
507 right ( string text, n integer ) → text
509 Returns last n characters in the string, or when n is negative, returns
510 all but first |n| characters.
512 right('abcde', 2) → de
514 split_part ( string text, delimiter text, n integer ) → text
516 Splits string at occurrences of delimiter and returns the n'th field
517 (counting from one), or when n is negative, returns the
518 |n|'th-from-last field.
520 split_part('abc~@~def~@~ghi', '~@~', 2) → def
522 split_part('abc,def,ghi,jkl', ',', -2) → ghi
524 starts_with ( string text, prefix text ) → boolean
526 Returns true if string starts with prefix.
528 starts_with('alphabet', 'alph') → t
530 string_to_array ( string text, delimiter text [, null_string text ] ) →
533 Splits the string at occurrences of delimiter and forms the resulting
534 fields into a text array. If delimiter is NULL, each character in the
535 string will become a separate element in the array. If delimiter is an
536 empty string, then the string is treated as a single field. If
537 null_string is supplied and is not NULL, fields matching that string
538 are replaced by NULL. See also array_to_string.
540 string_to_array('xx~~yy~~zz', '~~', 'yy') → {xx,NULL,zz}
542 string_to_table ( string text, delimiter text [, null_string text ] ) →
545 Splits the string at occurrences of delimiter and returns the resulting
546 fields as a set of text rows. If delimiter is NULL, each character in
547 the string will become a separate row of the result. If delimiter is an
548 empty string, then the string is treated as a single field. If
549 null_string is supplied and is not NULL, fields matching that string
550 are replaced by NULL.
552 string_to_table('xx~^~yy~^~zz', '~^~', 'yy') →
557 strpos ( string text, substring text ) → integer
559 Returns first starting index of the specified substring within string,
560 or zero if it's not present. (Same as position(substring in string),
561 but note the reversed argument order.)
563 strpos('high', 'ig') → 2
565 substr ( string text, start integer [, count integer ] ) → text
567 Extracts the substring of string starting at the start'th character,
568 and extending for count characters if that is specified. (Same as
569 substring(string from start for count).)
571 substr('alphabet', 3) → phabet
573 substr('alphabet', 3, 2) → ph
575 to_ascii ( string text ) → text
577 to_ascii ( string text, encoding name ) → text
579 to_ascii ( string text, encoding integer ) → text
581 Converts string to ASCII from another encoding, which may be identified
582 by name or number. If encoding is omitted the database encoding is
583 assumed (which in practice is the only useful case). The conversion
584 consists primarily of dropping accents. Conversion is only supported
585 from LATIN1, LATIN2, LATIN9, and WIN1250 encodings. (See the unaccent
586 module for another, more flexible solution.)
588 to_ascii('Karél') → Karel
590 to_bin ( integer ) → text
592 to_bin ( bigint ) → text
594 Converts the number to its equivalent two's complement binary
597 to_bin(2147483647) → 1111111111111111111111111111111
599 to_bin(-1234) → 11111111111111111111101100101110
601 to_hex ( integer ) → text
603 to_hex ( bigint ) → text
605 Converts the number to its equivalent two's complement hexadecimal
608 to_hex(2147483647) → 7fffffff
610 to_hex(-1234) → fffffb2e
612 to_oct ( integer ) → text
614 to_oct ( bigint ) → text
616 Converts the number to its equivalent two's complement octal
619 to_oct(2147483647) → 17777777777
621 to_oct(-1234) → 37777775456
623 translate ( string text, from text, to text ) → text
625 Replaces each character in string that matches a character in the from
626 set with the corresponding character in the to set. If from is longer
627 than to, occurrences of the extra characters in from are deleted.
629 translate('12345', '143', 'ax') → a2x5
631 unistr ( text ) → text
633 Evaluate escaped Unicode characters in the argument. Unicode characters
634 can be specified as \XXXX (4 hexadecimal digits), \+XXXXXX (6
635 hexadecimal digits), \uXXXX (4 hexadecimal digits), or \UXXXXXXXX (8
636 hexadecimal digits). To specify a backslash, write two backslashes. All
637 other characters are taken literally.
639 If the server encoding is not UTF-8, the Unicode code point identified
640 by one of these escape sequences is converted to the actual server
641 encoding; an error is reported if that's not possible.
643 This function provides a (non-standard) alternative to string constants
644 with Unicode escapes (see Section 4.1.2.3).
646 unistr('d\0061t\+000061') → data
648 unistr('d\u0061t\U00000061') → data
650 The concat, concat_ws and format functions are variadic, so it is
651 possible to pass the values to be concatenated or formatted as an array
652 marked with the VARIADIC keyword (see Section 36.5.6). The array's
653 elements are treated as if they were separate ordinary arguments to the
654 function. If the variadic array argument is NULL, concat and concat_ws
655 return NULL, but format treats a NULL as a zero-element array.
657 See also the aggregate function string_agg in Section 9.21, and the
658 functions for converting between strings and the bytea type in
663 The function format produces output formatted according to a format
664 string, in a style similar to the C function sprintf.
666 format(formatstr text [, formatarg "any" [, ...] ])
668 formatstr is a format string that specifies how the result should be
669 formatted. Text in the format string is copied directly to the result,
670 except where format specifiers are used. Format specifiers act as
671 placeholders in the string, defining how subsequent function arguments
672 should be formatted and inserted into the result. Each formatarg
673 argument is converted to text according to the usual output rules for
674 its data type, and then formatted and inserted into the result string
675 according to the format specifier(s).
677 Format specifiers are introduced by a % character and have the form
678 %[position][flags][width]type
680 where the component fields are:
683 A string of the form n$ where n is the index of the argument to
684 print. Index 1 means the first argument after formatstr. If the
685 position is omitted, the default is to use the next argument in
689 Additional options controlling how the format specifier's output
690 is formatted. Currently the only supported flag is a minus sign
691 (-) which will cause the format specifier's output to be
692 left-justified. This has no effect unless the width field is
696 Specifies the minimum number of characters to use to display the
697 format specifier's output. The output is padded on the left or
698 right (depending on the - flag) with spaces as needed to fill
699 the width. A too-small width does not cause truncation of the
700 output, but is simply ignored. The width may be specified using
701 any of the following: a positive integer; an asterisk (*) to use
702 the next function argument as the width; or a string of the form
703 *n$ to use the nth function argument as the width.
705 If the width comes from a function argument, that argument is
706 consumed before the argument that is used for the format
707 specifier's value. If the width argument is negative, the result
708 is left aligned (as if the - flag had been specified) within a
709 field of length abs(width).
712 The type of format conversion to use to produce the format
713 specifier's output. The following types are supported:
715 + s formats the argument value as a simple string. A null value
716 is treated as an empty string.
717 + I treats the argument value as an SQL identifier,
718 double-quoting it if necessary. It is an error for the value
719 to be null (equivalent to quote_ident).
720 + L quotes the argument value as an SQL literal. A null value is
721 displayed as the string NULL, without quotes (equivalent to
724 In addition to the format specifiers described above, the special
725 sequence %% may be used to output a literal % character.
727 Here are some examples of the basic format conversions:
728 SELECT format('Hello %s', 'World');
731 SELECT format('Testing %s, %s, %s, %%', 'one', 'two', 'three');
732 Result: Testing one, two, three, %
734 SELECT format('INSERT INTO %I VALUES(%L)', 'Foo bar', E'O\'Reilly');
735 Result: INSERT INTO "Foo bar" VALUES('O''Reilly')
737 SELECT format('INSERT INTO %I VALUES(%L)', 'locations', 'C:\Program Files');
738 Result: INSERT INTO locations VALUES('C:\Program Files')
740 Here are examples using width fields and the - flag:
741 SELECT format('|%10s|', 'foo');
744 SELECT format('|%-10s|', 'foo');
747 SELECT format('|%*s|', 10, 'foo');
750 SELECT format('|%*s|', -10, 'foo');
753 SELECT format('|%-*s|', 10, 'foo');
756 SELECT format('|%-*s|', -10, 'foo');
759 These examples show use of position fields:
760 SELECT format('Testing %3$s, %2$s, %1$s', 'one', 'two', 'three');
761 Result: Testing three, two, one
763 SELECT format('|%*2$s|', 'foo', 10, 'bar');
766 SELECT format('|%1$*2$s|', 'foo', 10, 'bar');
769 Unlike the standard C function sprintf, PostgreSQL's format function
770 allows format specifiers with and without position fields to be mixed
771 in the same format string. A format specifier without a position field
772 always uses the next argument after the last argument consumed. In
773 addition, the format function does not require all function arguments
774 to be used in the format string. For example:
775 SELECT format('Testing %3$s, %2$s, %s', 'one', 'two', 'three');
776 Result: Testing three, two, three
778 The %I and %L format specifiers are particularly useful for safely
779 constructing dynamic SQL statements. See Example 41.1.