--- title: "lpad" slug: "dev-database-reference-sql-functions-string-lpad" updated: 2026-10-30T18:18:56Z published: 2026-10-30T18:18:56Z canonical: "docs.vastdata.com/dev-database-reference-sql-functions-string-lpad" --- > ## Documentation Index > Fetch the complete documentation index at: https://docs.vastdata.com/llms.txt > Use this file to discover all available pages before exploring further. # lpad *Applies to VAST Cluster 5.5.* *[Functions](/develop/docs/dev-database-reference-sql-functions-index) › [Trimming and padding](/develop/docs/dev-database-reference-sql-functions-string-trimming-and-padding) › Trimming and padding.* `lpad(s, n, fill)` returns `s` padded on the left with `fill`, repeated as often as needed, until it is `n` characters long. A string longer than `n` is cut to its first `n` characters. ## Syntax ``` lpad(s, n, fill) ``` | Argument | Type | Description | | --- | --- | --- | | `s` | `VARCHAR` | The string to pad. | | `n` | `INTEGER` | The length of the result, in characters (Unicode code points). | | `fill` | `VARCHAR` | The characters to add on the left, repeated and cut to fit. | **Returns:** `VARCHAR`. ## Set up the examples The examples connect with the ADBC driver, as in [VAST Query Engine (ADBC)](/develop/docs/dev-database-integrations-adbc), and work in a schema called `docs_sql_fn_string_lpad`. Set `QE_ENDPOINT`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and `VASTDB_BUCKET` ([SQL reference](/develop/docs/dev-database-reference-sql-index#example-connect-and-use-a-transaction)), and run the blocks in order in one Python session. Below each block is the output you should see. This block connects, defines the `run()` and `plan()` helpers, and creates a table of five parts with a code and a label. The last row has no values: ``` import os import re import adbc_driver_manager import adbc_driver_manager.dbapi as dbapi import adbc_driver_vastdb BUCKET = os.environ["VASTDB_BUCKET"] SCHEMA = f'"{BUCKET}/docs_sql_fn_string_lpad"' conn = dbapi.connect( driver=adbc_driver_vastdb.get_driver_path(), db_kwargs={ "vast.db.endpoint": os.environ["QE_ENDPOINT"], "vast.db.access_key": os.environ["AWS_ACCESS_KEY_ID"], "vast.db.secret_key": os.environ["AWS_SECRET_ACCESS_KEY"], }, autocommit=True, ) def server_message(e): """The server's message in a driver error, without the request ID or the echoed statement.""" text = re.sub(r"\[req=0x[0-9a-f]+\]: ", "", str(e)) found = (re.search(r'message: "(.*?)", request_id', text, re.S) or re.search(r"description: (.*)\)", text, re.S)) message = found.group(1) if found else text.strip().splitlines()[-1] message = re.sub(r"^Plan query: '.*?' failed with: ", "", message, flags=re.S) message = re.split(r"\\n|\n", message)[0].replace('\\"', '"') return message.replace(BUCKET, "") def run(sql): """Run one statement. Print the rows it returns, or the error.""" try: with conn.cursor() as cur: cur.execute(sql) rows = cur.fetchall() if cur.description else [] except (adbc_driver_manager.Error, OSError) as e: print(f"{type(e).__name__}: {server_message(e)}") else: print(rows) def plan(sql): """Print the plan without its ~N Rows lines: the table's row count, which can still be 0 just after an insert.""" with conn.cursor() as cur: cur.execute("EXPLAIN " + sql) steps = cur.fetchall()[0][1] print("\n".join(line for line in steps.splitlines() if "Rows" not in line)) TABLE = f"{SCHEMA}.parts" run(f"CREATE SCHEMA IF NOT EXISTS {SCHEMA}") run(f"CREATE TABLE IF NOT EXISTS {TABLE} (id BIGINT, code VARCHAR, label VARCHAR)") run(f"INSERT INTO {TABLE} VALUES " "(1, '42', 'Bolt'), " "(2, '7', 'Nut'), " "(3, '123456', 'Washer'), " "(4, 'caf\u00e9', 'Caf\u00e9 table'), " "(5, NULL, NULL)") ``` ``` [] [] [(5,)] ``` ## What it does `lpad` measures `s` in characters (Unicode code points), then: | Case | What happens | Example | Result | | --- | --- | --- | --- | | `s` is shorter than `n` | `fill` is added on the left, repeated and cut so the result is exactly `n` characters | `lpad('abc', 8, 'xyz')` | `'xyzxyabc'` | | `s` is `n` characters | `s` unchanged | `lpad('abc', 3, '*')` | `'abc'` | | `s` is longer than `n` | `s` is cut to its **first** `n` characters (the right end is dropped, as with [rpad](/develop/docs/dev-database-reference-sql-functions-string-rpad)) | `lpad('abc', 2, '*')` | `'ab'` | | `n` is 0 or negative | an empty string | `lpad('abc', -1, '*')` | `''` | A character is a code point, not what a reader sees: `e` followed by a combining accent (U+0301) counts as two, and so does a flag emoji. A cut can split such a pair, in `s` or in `fill`, and leave a bare `e`. All three arguments are required; for spaces, pass `' '` as the fill. ## NULLs and edge cases | Input | Result | | --- | --- | | `NULL` as any argument | `NULL` | | `lpad('', 3, '0')` | `'000'` | | `lpad('abc', 5, '')` (empty fill, padding needed) | Error: `Insufficient padding in LPAD.` | | `lpad('abc', 3, '')`, `lpad('abc', 2, '')` (no padding needed) | `'abc'`, `'ab'` | | `lpad('é', 3, '*')` (precomposed) | `'**é'` | | `lpad('e\u0301', 3, '*')` (e and a combining accent) | `'*'` followed by `e` and the accent | | `lpad('abc', 4, 'e\u0301')` (the fill is cut after `e`) | `'eabc'` | | `lpad('abc', '5', '*')` (`n` as a string) | `'**abc'` | | `lpad('abc', 2.5, '*')` | Error: `No function matches the given name and argument types 'lpad(STRING_LITERAL, DECIMAL(2,1), STRING_LITERAL)'` | | `lpad(42, 5, '0')` (a number as `s`) | Error: `No function matches the given name and argument types 'lpad(INTEGER_LITERAL, INTEGER_LITERAL, STRING_LITERAL)'` | The same cases, as the cluster returns them. They use the table and helpers from [Set up the examples](/develop/docs/dev-database-reference-sql-functions-string-lpad#set-up-the-examples): ``` run("SELECT lpad(NULL, 5, '*'), lpad('abc', NULL, '*'), lpad('abc', 5, NULL), lpad('', 3, '0')") run("SELECT lpad('abc', 5, '')") run("SELECT lpad('abc', 3, ''), lpad('abc', 2, '')") run("SELECT lpad('\u00e9', 3, '*'), lpad('e\u0301', 3, '*'), lpad('abc', 4, 'e\u0301'), lpad('abc', '5', '*')") run("SELECT lpad('abc', 2.5, '*')") run("SELECT lpad(42, 5, '0')") ``` ``` [(None, None, None, '000')] OSError: Insufficient padding in LPAD. [('abc', 'ab')] [('**é', '*é', 'eabc', '**abc')] InternalError: Binder Error: No function matches the given name and argument types 'lpad(STRING_LITERAL, DECIMAL(2,1), STRING_LITERAL)'. You might need to add explicit type casts. InternalError: Binder Error: No function matches the given name and argument types 'lpad(INTEGER_LITERAL, INTEGER_LITERAL, STRING_LITERAL)'. You might need to add explicit type casts. ``` ## Examples Zero-pad each code to five characters, and pad each label with dots to a right-aligned width of 12. Code `123456` is longer than five characters, so it's cut to `12345`: ``` run(f"SELECT id, lpad(code, 5, '0'), '|' || lpad(label, 12, '.') FROM {TABLE} ORDER BY id LIMIT 10") ``` ``` [(1, '00042', '|........Bolt'), (2, '00007', '|.........Nut'), (3, '12345', '|......Washer'), (4, '0café', '|..Café table'), (5, None, None)] ``` Format a number with leading zeros: cast it to `VARCHAR` first. ``` run(f"SELECT id, lpad(CAST(id AS VARCHAR), 4, '0') FROM {TABLE} ORDER BY id LIMIT 10") ``` ``` [(1, '0001'), (2, '0002'), (3, '0003'), (4, '0004'), (5, '0005')] ``` ## How it runs in VAST The Query Engine runs on the cluster's CNodes, and a query on a table starts with a scan in VAST DataBase (`VAST_SCAN`). VAST DataBase can evaluate a comparison of a column with a constant, but not a function of a column, so `lpad()` is always computed by the Query Engine: - **In the `SELECT` list,** the scan reads the column and the Query Engine pads each value it returns. - **In `WHERE`,** the scan sends the column for every row, and a `FILTER` step in the Query Engine computes `lpad()` and keeps the rows that match. The plan of a padded comparison shows the `FILTER` step above the scan: ``` plan(f"SELECT id FROM {TABLE} WHERE lpad(code, 5, '0') = '00042'") ``` ``` ┌───────────────────────────┐ │ PROJECTION │ │ ──────────────────── │ │ #1 │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ FILTER │ │ ──────────────────── │ │ (lpad(code, 5, '0') = │ │ '00042') │ │ │ └─────────────┬─────────────┘ ┌─────────────┴─────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ │ │ Projections: │ │ code │ │ id │ │ │ └───────────────────────────┘ ``` ## Make it faster - **Compare the raw column.** `code = '42'` is pushed down to VAST DataBase, so rows that don't match never leave storage; `lpad(code, 5, '0') = '00042'` isn't. The plan has no `FILTER` step: ``` plan(f"SELECT id FROM {TABLE} WHERE code = '42'") ``` ``` ┌───────────────────────────┐ │ VAST_SCAN │ │ ──────────────────── │ │ Function: VAST_SCAN │ │ Projections: id │ │ │ └───────────────────────────┘ ``` - **Pad at load time if you filter on the padded form.** Store the padded value in its own column, and compare that column with a constant. - **Combine it with a pushed-down condition.** In `id > 100 AND lpad(code, 5, '0') = '00042'`, `id > 100` is still evaluated in VAST DataBase, so `lpad()` runs only on the rows that pass it. ## Limitations and errors - **Strings only.** A number, a date, a boolean, a `BLOB` or a list as `s` fails with `No function matches the given name and argument types`; the error lists the one form, `lpad(VARCHAR, INTEGER, VARCHAR) -> VARCHAR`. Cast the value to `VARCHAR` first. - **The fill is required.** `lpad(s, n)` fails with `No function matches the given name and argument types 'lpad(STRING_LITERAL, INTEGER_LITERAL)'`. - **`n` is an `INTEGER`.** A decimal such as `2.5`, or a literal larger than an `INTEGER` such as `9223372036854775807`, fails with `No function matches the given name and argument types`. - **An empty fill fails when padding is needed,** with `Insufficient padding in LPAD.`. That includes a fill that comes from a column: one empty value fails the whole query. ``` run("SELECT lpad('a', 3)") run("SELECT lpad('a', 3, ' '), lpad(CAST(42 AS VARCHAR), 5, '0')") ``` ``` InternalError: Binder Error: No function matches the given name and argument types 'lpad(STRING_LITERAL, INTEGER_LITERAL)'. You might need to add explicit type casts. [(' a', '00042')] ``` ## Similar functions | Function | Pads | Result for `'42'` to five characters | Cuts a longer string | | --- | --- | --- | --- | | [rpad](/develop/docs/dev-database-reference-sql-functions-string-rpad)`('42', 5, '0')` | on the right | `'42000'` | yes, to the first `n` characters | | [printf](/develop/docs/dev-database-reference-sql-functions-string-printf)`('%05d', 42)` | a number, with zeros | `'00042'` | no | | [printf](/develop/docs/dev-database-reference-sql-functions-string-printf)`('%5s', '42')` | on the left, with spaces | `' 42'` | no: `printf('%3s', 'abcdef')` is `'abcdef'` | | [format](/develop/docs/dev-database-reference-sql-functions-string-format)`('{:0>5}', '42')` | on the left, with any character | `'00042'` | | | [repeat](/develop/docs/dev-database-reference-sql-functions-string-repeat)`('0', 3) \\|\\| '42'` | a fixed number of characters | `'00042'` | | | [left](/develop/docs/dev-database-reference-sql-functions-string-left)`('abcdef', 3)` | (cuts only) | | `'abc'` | ``` run("SELECT lpad('42', 5, '0'), rpad('42', 5, '0'), printf('%05d', 42), printf('%5s', '42'), " "format('{:0>5}', '42'), repeat('0', 3) || '42'") run("SELECT lpad('abcdef', 3, '*'), rpad('abcdef', 3, '*'), left('abcdef', 3), printf('%3s', 'abcdef')") ``` ``` [('00042', '42000', '00042', ' 42', '00042', '00042')] [('abc', 'abc', 'abc', 'abcdef')] ``` Clean up: ``` run(f"DROP TABLE IF EXISTS {TABLE}") run(f"DROP SCHEMA IF EXISTS {SCHEMA}") conn.close() ``` ``` [] [] ``` ## See also - [Trimming and padding](/develop/docs/dev-database-reference-sql-functions-string-trimming-and-padding): all the trimming and padding functions, including [trim](/develop/docs/dev-database-reference-sql-functions-string-trim), [ltrim](/develop/docs/dev-database-reference-sql-functions-string-ltrim) and [rtrim](/develop/docs/dev-database-reference-sql-functions-string-rtrim). - [Where filters run](/develop/docs/dev-database-reference-sql-select#where-filters-run) and [pushdowns](/develop/docs/dev-database-reference-pushdowns). - [EXPLAIN](/develop/docs/dev-database-reference-sql-explain): how to read a plan.