String#

Function

Description

BIT_LENGTH

Returns the length of the input string in bits.

CHR

Returns the character of an integer Unicode code point.

CONCAT

Returns all input expressions concatenated together as a string.

CONCAT_WS

Returns all input expressions concatenated together (and interleaved with a separator) as a string.

DATE

Converts a formatted date string to an actual Date value.

ENDS_WITH

Returns True if the value ends with the second argument.

FORMAT

Fills the {} placeholders of a format string, with an optional Python format specification such as {:.2f}.

INITCAP

Converts the first letter of each word to uppercase, and the rest to lowercase.

JSON_EXTRACT_PATH

Returns the value at a path of keys in JSON text or a struct, as #> does.

JSON_EXTRACT_PATH_TEXT

Returns the value at a path of keys in JSON text or a struct as text, as #>> does.

LEFT

Returns the first (leftmost) n characters.

LENGTH

Returns the character length of the string.

LOWER

Returns a lowercased column.

LPAD

Pads a string on the left to a specified length using an optional fill character (default is a space).

LTRIM

Strips whitespaces from the left.

NORMALIZE

Convert string to the specified Unicode normalization form (one of NFC, NFD, NFKC, NFKD).

OCTET_LENGTH

Returns the length of a given string in bytes.

PRINTF

Fills the % conversions of a format string, as in C’s printf.

POSITION

Returns the position of a substring within a string.

REGEXP_EXTRACT

Returns the given capture group of the first match of pattern (optional: group, 0 for the whole match).

REGEXP_LIKE

Returns True if pattern matches the value (optional: flags).

REGEXP_MATCHES

Returns True if pattern matches the value (optional: options).

REGEXP_REPLACE

Replaces the first match of pattern with replacement (optional: flags; ‘g’ replaces all matches).

REGEXP_SUBSTR

Returns the n`th match of `pattern, or its capture group, or NULL if there is none.

REPEAT

Returns the string repeated n times.

REPLACE

Replaces a given substring with another string.

REVERSE

Returns the reversed string.

RIGHT

Returns the last (rightmost) n characters.

RPAD

Pads a string on the right to a specified length using an optional fill character (default is a space).

RTRIM

Strips whitespaces from the right.

SPLIT_PART

Splits a string by another substring/delimiter, returning the n-th part; note that n is 1-indexed.

STARTS_WITH

Returns True if the value starts with the second argument.

STRING_TO_ARRAY

Splits a string by another substring/delimiter, returning an array of strings.

STRPOS

Returns the index of the given substring in the target string; note that the result is 1-indexed (returning 0 indicates that the given string was not found).

STRPTIME

Converts a string to a Datetime using a strftime-compatible formatting string.

SUBSTR, SUBSTRING

Returns a slice of the string data (from a start index, with an optional length); note that start is 1-indexed.

TIMESTAMP

Converts a formatted timestamp/datetime string to an actual Datetime value.

TO_DATE

Converts a string to a Date using a PostgreSQL template.

TO_TIMESTAMP

Converts a string to a Datetime using a PostgreSQL template.

TRIM

Strips characters from the left and/or right of a string.

TRY_STRPTIME

Like STRPTIME, but returns NULL for a string that does not match the format.

UPPER

Returns an uppercased column.

BIT_LENGTH#

Returns the length of the input string in bits.

Example:

df = pl.DataFrame({"foo": ["a", "bb", "ccc", "dddd"]})
df.sql("""
  SELECT foo, BIT_LENGTH(foo) AS n_bits FROM self
""")
# shape: (4, 2)
# ┌──────┬────────┐
# │ foo  ┆ n_bits │
# │ ---  ┆ ---    │
# │ str  ┆ u32    │
# ╞══════╪════════╡
# │ a    ┆ 8      │
# │ bb   ┆ 16     │
# │ ccc  ┆ 24     │
# │ dddd ┆ 32     │
# └──────┴────────┘

CHR#

Returns the character of an integer Unicode code point. Raises an error for a negative number, a number above 1114111 (0x10FFFF), or a UTF-16 surrogate (55296 to 57343).

Example:

df = pl.DataFrame({"n": [65, 233, 8364]})
df.sql("""
  SELECT n, CHR(n) AS c FROM self
""")
# shape: (3, 2)
# ┌──────┬─────┐
# │ n    ┆ c   │
# │ ---  ┆ --- │
# │ i64  ┆ str │
# ╞══════╪═════╡
# │ 65   ┆ A   │
# │ 233  ┆ é   │
# │ 8364 ┆ €   │
# └──────┴─────┘

CONCAT#

Returns all input expressions concatenated together as a string.

Example:

