0

In one of my queries, I was trying to sort by a column that had a varchar data type.
I wanted to show columns that had a space after the columns that had empty strings, but the output of ORDER BY did not work as I expected it to (in fact it surprised me).

Here is a SQL FIDDLE that shows the problem.

I have researched this issue and the only partially relevant article I found is this.

What I want to know is why would SQL Server do this, and what can I do to force the sorting to consider these values as different?

Thanks in advance.

user2989408
  • 3,127
  • 1
  • 17
  • 15

2 Answers2

2

Use the DATALENGTH() function

SELECT *
FROM Tab
ORDER BY DATALENGTH(val)
Anon
  • 10,660
  • 1
  • 29
  • 31
1

You can differentiate in the ORDER BY by replacing a space with something:

SELECT * 
FROM Tab 
ORDER BY LEN(REPLACE(val,' ','X'));

Demo: SQL Fiddle

As for why SQL Server behaves this way I can't shed any light.

Hart CO
  • 34,064
  • 6
  • 48
  • 63
  • I was more interested in knowing why this was happening? If it was just about sorting, I could have replaced the space with a character and achieved that. Also my column has values too, it saves user names. – user2989408 Feb 06 '14 at 22:16
  • @user2989408 The 'why' seems to be answered here: http://stackoverflow.com/questions/1399844/sql-server-2008-empty-string-vs-space If you need help in getting sorting to go a certain way then post some sample data. – Hart CO Feb 06 '14 at 22:21