MySQL SPACE() Function
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
Nspaces,''whenNis zero or negative, orNULLifNisNULL.
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)orSPACE(-4)returns an empty string'', not an error. - HTML collapses repeated spaces: When rendering
SPACE(5)inside a web page without preformatted tags or CSSwhite-space: pre, browsers collapse consecutive spaces into one space. - Packet size limits: Requesting millions of spaces beyond
max_allowed_packetreturnsNULLwith a warning. - NULL input:
SPACE(NULL)returnsNULL, which turns an outerCONCAT()expression intoNULLunless wrapped inCOALESCE().
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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.