df = pl.DataFrame(
  {
    "foo": ["aa", "b", "c", "dd"],
    "bar": ["zz", "yy", "xx", "ww"],
  }
)
df.sql("""
  SELECT CONCAT(foo, bar) AS foobar FROM self
""")
# shape: (4, 1)
# ┌────────┐
# │ foobar │
# │ ---    │
# │ str    │
# ╞════════╡
# │ aazz   │
# │ byy    │
# │ cxx    │
# │ ddww   │
# └────────┘

CONCAT_WS#

Returns all input expressions concatenated together (and interleaved with a separator) as a string.

Example:

df = pl.DataFrame(
  {
    "foo": ["aa", "b", "c", "dd"],
    "bar": ["zz", "yy", "xx", "ww"],
  }
)
df.sql("""
  SELECT CONCAT_WS(':', foo, bar) AS foobar FROM self
""")
# shape: (4, 1)
# ┌────────┐
# │ foobar │
# │ ---    │
# │ str    │
# ╞════════╡
# │ aa:zz  │
# │ b:yy   │
# │ c:xx   │
# │ dd:ww  │
# └────────┘

DATE#

Converts a formatted string date to an actual Date type; ISO-8601 format is assumed unless a strftime-compatible formatting string is provided as the second parameter.

Tip

DATE is also supported as a typed literal (this form does not allow a format string).

SELECT DATE '2021-01-01' AS dt

Example:

df = pl.DataFrame(
  {
    "s_dt1": ["1969-10-30", "2024-07-05", "2077-02-28"],
    "s_dt2": ["10 February 1920", "5 July 2077", "28 April 2000"],
  }
)
df.sql("""
  SELECT
    DATE(s_dt1) AS dt1,
    DATE(s_dt2, '%d %B %Y') AS dt2
  FROM self
""")
# shape: (3, 2)
# ┌────────────┬────────────┐
# │ dt1        ┆ dt2        │
# │ ---        ┆ ---        │
# │ date       ┆ date       │
# ╞════════════╪════════════╡
# │ 1969-10-30 ┆ 1920-02-10 │
# │ 2024-07-05 ┆ 2077-07-05 │
# │ 2077-02-28 ┆ 2000-04-28 │
# └────────────┴────────────┘

ENDS_WITH#

Returns True if the value ends with the second argument.

Example:

df = pl.DataFrame(
  {
    "foo": ["aa", "bb", "cc", "dd"],
    "bar": ["zz", "yy", "xx", "ww"],
  }
)
df.sql("""
  SELECT foo, ENDS_WITH(foo, 'a') AS ends_a FROM self
""")
# shape: (4, 2)
# ┌─────┬────────┐
# │ foo ┆ ends_a │
# │ --- ┆ ---    │
# │ str ┆ bool   │
# ╞═════╪════════╡
# │ aa  ┆ true   │
# │ bb  ┆ false  │
# │ cc  ┆ false  │
# │ dd  ┆ false  │
# └─────┴────────┘

FORMAT#

Fills the {} placeholders of a format string with the other arguments. A placeholder can hold an argument index ({1}) and a Python format specification after a colon ({:>8}, {:.2f}, {:,}), as in polars.format(). Write {{ and }} for literal braces. The result is null if any argument is null.

Example:

df = pl.DataFrame({"name": ["apple", "kiwi"], "price": [1.5, 1234.125]})
df.sql("""
  SELECT FORMAT('{:<6}|{:>9,.2f}', name, price) AS fmt FROM self
""")
# shape: (2, 1)
# ┌──────────────────┐
# │ fmt              │
# │ ---              │
# │ str              │
# ╞══════════════════╡
# │ apple |     1.50 │
# │ kiwi  | 1,234.12 │
# └──────────────────┘

INITCAP#

Converts the first letter of each word to uppercase, and the rest to lowercase.

Example:

df = pl.DataFrame({"bar": ["hello world", "HELLO", "wOrLd"]})
df.sql("""
  SELECT bar, INITCAP(bar) AS baz FROM self
""")
# shape: (3, 2)
# ┌─────────────┬─────────────┐
# │ bar         ┆ baz         │
# │ ---         ┆ ---         │
# │ str         ┆ str         │
# ╞═════════════╪═════════════╡
# │ hello world ┆ Hello World │
# │ HELLO       ┆ Hello       │
# │ wOrLd       ┆ World       │
# └─────────────┴─────────────┘

JSON_EXTRACT_PATH, JSON_EXTRACT_PATH_TEXT#

Returns the value at a path of keys, or of array indexes counted from 0, in JSON text or a struct: JSON_EXTRACT_PATH(j, 'a', 'b') is j #> '{a,b}' and JSON_EXTRACT_PATH_TEXT is j #>> '{a,b}', as in Postgres. The keys are literals. NULL if there is no such value; unlike Postgres, JSON_EXTRACT_PATH of JSON text gives the value’s text, as #> does.

Example:

