tags:

views:

41

answers:

3

For example:


SELECT * FROM atable ORDER BY num; 

'atable' is:


num  name     
1     a    
3     y    
0     cc    
2     fs

The result is:


num  name     
1     a    
2     fs    
3     y    
0     cc

But I want it to be:


num  name  
0     cc    
1     a    
2     fs    
3     y
A: 
SELECT * FROM atable 
ORDER BY ISNULL(CAST(num as int), 0); 
Mitch Wheat
A char value of '0' will still sort before a char value of '1'
Adam Ruth
Thanks, Adam. updated...
Mitch Wheat
+1  A: 

Are you sure that the 0 isn't a null value being displayed as a 0? Nulls can sort either at the top or the bottom, depending on database setting.

Adam Ruth
+1  A: 

I can't reproduce the result you are seeing. The query that you posted should work as you wish it to. Here's my steps to reproduce:

CREATE TABLE atable (num INT NOT NULL, name NVARCHAR(100) NOT NULL);
INSERT INTO atable (num, name) VALUES
(1, 'a'),
(3, 'y'),
(0, 'cc'),
(2, 'fs');
SELECT * FROM atable ORDER BY num;

Result:

0, 'cc'
1, 'a'
2, 'fs'
3, 'y'

Perhaps you could post your create scripts for your table and test data in your question so that we can reproduce your result?

Mark Byers
suspect posters 'num' column is not an int
Mitch Wheat
For completeness, could the OP explain how this answers his question?
Mitch Wheat