Lesson

MySQL REPEAT() Function

10 min reading
Free Course

MySQL REPEAT() Function

The REPEAT() function builds a new string by repeating an input string a given number of times. Analysts and engineers use it to generate masking masks, divider lines, and lightweight text charts in SQL reports.

Syntax

REPEAT(str, count)
  • str: The character or string pattern to repeat.
  • count: Integer number of repetitions.
  • Return value: Repeated string, '' if count <= 0, or NULL if either argument is NULL.

Unlike SPACE(n), which only repeats single spaces, REPEAT() duplicates any character or multi-character sequence.

Practical Example

Suppose you want a quick visual bar chart comparing product prices in demo_products, printing one '#' per $25 tier alongside a masked SKU prefix.

SELECT
    product_id,
    product_name,
    unit_price,
    REPEAT('#', FLOOR(unit_price / 25)) AS price_bar,
    CONCAT(REPEAT('*', 4), RIGHT(sku, 4)) AS masked_sku
FROM demo_products
ORDER BY unit_price DESC;
product_id product_name unit_price price_bar masked_sku
5 Standing Desk 150.00 ###### ****9042
2 Desk Lamp 75.00 ### ****1180
9 Mouse Pad 18.00 "" ****0045

In row 9, FLOOR(18.00 / 25) evaluates to 0, so REPEAT('#', 0) cleanly produces an empty string ''.

Common Mistakes & NULL Behavior

  • Exceeding max_allowed_packet: If the repeated output exceeds the server's max_allowed_packet size (or memory limits), REPEAT() returns NULL and logs a warning. Guard large dynamic counts with LEAST(count, 1000).
  • Negative or zero counts: REPEAT('x', -5) and REPEAT('x', 0) return '', never an error.
  • NULL propagation: If str or count is NULL, REPEAT() returns NULL.

Frequently Asked Questions

What is the difference between REPEAT(' ', n) and SPACE(n)?

Both return n spaces. SPACE(n) is more concise when you only need whitespace, whereas REPEAT() works with any character or word.

Can REPEAT() accept a decimal count?

MySQL rounds or truncates numeric expressions to an integer depending on context, so wrap calculations in FLOOR(), CEIL(), or ROUND() explicitly for predictable output.

What happens if str is an empty string?

REPEAT('', 10) returns '' because repeating zero characters still yields zero characters.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum