Friday, December 20, 2024

MySQL SPACE() Function

 The SPACE() function in MySQL is used to return a string consisting of a specified number of spaces. It takes a single integer argument that specifies the number of spaces to be returned.

Syntax:

SPACE(N)
  • N: The number of spaces to return. It should be a non-negative integer.

Example Usage:

  1. Basic Example:

    SELECT SPACE(5);
    

    This will return a string with 5 spaces:

    "     "
    
  2. Concatenating with Other Strings: You can use SPACE() to create a certain number of spaces between strings:

    SELECT CONCAT('Hello', SPACE(3), 'World');
    

    This will return:

    "Hello   World"
    
  3. Used in Formatting: It can be useful for padding data for alignment or formatting in reports:

    SELECT CONCAT('Item', SPACE(10), 'Price');
    

    This can help in generating well-aligned output if the data is printed in a console or report.

Important Notes:

  • If you pass a negative value or zero to the SPACE() function, it will return an empty string.
  • SPACE() is often used in conjunction with other string functions like CONCAT() or CONCAT_WS() to format the output.

No comments:

Post a Comment