df = pl.DataFrame({"j": ['{"user": {"name": "Ann", "tags": ["a", "b"]}}', '{"user": {}}']})
df.sql("""
  SELECT
    JSON_EXTRACT_PATH_TEXT(j, 'user', 'name') AS name,
    JSON_EXTRACT_PATH_TEXT(j, 'user', 'tags', 1) AS tag
  FROM self
""")
# shape: (2, 2)
# ┌──────┬──────┐
# │ name ┆ tag  │
# │ ---  ┆ ---  │
# │ str  ┆ str  │
# ╞══════╪══════╡
# │ Ann  ┆ b    │
# │ null ┆ null │
# └──────┴──────┘

LEFT#

Returns the first (leftmost) n characters.

Example:

df = pl.DataFrame(
  {
    "foo": ["abcd", "efgh", "ijkl", "mnop"],
    "bar": ["zz", "yy", "xx", "ww"],
  }
)
df.sql("""
  SELECT
    LEFT(foo, 1) AS foo1,
    LEFT(bar, 2) AS bar2
  FROM self
""")

# shape: (4, 2)
# ┌──────┬──────┐
# │ foo1 ┆ bar2 │
# │ ---  ┆ ---  │
# │ str  ┆ str  │
# ╞══════╪══════╡
# │ a    ┆ zz   │
# │ e    ┆ yy   │
# │ i    ┆ xx   │
# │ m    ┆ ww   │
# └──────┴──────┘

LENGTH#

Returns the character length of the string.

Aliases

CHAR_LENGTH, CHARACTER_LENGTH

Example:

df = pl.DataFrame(
  {
    "iso_lang":["de", "ru", "es"],
    "color": ["weiß", "синий", "amarillo"],
  }
)
df.sql("""
  SELECT
    iso_lang,
    color,
    LENGTH(color) AS n_chars,
    OCTET_LENGTH(color) AS n_bytes
  FROM self
""")

# shape: (3, 4)
# ┌──────────┬──────────┬─────────┬─────────┐
# │ iso_lang ┆ color    ┆ n_chars ┆ n_bytes │
# │ ---      ┆ ---      ┆ ---     ┆ ---     │
# │ str      ┆ str      ┆ u32     ┆ u32     │
# ╞══════════╪══════════╪═════════╪═════════╡
# │ de       ┆ weiß     ┆ 4       ┆ 5       │
# │ ru       ┆ синий    ┆ 5       ┆ 10      │
# │ es       ┆ amarillo ┆ 8       ┆ 8       │
# └──────────┴──────────┴─────────┴─────────┘

LOWER#

Returns a lowercased column.

Example:

df = pl.DataFrame({"foo": ["AA", "BB", "CC", "DD"]})
df.sql("""
  SELECT foo, LOWER(foo) AS foo_lower FROM self
""")
# shape: (4, 2)
# ┌─────┬───────────┐
# │ foo ┆ foo_lower │
# │ --- ┆ ---       │
# │ str ┆ str       │
# ╞═════╪═══════════╡
# │ AA  ┆ aa        │
# │ BB  ┆ bb        │
# │ CC  ┆ cc        │
# │ DD  ┆ dd        │
# └─────┴───────────┘

LPAD#

Pads a string on the left to a specified length using an optional fill character (default is a space). If the string is longer than the target length it is truncated.

Example:

df = pl.DataFrame({"foo": ["hello", "hi", "a", None, "longstr"]})
df.sql("""
  SELECT
    foo,
    LPAD(foo, 7) AS lpad,
    LPAD(foo, 7, 'x') AS lpad_x,
    LPAD(foo, 4, '#') AS lpad_trunc
  FROM self
""")
# shape: (5, 4)
# ┌─────────┬─────────┬─────────┬────────────┐
# │ foo     ┆ lpad    ┆ lpad_x  ┆ lpad_trunc │
# │ ---     ┆ ---     ┆ ---     ┆ ---        │
# │ str     ┆ str     ┆ str     ┆ str        │
# ╞═════════╪═════════╪═════════╪════════════╡
# │ hello   ┆   hello ┆ xxhello ┆ hell       │
# │ hi      ┆      hi ┆ xxxxxhi ┆ ##hi       │
# │ a       ┆       a ┆ xxxxxxa ┆ ###a       │
# │ null    ┆ null    ┆ null    ┆ null       │
# │ longstr ┆ longstr ┆ longstr ┆ long       │
# └─────────┴─────────┴─────────┴────────────┘

LTRIM#

Strips whitespaces from the left.

Example:

df = pl.DataFrame({"foo": ["   AA", " BB", "CC", "  DD"]})
df.sql("""
  SELECT foo, LTRIM(foo) AS trimmed FROM self
""")
# shape: (4, 2)
# ┌───────┬─────────┐
# │ foo   ┆ trimmed │
# │ ---   ┆ ---     │
# │ str   ┆ str     │
# ╞═══════╪═════════╡
# │    AA ┆ AA      │
# │  BB   ┆ BB      │
# │ CC    ┆ CC      │
# │   DD  ┆ DD      │
# └───────┴─────────┘

