BigQuery · String function
BigQuery RPAD
RPAD(value, length[, pattern]) pads a string on the right to a fixed length: RPAD('SKU', 8, '.') returns SKU..... The default pattern is a space. Values longer than length are truncated to their first length characters.
RPAD appends copies of pattern until the result is return_length characters long (bytes for BYTES). A multi-character pattern is repeated and cut where the length is reached; the default pattern is one space.
Like LPAD, RPAD truncates values that are already longer than return_length, keeping the leftmost characters. That makes RPAD(value, n) a way to force an exact width, which is what fixed-width file formats need, but it also means long values lose data without an error.
The value must be STRING or BYTES. An empty pattern and a negative length raise errors, and NULL in any argument returns NULL.
Syntax
RPAD(original_value, return_length[, pattern])Arguments and return value
| Argument | Description |
|---|---|
original_value | The STRING or BYTES value to pad. |
return_length | INT64 length of the result in characters (STRING) or bytes (BYTES). Must not be negative. |
pattern | Optional padding text, the same type as original_value. Defaults to a space. Must not be empty. |
Returns: STRING or BYTES, the same type as original_value.
Examples
Padding, repeated patterns and truncation
SELECT
RPAD('SKU', 8, '.') AS dotted,
RPAD('abc', 7, 'xy') AS repeated_pattern,
RPAD('Enterprise Plus', 10) AS truncated,
FORMAT('%T', RPAD('EU', 4)) AS default_spaces;| dotted | repeated_pattern | truncated | default_spaces |
|---|---|---|---|
| SKU..... | abcxyxy | Enterprise | "EU " |
Fixed-width export line
Each field gets an exact width; the long customer name is cut at 12 characters.
WITH invoices AS (
SELECT 'INV-17' AS invoice_id, 'ACME GmbH' AS customer, 1250 AS amount_cents UNION ALL
SELECT 'INV-1803', 'Northwind Traders Ltd', 99
)
SELECT
CONCAT(RPAD(invoice_id, 10), RPAD(customer, 12), LPAD(CAST(amount_cents AS STRING), 8, '0')) AS line
FROM invoices
ORDER BY invoice_id;| line |
|---|
| INV-17 ACME GmbH 00001250 |
| INV-1803 Northwind Tr00000099 |
Common mistakes
- Assuming RPAD only adds characters. A value longer than
return_lengthis truncated, soRPAD(customer, 12)drops the end of long names without warning. - Padding numbers without casting.
RPAD(42, 5, '0')fails with No matching signature; cast to STRING first. - Using an empty pattern.
RPAD(value, 10, '')raisesThird argument (pad pattern) for LPAD/RPAD cannot be empty.
FAQ
How do I pad a string to a fixed width in BigQuery?
Use RPAD(value, width) to left-align (pad on the right) or LPAD(value, width) to right-align. Both also cut values that are longer than width.
How do I right-pad with a character other than a space?
Pass it as the third argument: RPAD(code, 8, '-'). Multi-character patterns are repeated and cut to fit.
Related
Errors you may hit
More string functions
All BigQuery string functions · All functions · BigQuery error messages
