MySQL SPACE() Function



The MySQL SPACE() function is used to insert a specified number of spaces into a string. It takes a single argument, which is the number of spaces to be inserted.

This function is often used in combination with the CONCAT() function to create formatted strings with specific spacing between words or columns.

Syntax

Following is the syntax of MySQL SPACE() function −

SPACE(N)

Parameters

This function takes an integer value as a parameter.

Return Value

This function returns a string consisting of the specified number of space characters.

Example

In the following example, the SPACE() function returns a string with four spaces −

SELECT SPACE(4);

Following is the output of the above code −

SPACE(4)
    

Example

In this example, the SPACE() function is used to add spaces between the words "Welcome," "To," and "Tutorialspoint" when using CONCAT() function −

SELECT CONCAT('Welcome', SPACE(5), 'To', SPACE(5), 'Tutorialspoint');

Output of the above code is as shown below −

CONCAT('Welcome', SPACE(5), 'To', SPACE(5), 'Tutorialspoint')
Welcome     To     Tutorialspoint

Example

Let us create a table named "PLAYERS" and insert records into it using CREATE and INSERT statements as shown below −

CREATE TABLE PLAYERS(
   ID INT,
   First_Name VARCHAR(255),
   Last_Name VARCHAR(255),
   Date_Of_Birth date,
   Place_Of_Birth VARCHAR(255),
   Country VARCHAR(255),
   PRIMARY KEY (ID)
);

Now, let us insert records into it using the INSERT statement −

INSERT INTO PLAYERS VALUES
(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'),
(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'),
(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'),
(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'),
(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'),
(6, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');

The PLAYERS table obtained is as follows −

ID First_Name Last_Name Date_Of_Birth Place_Of_Birth Country
1 Shikhar Dhawan 1981-12-05 Delhi India
2 Jonathan Trott 1981-04-22 CapeTown SouthAfrica
3 Kumara Sangakkara 1977-10-27 Matale Srilanka
4 Virat Kohli 1988-11-05 Delhi India
5 Rohit Sharma 1987-04-30 Nagpur India
6 James Anderson 1982-06-30 Burnley England

Following query concatenates/joins the First_Name and Last_Name values of the PLAYERS table and displays the result as FullName. Here we are using the SPACE() function to add space between the two names −

SELECT ID, First_Name, Last_Name, Country, CONCAT(First_Name, SPACE(1), LAST_Name) as Name
FROM PLAYERS;

Output

After executing the above code, we get the following output −

ID First_Name Last_Name Country Name
1 Shikhar Dhawan India Shikhar Dhawan
2 Jonathan Trott SouthAfrica Jonathan Trott
3 Kumara Sangakkara Srilanka Kumara Sangakkara
4 Virat Kohli India Virat Kohli
5 Rohit Sharma India Rohit Sharma
6 James Anderson England James Anderson
mysql-space-function.htm
Advertisements