NORMALIZE#

Convert string to the specified Unicode normalization form (one of NFC, NFD, NFKC, NFKD). If the normalization form is not provided, NFC is used by default.

Example:

df = pl.DataFrame({
    "txt": [
        "Test",
        "Ⓣⓔⓢⓣ",
        "𝕿𝖊𝖘𝖙",
        "𝕋𝕖𝕤𝕥",
        "𝗧𝗲𝘀𝘁",
    ],
})
df.sql("""
  SELECT NORMALIZE(txt, NFKC) FROM self
""").to_series()
# shape: (5,)
# Series: 'txt' [str]
# [
#   "Test"
#   "Test"
#   "Test"
#   "Test"
#   "Test"
# ]

OCTET_LENGTH#

Returns the length of a given string in bytes.

Example:

df = pl.DataFrame(
  {
    "iso_lang":["de", "ru", "es"],
    "color": ["weiß", "синий", "amarillo"],
  }
)
df.sql("""
  SELECT
    iso_lang,
    color,
    OCTET_LENGTH(color) AS n_bytes,
    LENGTH(color) AS n_chars
  FROM self
""")
# shape: (3, 4)
# ┌──────────┬──────────┬─────────┬─────────┐
# │ iso_lang ┆ color    ┆ n_bytes ┆ n_chars │
# │ ---      ┆ ---      ┆ ---     ┆ ---     │
# │ str      ┆ str      ┆ u32     ┆ u32     │
# ╞══════════╪══════════╪═════════╪═════════╡
# │ de       ┆ weiß     ┆ 5       ┆ 4       │
# │ ru       ┆ синий    ┆ 10      ┆ 5       │
# │ es       ┆ amarillo ┆ 8       ┆ 8       │
# └──────────┴──────────┴─────────┴─────────┘

PRINTF#

Fills the % conversions of a format string with the other arguments, as in C’s printf. Supports the flags -, +, space, #, 0 and , (thousands separator), the width, the precision, argument numbers (%2$s) and the conversions d, i, u, f, F, e, E, g, G, x, X, o, c and s; %% writes a %. %s converts any value that can be cast to a string, which excludes lists and arrays. A precision is not supported with d, i, u, o, x, X and c, nor is # with o. Negative numbers keep their sign with u, x, X and o, %#x writes 0x0 for zero, and %c writes the character of a Unicode code point. The result is null if any argument is null.

Example:

df = pl.DataFrame({"name": ["apple", "kiwi"], "n": [3, 12], "price": [1.5, 0.25]})
df.sql("""
  SELECT PRINTF('%-6s x%03d at %.2f', name, n, price) AS line FROM self
""")
# shape: (2, 1)
# ┌─────────────────────┐
# │ line                │
# │ ---                 │
# │ str                 │
# ╞═════════════════════╡
# │ apple  x003 at 1.50 │
# │ kiwi   x012 at 0.25 │
# └─────────────────────┘

POSITION#

Returns the position of a substring within a string. The result is 1-indexed, returning 0 if the substring is not found.

See also

STRPOS for the equivalent function-call syntax.

Example:

df = pl.DataFrame({"foo": ["apple", "banana", "orange", "grape"]})
df.sql("""
  SELECT foo, POSITION('an' IN foo) AS pos FROM self
""")
# shape: (4, 2)
# ┌────────┬─────┐
# │ foo    ┆ pos │
# │ ---    ┆ --- │
# │ str    ┆ u32 │
# ╞════════╪═════╡
# │ apple  ┆ 0   │
# │ banana ┆ 2   │
# │ orange ┆ 3   │
# │ grape  ┆ 0   │
# └────────┴─────┘

REGEXP_EXTRACT#

Returns the given capture group of the first match of pattern (optional: group, 0 for the whole match), or an empty string if there is no match.

Example:

df = pl.DataFrame({"foo": ["ab12-34", "x56-78", "abc"]})
df.sql(r"""
  SELECT foo, REGEXP_EXTRACT(foo, '(\d+)-(\d+)', 2) AS second FROM self
""")
# shape: (3, 2)
# ┌─────────┬────────┐
# │ foo     ┆ second │
# │ ---     ┆ ---    │
# │ str     ┆ str    │
# ╞═════════╪════════╡
# │ ab12-34 ┆ 34     │
# │ x56-78  ┆ 78     │
# │ abc     ┆        │
# └─────────┴────────┘

REGEXP_LIKE#

Returns True if pattern matches the value (optional: flags).

Example:

