MySQL SPACE Function | String Specified Space Characters

MySQL SPACE is an inbuilt Function in MySQL. It returns a string containing a specified number of space characters. In this article, we will discuss the MySQL SPACE Function. Also, we will discuss a few examples of using it.

Syntax

SPACE (num_of_characters)

Parameters

The MySQL SPACE Function expects only one parameter. The number of space characters to return is passed as the parameter. Moreover, this number should be greater than or equal to 0.

Return Value

The function returns a string containing the specified number of space characters.

MySQL Space Function

Examples

Let’s consider a few examples of using the function.

Example 1: Simple SELECT Query

mysql> SELECT SPACE(20) as space;
+----------------------+
| space                |
+----------------------+
|                      |
+----------------------+

In the above example, the function returns 20 space characters as specified in the parameters.

Example 2: Using with CONCAT Function

Similarly, you can use this function along with MySQL CONCAT Function to provide spaces between two column values.

mysql> SELECT CONCAT('Bringing', SPACE(3), 'KNOWLEDGE', SPACE(7), 'TOGETHER') as finalString;
+-------------------------------------+
| finalString                         |
+-------------------------------------+
| Bringing   KNOWLEDGE       TOGETHER |
+-------------------------------------+
#First 3 spaces and then 7 spaces

In the above example, we use the Concat Function to concatenate 3 strings with different number of space characters.

Example 3: Negative or Zero Space

When you provide zero (0) as the number of spaces, the function does not return any space. Also, even if you pass a negative value, the function treats it as 0.

#0 Space Characters
mysql> SELECT CONCAT('String1', SPACE(0), 'String2') as final_string;
+----------------+
| final_string   |
+----------------+
| String1String2 |
+----------------+

#Negative Space Characters
mysql> SELECT CONCAT('String1', SPACE(-10), 'String2') as final_string;
+----------------+
| final_string   |
+----------------+
| String1String2 |
+----------------+

Conclusion

In conclusion, we discussed the MySQL SPACE Function. You can read more about it on the MySQL Official Documentation. Additionally, you can learn about more MySQL String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *