How to Repeat a String with MariaDB REPEAT()

MariaDB’s REPEAT(str, count) returns count copies of str joined together. REPEAT('123', 4) returns 123123123123. A zero or negative count gives an empty string. If the string or count is NULL, the result is NULL.

Check the return value for different counts

Pass an integer as the second argument to REPEAT(). Spaces in the input are copied along with the other characters. The table varies the count while keeping the text at '123'.

Count Return value
4 123123123123
0 Empty string
-1 Empty string
NULL NULL
SELECT REPEAT('123', 4) AS repeated,
       CHAR_LENGTH(REPEAT('123', 0)) AS zero_count_length,
       CHAR_LENGTH(REPEAT('123', -1)) AS negative_count_length,
       REPEAT(NULL, 4) IS NULL AS missing_text,
       REPEAT('123', NULL) IS NULL AS missing_count;

Both length columns are 0, and both IS NULL checks return 1. Some clients display an empty string and NULL similarly, so use a length check and IS NULL to tell them apart.

Repeat a separator or pad to a fixed width

For a specific number of separators, use REPEAT() to produce the separators and CONCAT() to attach the surrounding values. To bring an identifier to a fixed total width, use LPAD() to pad on the left.

SELECT CONCAT('A', REPEAT('-', 4), 'B') AS label,
       LPAD('123', 6, '0') AS padded,
       LPAD('1234567', 6, '0') AS clipped;

label is A----B and padded is 000123. LPAD() shortens input that is already longer than the target, so clipped is 123456. Check for longer input first when the whole identifier must be preserved.

Measure characters and bytes

CHAR_LENGTH() counts characters and OCTET_LENGTH() counts bytes. This query converts the UTF-8 bytes E282AC to the utf8mb4 string € and repeats it three times.

SELECT REPEAT(sample, 3) AS repeated,
       CHAR_LENGTH(REPEAT(sample, 3)) AS characters,
       OCTET_LENGTH(REPEAT(sample, 3)) AS bytes
FROM (SELECT CONVERT(0xE282AC USING utf8mb4) AS sample) AS utf8_sample;

With a UTF-8 client, the text displays as €€€. The result contains 3 characters and 9 bytes. Use the byte count when estimating storage or transfer size.

Estimate the size before building a long string

For a nonnegative count, estimate the size of a repeated string as OCTET_LENGTH(str) × count. Server settings such as max_allowed_packet constrain large intermediate results. This query checks the current session’s limit and the size of a small example without building the repeated text.

SELECT @@SESSION.max_allowed_packet AS packet_limit_bytes,
       OCTET_LENGTH('ab') * 4 AS expected_bytes;

The example takes 8 bytes, and the session limit depends on the server configuration. When an application accepts a repeat count, cap it based on the expected byte size. If both arguments are present but the result is unexpectedly NULL, run SHOW WARNINGS immediately afterward to investigate.