// strings reference

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.

Categoria
Strings
Returns
string
In this category
35 of 172

Sintaxe

REPLICATE(string, n)
REPEAT(string, n)

Each block is a separate form. The support table and the examples show which engine takes which.

Suporte a mecanismos

MotorSupportNotas
SQL Server Sim result is capped by the string type's max length
PostgreSQL Sim spelled repeat()
MySQL Sim Supported under this name.
SQLite Not built in No built-in equivalent.
Oracle Not built in No built-in equivalent.

Exemplos

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

Bom saber

  • 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.

// 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.