Skip to content

SPACE String Function

The SPACE string function returns a string of repeated spaces. The syntax of the SPACE string function is as follows:

SPACE ( < integer_expression > )

The < integer_expression > is a positive integer that indicates the number of spaces. If < integer_expression > is negative, a NULL string is returned.

Sample Uses of the SPACE String Function

Here are sample uses of the SPACE string function

Usage #1 : Right-Align Text

DECLARE @Header1 VARCHAR(25) = 'Database, LLC'
DECLARE @Header2 VARCHAR(25) = '1234 1st Street'
DECLARE @Header3 VARCHAR(25) = 'Somewhere City, NY 01001'
PRINT SPACE(50 - LEN(@Header1)) + @Header1
PRINT SPACE(50 - LEN(@Header2)) + @Header2
PRINT SPACE(50 - LEN(@Header3)) + @Header3
Output
---------------
                             Database Helper, LLC
                                   1234 1st Street
                          Somewhere City, NY 01001

Usage #2 : Center-Align Text

DECLARE @Header1 VARCHAR(25) = 'Database Helper, LLC'
DECLARE @Header2 VARCHAR(25) = '1234 1st Street'
DECLARE @Header3 VARCHAR(25) = 'Somewhere City, NY 01001'
PRINT SPACE((50 - LEN(@Header1))/2) + @Header1
PRINT SPACE((50 - LEN(@Header2))/2) + @Header2
PRINT SPACE((50 - LEN(@Header3))/2) + @Header3
Output
------------
               Database Helper, LLC
                 1234 1st Street
             Somewhere City, NY 01001

Usage #3 : Justify Text

DECLARE @Contents TABLE ( 
    [Title]         VARCHAR(50),
    [PageNumber]    INT
)

INSERT INTO @Contents ( [Title], [PageNumber] )
VALUES ( 'Introduction', 1)

INSERT INTO @Contents ( [Title], [PageNumber] )
VALUES ( 'Table of Contents', 2)

INSERT INTO @Contents ( [Title], [PageNumber] )
VALUES ( 'Index', 100)

SELECT [Title] + SPACE(50 - LEN([Title])) +
       RIGHT(SPACE(5) + CAST([PageNumber] AS VARCHAR(5)), 5) AS [Output]
FROM @Contents
Output
------------
Introduction                                          1
Table of Contents                                     2
Index                                               100