df = pl.DataFrame({"foo": ["abc123", "4ab4a", "abc456", "321cba"]})
df.sql(r"""
  SELECT foo, REGEXP_LIKE(foo, '\d$') AS ends_in_digit FROM self
""")
# shape: (4, 2)
# ┌────────┬───────────────┐
# │ foo    ┆ ends_in_digit │
# │ ---    ┆ ---           │
# │ str    ┆ bool          │
# ╞════════╪═══════════════╡
# │ abc123 ┆ true          │
# │ 4ab4a  ┆ false         │
# │ abc456 ┆ true          │
# │ 321cba ┆ false         │
# └────────┴───────────────┘

REGEXP_MATCHES#

Returns True if pattern matches the value. The optional options are ‘c’ (case-sensitive, the default), ‘i’ (case-insensitive), ‘l’ (match pattern literally), ‘s’ (. also matches a newline) and ‘m’, ‘n’ or ‘p’ (. does not match a newline, the default).

Example:

df = pl.DataFrame({"s": ["Polars", "python", "a.b"]})
df.sql("""
  SELECT
    s,
    REGEXP_MATCHES(s, '^p', 'i') AS m1,
    REGEXP_MATCHES(s, '.', 'l') AS m2
  FROM self
""")
# shape: (3, 3)
# ┌────────┬───────┬───────┐
# │ s      ┆ m1    ┆ m2    │
# │ ---    ┆ ---   ┆ ---   │
# │ str    ┆ bool  ┆ bool  │
# ╞════════╪═══════╪═══════╡
# │ Polars ┆ true  ┆ false │
# │ python ┆ true  ┆ false │
# │ a.b    ┆ false ┆ true  │
# └────────┴───────┴───────┘

REGEXP_REPLACE#

Replaces the first match of pattern with replacement (optional: flags). The ‘g’ flag replaces all matches; other flags are applied as inline regex flags, such as ‘i’ for a case-insensitive match. In replacement, 1 refers to the first capture group and & to the whole match.

Example:

df = pl.DataFrame({"foo": ["abc-123", "ab-cd", "x"]})
df.sql(r"""
  SELECT foo, REGEXP_REPLACE(foo, '(\w+)-(\w+)', '\2-\1') AS bar FROM self
""")
# shape: (3, 2)
# ┌─────────┬─────────┐
# │ foo     ┆ bar     │
# │ ---     ┆ ---     │
# │ str     ┆ str     │
# ╞═════════╪═════════╡
# │ abc-123 ┆ 123-abc │
# │ ab-cd   ┆ cd-ab   │
# │ x       ┆ x       │
# └─────────┴─────────┘

REGEXP_SUBSTR#

Returns the substring of the nth match of pattern (optional, default 1), or of its capture group subexpr (first match only), as in Postgres; NULL if there is no such match. flags ‘i’ makes the match case-insensitive and ‘c’ case-sensitive; the start position must be 1. The pattern is a Rust regex: an alternation takes the first alternative that matches, where Postgres takes the longest.

Example:

df = pl.DataFrame({"s": ["user=Ann path=/a", "path=/b"]})
df.sql(r"""
  SELECT REGEXP_SUBSTR(s, 'user=(\w+)', 1, 1, 'c', 1) AS user FROM self
""")
# shape: (2, 1)
# ┌──────┐
# │ user │
# │ ---  │
# │ str  │
# ╞══════╡
# │ Ann  │
# │ null │
# └──────┘

REPEAT#

Returns the string repeated n times; a negative n gives an empty string.

Example:

df = pl.DataFrame({"foo": ["ab", "c", None], "n": [2, 3, 1]})
df.sql("""
  SELECT foo, REPEAT(foo, n) AS repeated FROM self
""")
# shape: (3, 2)
# ┌──────┬──────────┐
# │ foo  ┆ repeated │
# │ ---  ┆ ---      │
# │ str  ┆ str      │
# ╞══════╪══════════╡
# │ ab   ┆ abab     │
# │ c    ┆ ccc      │
# │ null ┆ null     │
# └──────┴──────────┘

REPLACE#

Replaces a given substring with another string.

Example:

df = pl.DataFrame({"foo": ["abc123", "11aabb", "bcbc45"]})
df.sql("""
  SELECT foo, REPLACE(foo, 'b', '?') AS bar FROM self
""")
# shape: (3, 2)
# ┌────────┬────────┐
# │ foo    ┆ bar    │
# │ ---    ┆ ---    │
# │ str    ┆ str    │
# ╞════════╪════════╡
# │ abc123 ┆ a?c123 │
# │ 11aabb ┆ 11aa?? │
# │ bcbc45 ┆ ?c?c45 │
# └────────┴────────┘

REVERSE#

Returns the reversed string.

Example:

