SPACE Function in SQL

This string function of SQL adds the given number of spaces between two characters or a set of strings.

Syntax of SPACE String Function

Syntax1: This syntax uses the SPACE function with the column names of the SQL table:

In the syntax, we have to specify the name of those columns on which we want to use SPACE function.

Syntax2: This syntax uses the SPACE function with two or more strings:

Syntax3: This syntax uses the SPACE function with two or more single characters:

Syntax4: We can also use the given syntax to specify the space:

Examples of SPACE String function

Example 1: The following SELECT query shows the 15 space in the result:

Output:

15_Spaces
'               '

Example 2: The following SELECT query adds the 10 spaces after the JavaTpoint Word:

SELECT 'JavaTpoint' + SPACE(10) AS 10_Space;

Output:

'JavaTpoint          '
10

Example 3: The following SELECT query adds the 20 spaces between two single characters:

Output:

20_Spaces
'S                    K'

Example 4: The following SELECT query adds the 15 spaces between the multiple given strings:

Output:

20_Spaces
'New'               'Delhi'                'is'               'the'               'Capital'               'of'               'India'

Example 5: This example uses the SPACE function with the SQL table

In this example, we are going to create a new table that helps in executing the space function with the string columns.

The syntax for creating the new table in the SQL database is as follows:

The following CREATE statement creates the Student_Grade table:

The below INSERT queries insert the records of students with grades and marks in the Student_Grade table:

The following SELECT statement displays the inserted records of the above Student_Grade table:


Roll_NoFirst_NameLast_NameFirst_CitySecond_CityNew_CityHindi_MarksMaths_MarksGrade
10AmanSharmaLucknowChandigarhGhaziabad8895A2
02VishalSharmaChandigarhGhaziabadGhaziabad9582A1
07RajGuptaDelhiGhaziabadLucknow9195A1
04YashSinghaniaGhaziabadDelhiLucknow8582A2
11VinayRoyDelhiKanpurGhaziabad9597A1
16ManojGuptaGhaziabadMeerutChandigarh9590B1
19RamGuptaLucknowGhaziabadChandigarh8995A2

The following SELECT query uses the SPACE function with the First_Name and Last_Name column of the above Student_Grade table:

This SQL statement adds the 10 spaces between the first name and last name of each student.

Output:

First_NameLast_Name10_space
AmanSharma
Aman          Sharma
VishalSharma
Vishal          Sharma
RajGupta
Raj          Gupta
YashSinghania
Yash          Singhania
VinayRoy
Vinay          Roy
ManojGupta
Manoj          Gupta
RamGupta
Ram          Gupta

The following SELECT query uses the SPACE function with the First_Name and Grade column of those students whose Roll_No is greater than 2 in the above Student_Grade table:

Output:

Roll_NoFirst_Name + SPACE(5) + Grade
07
Raj     A1
04
Yash     A2
11
Vinay     A1
16
Manoj     B1
19
Ram     A2