Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a space a valid column name in SqlServer?

Tags:

sql-server

See for yourself:

create table #temp ([ ] varchar(1))
insert into #temp values ('1')
select [ ] from #temp

What in the world is the rationale for allowing this?

like image 841
Michael Todd Avatar asked Apr 23 '09 16:04

Michael Todd


People also ask

Can column names have spaces SQL Server?

Column names can contain any valid characters (for example, spaces).

Can an SQL column have a space?

Blanks spaces are restricted in the naming convention of the database object's name and column name of the table. If you want to include the blanks space in the object name or column name, the query and application code must be written differently. You must be careful and precise while writing dynamic SQL queries.

Can column name have space?

To select a column name with spaces, use the back tick symbol with column name. The symbol is ( ` `). Back tick is displayed in the keyboard below the tilde operator ( ~).

Is space considered a character in SQL?

Yes, a space counts as a character. It is a character (ASCII char 32 (20 hex).)


4 Answers

I think the rationale is more along the lines of:

Is it worth preventing this functionality?

I don't know how SQL is coded internally but I would suspect it would take more effort to prevent this then to allow it.

like image 105
JoshBerke Avatar answered Oct 20 '22 11:10

JoshBerke


I use it all the time as a placeholder/seperator when debugging complex queries. I might have something like this:

SELECT a.*, ' ' as [ ], b.*
FROM a
LEFT JOIN b on ...

This way I get a blank section in between the two tables so I can easily see in the results where one stops and the other starts.

Later on when I get the results and performance I need I'll change the select clause to only use the columns I care about.

That said, I suppose there's no reason I couldn't use something else for the column name.

like image 36
Joel Coehoorn Avatar answered Oct 20 '22 10:10

Joel Coehoorn


Space is an acceptable character, as some people like to have spaces in their column names. And if it can be a part of a column name then why not a column name by itself?

Why do they ever do it will remain a mystery to me, as it makes programming so much more difficult (constantly enclosing everything in "" or []). I have actually seen a column name with a question mark, which is definitely something I would avoid using in any identifier, but it's possible, still.

like image 4
Peter Perháč Avatar answered Oct 20 '22 11:10

Peter Perháč


Any valid characters can be used in between [] to define the column & table names. Given that something like [A Column] is valid (with space), there is no reason to prevent a single space as a column name.

However, trailing spaces are removed so.

[ ] and [  ] (1 & 2 spaces) 
will be both treated as
[ ] (1 space).
like image 4
Steven Avatar answered Oct 20 '22 11:10

Steven