df = pl.DataFrame({"foo": ["apple", "banana", "orange", "grape"]})
df.sql("""
  SELECT foo, REVERSE(foo) AS oof FROM self
""")
# shape: (4, 2)
# ┌────────┬────────┐
# │ foo    ┆ oof    │
# │ ---    ┆ ---    │
# │ str    ┆ str    │
# ╞════════╪════════╡
# │ apple  ┆ elppa  │
# │ banana ┆ ananab │
# │ orange ┆ egnaro │
# │ grape  ┆ eparg  │
# └────────┴────────┘

RPAD#

Pads a string on the right to a specified length using an optional fill character (default is a space). If the string is longer than the target length it is truncated.

Example:

df = pl.DataFrame({"foo": ["hello", "hi", "a", None, "longstr"]})
df.sql("""
  SELECT
    foo,
    RPAD(foo, 7) AS rpad,
    RPAD(foo, 7, '-') AS rpad_dash,
    RPAD(foo, 4, '#') AS rpad_trunc
  FROM self
""")
# shape: (5, 4)
# ┌─────────┬─────────┬───────────┬────────────┐
# │ foo     ┆ rpad    ┆ rpad_dash ┆ rpad_trunc │
# │ ---     ┆ ---     ┆ ---       ┆ ---        │
# │ str     ┆ str     ┆ str       ┆ str        │
# ╞═════════╪═════════╪═══════════╪════════════╡
# │ hello   ┆ hello   ┆ hello--   ┆ hell       │
# │ hi      ┆ hi      ┆ hi-----   ┆ hi##       │
# │ a       ┆ a       ┆ a------   ┆ a###       │
# │ null    ┆ null    ┆ null      ┆ null       │
# │ longstr ┆ longstr ┆ longstr   ┆ long       │
# └─────────┴─────────┴───────────┴────────────┘

RTRIM#

Strips whitespaces from the right.

Example:

df = pl.DataFrame({"bar": ["zz    ", "yy  ", "xx ", "ww   "]})
df.sql("""
  SELECT bar, RTRIM(bar) AS baz FROM self
""")
# shape: (4, 2)
# ┌────────┬─────┐
# │ bar    ┆ baz │
# │ ---    ┆ --- │
# │ str    ┆ str │
# ╞════════╪═════╡
# │ zz     ┆ zz  │
# │ yy     ┆ yy  │
# │ xx     ┆ xx  │
# │ ww     ┆ ww  │
# └────────┴─────┘

SPLIT_PART#

Splits a string by another substring/delimiter, returning the n-th part; note that n is 1-indexed.

Example:

df = pl.DataFrame({"s": ["xx,yy,zz", "abc,,xyz,???,hmm", None, ""]})
df.sql("""
  SELECT
    s,
    SPLIT_PART(s,',',1) AS "s+1",
    SPLIT_PART(s,',',3) AS "s+3",
    SPLIT_PART(s,',',-2) AS "s-2",
  FROM self
""")
# shape: (4, 4)
# ┌──────────────────┬──────┬──────┬──────┐
# │ s                ┆ s+1  ┆ s+3  ┆ s-2  │
# │ ---              ┆ ---  ┆ ---  ┆ ---  │
# │ str              ┆ str  ┆ str  ┆ str  │
# ╞══════════════════╪══════╪══════╪══════╡
# │ xx,yy,zz         ┆ xx   ┆ zz   ┆ yy   │
# │ abc,,xyz,???,hmm ┆ abc  ┆ xyz  ┆ ???  │
# │ null             ┆ null ┆ null ┆ null │
# │                  ┆      ┆      ┆      │
# └──────────────────┴──────┴──────┴──────┘

STARTS_WITH#

Returns True if the value starts with the second argument.

Example:

df = pl.DataFrame({"foo": ["apple", "banana", "avocado", "grape"]})
df.sql("""
  SELECT foo, STARTS_WITH(foo, 'a') AS starts_a FROM self
""")
# shape: (4, 2)
# ┌─────────┬──────────┐
# │ foo     ┆ starts_a │
# │ ---     ┆ ---      │
# │ str     ┆ bool     │
# ╞═════════╪══════════╡
# │ apple   ┆ true     │
# │ banana  ┆ false    │
# │ avocado ┆ true     │
# │ grape   ┆ false    │
# └─────────┴──────────┘

STRING_TO_ARRAY#

Splits a string by another substring/delimiter, returning an array of strings.

Example:

df = pl.DataFrame({"foo": ["aa,bb,cc", "x,y"]})
df.sql("""
  SELECT foo, STRING_TO_ARRAY(foo, ',') AS arr FROM self
""")
# shape: (2, 2)
# ┌──────────┬────────────────────┐
# │ foo      ┆ arr                │
# │ ---      ┆ ---                │
# │ str      ┆ list[str]          │
# ╞══════════╪════════════════════╡
# │ aa,bb,cc ┆ ["aa", "bb", "cc"] │
# │ x,y      ┆ ["x", "y"]         │
# └──────────┴────────────────────┘

