troubleshooting Question

SQL Server unexpected (and wrong) ORDER BY behavior

Avatar of Russ Suter
Russ Suter asked on
Microsoft SQL ServerSQL
2 Comments1 Solution68 ViewsLast Modified:
I may have found a bug in Microsoft SQL Server and I'm hoping someone can shed some light on this. I've created a very simple example that fully illustrates the problem. If you run the following SQL statements in SQL Server Management Studio you'll see the problem.
CREATE TABLE #ORDERTEST
(
  OPER nchar(1),
  ORDINAL INT
)

INSERT INTO #ORDERTEST VALUES('+', 1)
INSERT INTO #ORDERTEST VALUES('-', 2)
INSERT INTO #ORDERTEST VALUES('+', 3)

SELECT * FROM #ORDERTEST ORDER BY OPER

DROP TABLE #ORDERTEST
This creates a super simple temp table, inserts some values, and selects them. The oddity here is that it orders the '-' first. This despite fact that the '+' character has an ASCII value of 43 and '-' has an ASCII value of 45. Even weirder than this is if you replace the nchar(1) with a char(1) declaration it returns the result set ordered in reverse, correctly prioritizing the '+' character over the '-'.
What's going on here? We had to write additional code to catch this condition and order it correctly. I'm wondering where else a similar gotcha might be lurking.
ASKER CERTIFIED SOLUTION
lcohan
Database Analyst

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros