// strings reference

SQL RPAD function

Pads a string on the right with a fill pattern until it reaches the requested length.

類別
Strings
Returns
string
In this category
114 of 172

語法

RPAD(str, length [, pad_string])  -- pad_string is required in MySQL

引擎支援

引擎Support備註
SQL Server Not built in No RPAD; LEFT(str + REPLICATE(pad, n), n).
PostgreSQL 是 Supported under this name.
MySQL 是 Supported under this name.
SQLite Not built in No RPAD; printf('%-10s', str) pads with spaces.
Oracle 是 Supported under this name.

範例

PostgreSQL

SELECT RPAD('id-', 6, '0') AS code;  -- id-000

MySQL

SELECT RPAD(name, 20, '.') AS name_line
FROM products;

小知識

  • A target length shorter than the input truncates it: RPAD('abcdef', 4, 'x') is 'abcd', so padding and clipping are the same call.
  • The pad string repeats and is cut to fit: RPAD('ab', 8, 'xy') is 'abxyxyxy'.
  • PostgreSQL and Oracle pad with spaces when the third argument is omitted; MySQL requires it. Oracle measures the length in display width, which matches characters except in some multibyte character sets.

Questions about RPAD

How do I right-pad in SQL Server?

There is no RPAD. LEFT(str + REPLICATE(pad, n), n) pads and truncates to n characters; LEFT(str + SPACE(n), n) for spaces.

Does RPAD truncate long strings?

Yes. The result is exactly length characters, so RPAD also works as a fixed-width clip. In PostgreSQL an empty pad string means no padding at all.

Is RPAD case-sensitive or collation-aware?

Neither applies: padding appends the pad pattern verbatim and never compares characters.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, MySQL, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.