STRPOS#

Returns the index of the given substring in the target string.

Example:

df = pl.DataFrame({"foo": ["apple", "banana", "orange", "grape"]})
df.sql("""
  SELECT foo, STRPOS(foo, 'a') AS pos_a FROM self
""")
# shape: (4, 2)
# ┌────────┬───────┐
# │ foo    ┆ pos_a │
# │ ---    ┆ ---   │
# │ str    ┆ u32   │
# ╞════════╪═══════╡
# │ apple  ┆ 1     │
# │ banana ┆ 2     │
# │ orange ┆ 3     │
# │ grape  ┆ 3     │
# └────────┴───────┘

STRPTIME#

Converts a string to a Datetime using a chrono strftime-compatible formatting string.

Example:

df = pl.DataFrame(
  {
    "s_dt": ["1969 Oct 30", "2024 Jul 05", "2077 Feb 28"],
    "s_tm": ["00.30.55", "12.40.15", "10.45.00"],
  }
)
df.sql("""
  SELECT
    s_dt,
    s_tm,
    STRPTIME(s_dt || ' ' || s_tm, '%Y %b %d %H.%M.%S') AS dtm
  FROM self
""")
# shape: (3, 3)
# ┌─────────────┬──────────┬─────────────────────┐
# │ s_dt        ┆ s_tm     ┆ dtm                 │
# │ ---         ┆ ---      ┆ ---                 │
# │ str         ┆ str      ┆ datetime[μs]        │
# ╞═════════════╪══════════╪═════════════════════╡
# │ 1969 Oct 30 ┆ 00.30.55 ┆ 1969-10-30 00:30:55 │
# │ 2024 Jul 05 ┆ 12.40.15 ┆ 2024-07-05 12:40:15 │
# │ 2077 Feb 28 ┆ 10.45.00 ┆ 2077-02-28 10:45:00 │
# └─────────────┴──────────┴─────────────────────┘

SUBSTR#

Returns a slice of the string data (from a start index, with an optional length); note that start is 1-indexed.

See also

SUBSTRING supports the additional form (FROM ... FOR ...).

Example:

df = pl.DataFrame({"foo": ["apple", "banana", "orange", "grape"]})
df.sql("""
  SELECT foo, SUBSTR(foo, 3, 4) AS foo_3_4 FROM self
""")
# shape: (4, 2)
# ┌────────┬─────────┐
# │ foo    ┆ foo_3_4 │
# │ ---    ┆ ---     │
# │ str    ┆ str     │
# ╞════════╪═════════╡
# │ apple  ┆ ple     │
# │ banana ┆ nana    │
# │ orange ┆ ange    │
# │ grape  ┆ ape     │
# └────────┴─────────┘

SUBSTRING#

Returns a slice of the string data (from a start index, with an optional length); note that start is 1-indexed.

See also

SUBSTR for the simpler function-call syntax.

Supports multiple forms:

  • SUBSTRING(str, start)

  • SUBSTRING(str, start, length)

  • SUBSTRING(str FROM start)

  • SUBSTRING(str FROM start FOR length)

Note that start is 1-indexed.

Example:

df = pl.DataFrame({"foo": ["apple", "banana", "orange", "grape"]})
df.sql("""
  SELECT foo, SUBSTRING(foo FROM 2 FOR 3) AS foo_2_3 FROM self
""")
# shape: (4, 2)
# ┌────────┬─────────┐
# │ foo    ┆ foo_2_3 │
# │ ---    ┆ ---     │
# │ str    ┆ str     │
# ╞════════╪═════════╡
# │ apple  ┆ ppl     │
# │ banana ┆ ana     │
# │ orange ┆ ran     │
# │ grape  ┆ rap     │
# └────────┴─────────┘

TIMESTAMP#

Converts a formatted string date to an actual Datetime type; ISO-8601 format is assumed unless a strftime-compatible formatting string is provided as the second parameter.

Aliases

DATETIME

Note

TIMESTAMP is also supported as a typed literal (this form does not allow a format string).

SELECT TIMESTAMP '2077-12-10 22:30:45' AS ts

Example:

df = pl.DataFrame(
  {
    "str_timestamp": [
      "1969 July 30, 00:30:55",
      "2030-October-08, 12:40:15",
      "2077 February 28, 10:45:00",
    ]
  }
)
df.sql("""
  SELECT str_timestamp, TIMESTAMP(str_date, '%Y.%m.%d') AS date FROM self
""")
# shape: (3, 2)
# ┌────────────┬────────────┐
# │ str_date   ┆ date       │
# │ ---        ┆ ---        │
# │ str        ┆ date       │
# ╞════════════╪════════════╡
# │ 1969.10.30 ┆ 1969-10-30 │
# │ 2024.07.05 ┆ 2024-07-05 │
# │ 2077.02.28 ┆ 2077-02-28 │
# └────────────┴────────────┘

