Lesson

MySQL SPACE() Function

10 min reading
Free Course

MySQL SPACE() Function

The SPACE() function generates a string made up of N consecutive ASCII space characters (' '). It offers a readable shorthand for REPEAT(' ', N) when building indented reports or fixed-width fields.

Syntax

SPACE(N)
  • N: Integer count of space characters to generate.
  • Return value: String of N spaces, '' when N is zero or negative, or NULL if N is NULL.

Because SPACE() returns a standard VARCHAR string, you can feed it straight into CONCAT() or CONCAT_WS(). It helps build fixed-width mainframe exports, indented hierarchy views, and readable terminal reports directly inside SQL.

Practical Example

Suppose you want to format a clean fixed-column directory export from demo_employees by inserting dynamic spacing between each employee's name and department.

SELECT
    employee_id,
    CONCAT(
        full_name,
        SPACE(GREATEST(1, 20 - CHAR_LENGTH(full_name))),
        department
    ) AS aligned_row
FROM demo_employees
ORDER BY employee_id;
employee_id aligned_row
1 Elena Park Engineering
2 Omar Hassan Support
3 Li Wei Finance

Using GREATEST(1, ...) guarantees at least one separating space even if a future employee name approaches or passes 20 characters.

Common Mistakes & NULL Behavior

  • Negative or zero values: Passing SPACE(0) or SPACE(-4) returns an empty string '', not an error.
  • HTML collapses repeated spaces: When rendering SPACE(5) inside a web page without preformatted tags or CSS white-space: pre, browsers collapse consecutive spaces into one space.
  • Packet size limits: Requesting millions of spaces beyond max_allowed_packet returns NULL with a warning.
  • NULL input: SPACE(NULL) returns NULL, which turns an outer CONCAT() expression into NULL unless wrapped in COALESCE().

Frequently Asked Questions

When should I use SPACE(N) instead of RPAD()?

Use SPACE(N) when you want to insert a specific gap between two expressions. Use RPAD(col, width, ' ') when you want a column padded to an exact total width.

Does SPACE() support tab characters or non-breaking spaces?

No. SPACE() always produces standard ASCII spaces (0x20). Use REPEAT(' ', N) when you need tab characters instead.

Is SPACE(N) faster than REPEAT(' ', N)?

Performance is virtually identical; SPACE(N) simply makes whitespace intent clearer to read in reports and export queries.

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