Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Sorting and hyphens

Is there a way to easily sort in SQL Server 2005 while ignoring hyphens in a string field? Currently I have to do a REPLACE(fieldname,'-','') or a function to remove the hyphen in the sort clause. I was hoping there was a flag I could set at the top of the stored procedure or something.

Access and the GridView default sorting seems to ignore the hypen in strings.

like image 620
tidge Avatar asked Dec 11 '08 21:12

tidge


People also ask

Are hyphens allowed in SQL?

Progress ABL/4GL allows table and field names to be created with with hyphens and start with underscore characters. Under SQL-92 table and field names should not: Contain SQL special characters like the hyphen/dash/minus character. Start with non-alphabetic characters like the underscore.

How do you Sortby in SQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do I sort 3 columns in SQL?

Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first.


1 Answers

I learned something new, just like you as well

I believe the difference is between a "String Sort" vs a "Word Sort" (ignores hyphen)

Sample difference between WORD sort and STRING sort http://andrusdevelopment.blogspot.com/2007/10/string-sort-vs-word-sort-in-net.html

From Microsoft http://support.microsoft.com/kb/322112

For example, if you are using the SQL collation "SQL_Latin1_General_CP1_CI_AS", the non-Unicode string 'a-c' is less than the string 'ab' because the hyphen ("-") is sorted as a separate character that comes before "b". However, if you convert these strings to Unicode and you perform the same comparison, the Unicode string N'a-c' is considered to be greater than N'ab' because the Unicode sorting rules use a "word sort" that ignores the hyphen.

I did some sample code you can also play with the COLLATE to find the one to work with your sorting

DECLARE @test TABLE
(string VARCHAR(50))

INSERT INTO @test SELECT 'co-op'
INSERT INTO @test SELECT 'co op'
INSERT INTO @test SELECT 'co_op'

SELECT * FROM @test ORDER BY string --COLLATE SQL_Latin1_General_Cp1_CI_AS
--co op
--co-op
--co_op

SELECT * FROM @test ORDER BY CAST(string AS NVARCHAR(50)) --COLLATE SQL_Latin1_General_Cp1_CI_AS
--co op
--co_op
--co-op
like image 194
jerryhung Avatar answered Sep 23 '22 02:09

jerryhung