SQL SPACE function
Builds a run of spaces for padding and alignment inside string expressions, so 'a' + SPACE(3) + 'b' reads better than a magic literal.
- Categoria
- Strings
- Returns
string- In this category
- 34 of 172
Sintaxe
SPACE(n)
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | SPACE is shorthand for REPLICATE(' ', n) |
| PostgreSQL | Not built in | No built-in equivalent. |
| MySQL | Sim | SPACE(0) and negative counts return an empty string |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Not built in | No built-in equivalent. |
Exemplos
SQL Server
SELECT 'a' + SPACE(3) + 'b' AS gapped; -- a b
MySQL
SELECT CONCAT('a', SPACE(3), 'b') AS gapped; -- a b
Bom saber
- SQL Server returns NULL for a negative count, so a computed width can silently blank out a whole expression; GREATEST-guard or CASE it.
- PostgreSQL has repeat(' ', n); Oracle has RPAD(' ', n); SQLite has neither: printf('%*s', n, '') or literal padding.
- Trailing spaces are invisible in result grids, and SQL Server's LEN does not count them: LEN(SPACE(3)) is 0 while DATALENGTH is 3. Padding at the end of a value is easy to lose track of.
- For repeated non-space fills, REPLICATE (SQL Server) or REPEAT (MySQL, PostgreSQL) take any string.
Questions about SPACE
Is SPACE(n) the same as REPLICATE(' ', n)?
Yes on SQL Server; it is defined that way. The value is readability: the intent survives review better than a magic number of quoted spaces.
Why did my SPACE call return NULL?
A negative n on SQL Server yields NULL, which then poisons the whole + expression. Clamp computed widths to zero or above.
Does PostgreSQL have SPACE?
No. Use repeat(' ', n). MySQL and SQL Server are the engines with a SPACE function.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, MySQL.
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.