SQL REPLICATE function
Builds runs of a character or pattern for padding, masking and test data. Three names for one job, and NULL semantics differ between them.
- 類別
- Strings
- Returns
string- In this category
- 35 of 172
語法
REPLICATE(string, n)
REPEAT(string, n)
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | 是 | result is capped by the string type's max length |
| PostgreSQL | 是 | spelled repeat() |
| MySQL | 是 | Supported under this name. |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Not built in | No built-in equivalent. |
範例
SQL Server
SELECT REPLICATE('ab', 3) AS r; -- ababab
PostgreSQL
SELECT repeat('ab', 3) AS r; -- ababab
MySQL
SELECT REPEAT('ab', 3) AS r; -- ababab
小知識
- SQL Server: REPLICATE('x', -1) returns NULL; MySQL's REPEAT returns '' for n <= 0. Edge inputs do not agree across engines.
- The result is bounded by the argument's type: REPLICATE over a varchar literal stops at 8000 bytes silently. Cast to varchar(max) to keep going.
- Oracle has no equivalent: RPAD/LPAD repeat a pattern up to a total length (RPAD('ab', 7, 'ab') is 'abababa'), so you compute a length instead of a count.
- SQLite has neither function. replace(printf('%*s', n, ''), ' ', 'ab') repeats 'ab' n times: printf builds n spaces, replace swaps each one.
Questions about REPLICATE / REPEAT
Why did my REPLICATE result get cut off?
The input was a non-max varchar, so the output capped at 8000 bytes silently. REPLICATE(CAST('x' AS varchar(max)), 10000) keeps the full run.
What is Oracle's alternative to REPLICATE?
RPAD and LPAD repeat a pattern until a total length is reached: RPAD('-', 10, '-') gives a 10-dash rule. There is no repeat-n-times function.
Does REPLICATE('x', 0) return NULL or ''?
Empty string on SQL Server and MySQL; NULL only for negative counts on SQL Server. MySQL returns '' for 0 and negatives alike.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Walk a bill of materials Snippet
- Mask payment card numbers in SQL (show last 4) Snippet
- Mask names in query results Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL.
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.