Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Difference between SPACE(2) + '|' + SPACE(2) and ‘ | ‘?

Tags:

sql

sql-server

Is there any difference between using SPACE(2) + '|' + SPACE(2) or just ' | '? I know the output will be the same but I'm not sure about other aspects... Actually I can't see the point in using SPACE function if there's no difference...

Thanks!

like image 777
D. Caan Avatar asked Sep 16 '13 12:09

D. Caan


People also ask

What are spaces in SQL?

SPACE() : This function in SQL Server helps to return a string that has a specified number of spaces. This function is also available in MYSQL with the same name.

How do you put a space in SQL query?

In many SQL relational database you will have to use the RPAD function to insert spaces into a character string. That also works in Vertica. However, for a more robust solution, Vertica provides the built-in function SPACE which returns the specified number of blank spaces.

How do I add space between two words in SQL?

In SQL Server, you can use the T-SQL SPACE() function to generate a specific number of spaces. This can be handy for adding spaces within a string, for example, when concatenating two or more strings.


2 Answers

The first difference which comes to my mind is the amount of spaces. Let's say you'd like to write 20 spaces, a word and another 20 spaces:

'                    abcd                    '

How many spaces are there? Much more useful:

SPACE(20)+'abcd'+SPACE(20)

Isn't it?

There are many cases in which you edit somebody's code generating SQL queries. It's more than probable that you delete a space somewhere and not possible to debug it. There's no such problem if SPACE function is used.

like image 128
makciook Avatar answered Oct 20 '22 16:10

makciook


I agree with others who have answered this that SPACE() is useful to indicate the number of spaces used or to add large numbers of spaces.

Using SPACE may also be simpler if you want to generate a fixed-width format file - you can use the data length as a parameter e.g.

SELECT 
  name + SPACE(20-LEN(name))
FROM
  SomeTableWithNames
like image 22
penguat Avatar answered Oct 20 '22 17:10

penguat