SQL Server SPACE Function

Summary: in this tutorial, you will learn how to use the SQL Server SPACE() function to generate a string of repeated spaces.

Introduction to SQL Server SPACE() function #

The SPACE() function returns a string of repeated spaces. The following shows the syntax of the SPACE() function:

SPACE(count);
Code language: SQL (Structured Query Language) (sql)

In this syntax, count is a positive integer that specifies the number of spaces. If count is negative, the function will return NULL.

SQL Server SPACE() function example #

Let’s take some examples of using the SPACE() function.

A) Using SPACE() function with literal strings #

This example concatenates three strings 'John', space, and 'Doe' into one. Instead of using the space literal ' ', we use the SPACE() function:

SELECT 
    'John' + SPACE(1) + 'Doe' full_name;Code language: SQL (Structured Query Language) (sql)

Here is the output:

full_name
---------
John Doe

(1 row affected)

B) Using SPACE() function with table column #

The following example uses the SPACE() function to concatenate the first name, space, and last name in the sales.customers table into the full name:

SELECT
    first_name + SPACE(1) + last_name full_name
FROM
    sales.customers
ORDER BY
    first_name,
    last_name;
Code language: SQL (Structured Query Language) (sql)

The following picture shows the partial output:

SQL Server SPACE Function Example

In this tutorial, you have learned how to use the SQL Server SPACE() function to generate a sequence of spaces.

Was this tutorial helpful?