TRIM#

Strips characters from the left and/or right of a string.

Syntax:

  • TRIM(expr) - strip whitespace from both sides.

  • TRIM(BOTH char FROM expr) - strip char from both sides.

  • TRIM(LEADING char FROM expr) - strip char from the left.

  • TRIM(TRAILING char FROM expr) - strip char from the right.

Example:

df = pl.DataFrame({"foo": ["  hello  ", "  world  ", "  test  "]})
df.sql("""
  SELECT
    foo,
    TRIM(foo) AS trimmed,
    TRIM(LEADING ' ' FROM foo) AS ltrimmed,
    TRIM(TRAILING ' ' FROM foo) AS rtrimmed
  FROM self
""")
# shape: (3, 4)
# ┌───────────┬─────────┬──────────┬──────────┐
# │ foo       ┆ trimmed ┆ ltrimmed ┆ rtrimmed │
# │ ---       ┆ ---     ┆ ---      ┆ ---      │
# │ str       ┆ str     ┆ str      ┆ str      │
# ╞═══════════╪═════════╪══════════╪══════════╡
# │   hello   ┆ hello   ┆ hello    ┆   hello  │
# │   world   ┆ world   ┆ world    ┆   world  │
# │   test    ┆ test    ┆ test     ┆   test   │
# └───────────┴─────────┴──────────┴──────────┘

TO_DATE#

Converts a string to a Date using a PostgreSQL template, such as ‘DD Mon YYYY’; the patterns are those of TO_CHAR. A template that contains % is read as a strftime format, and without a template ISO-8601 format is assumed.

Example:

df = pl.DataFrame({"s": ["05 Jul 1978", "10 Apr 2020"]})
df.sql("SELECT s, TO_DATE(s, 'DD Mon YYYY') AS dt FROM self")
# shape: (2, 2)
# ┌─────────────┬────────────┐
# │ s           ┆ dt         │
# │ ---         ┆ ---        │
# │ str         ┆ date       │
# ╞═════════════╪════════════╡
# │ 05 Jul 1978 ┆ 1978-07-05 │
# │ 10 Apr 2020 ┆ 2020-04-10 │
# └─────────────┴────────────┘

TO_TIMESTAMP#

Converts a string to a Datetime using a PostgreSQL template, such as ‘YYYY-MM-DD HH24:MI:SS’; the patterns are those of TO_CHAR. A template that contains % is read as a strftime format, and without a template ISO-8601 format is assumed. A number is read as the seconds since the Unix epoch, giving a UTC Datetime.

Example:

df = pl.DataFrame({"s": ["1978-07-05 10:30 AM", "2020-04-10 10:05 PM"]})
df.sql("SELECT s, TO_TIMESTAMP(s, 'YYYY-MM-DD HH12:MI AM') AS dtm FROM self")
# shape: (2, 2)
# ┌─────────────────────┬─────────────────────┐
# │ s                   ┆ dtm                 │
# │ ---                 ┆ ---                 │
# │ str                 ┆ datetime[μs]        │
# ╞═════════════════════╪═════════════════════╡
# │ 1978-07-05 10:30 AM ┆ 1978-07-05 10:30:00 │
# │ 2020-04-10 10:05 PM ┆ 2020-04-10 22:05:00 │
# └─────────────────────┴─────────────────────┘

TRY_STRPTIME#

Like STRPTIME, but returns NULL for a string that does not match the format, instead of raising an error.

Example:

df = pl.DataFrame({"s": ["2024-02-29", "2023-02-29", "not a date"]})
df.sql("SELECT s, TRY_STRPTIME(s, '%Y-%m-%d') AS dt FROM self")
# shape: (3, 2)
# ┌────────────┬─────────────────────┐
# │ s          ┆ dt                  │
# │ ---        ┆ ---                 │
# │ str        ┆ datetime[μs]        │
# ╞════════════╪═════════════════════╡
# │ 2024-02-29 ┆ 2024-02-29 00:00:00 │
# │ 2023-02-29 ┆ null                │
# │ not a date ┆ null                │
# └────────────┴─────────────────────┘

UPPER#

Returns an uppercased column.

Example:

df = pl.DataFrame({"foo": ["apple", "banana", "orange", "grape"]})
df.sql("""
  SELECT foo, UPPER(foo) AS foo_upper FROM self
""")
# shape: (4, 2)
# ┌────────┬───────────┐
# │ foo    ┆ foo_upper │
# │ ---    ┆ ---       │
# │ str    ┆ str       │
# ╞════════╪═══════════╡
# │ apple  ┆ APPLE     │
# │ banana ┆ BANANA    │
# │ orange ┆ ORANGE    │
# │ grape  ┆ GRAPE     │
# └────────┴───────────┘