| | |
Sort Null values at top
Please support our MS SQL advertiser: Intel Parallel Studio Home
Thread Solved |
I have a datetime column in a T-SQL table that I need to sort desc. However, when I do this the NULL values for that field will show up at the bottom. I need them to be at the top of the list, while still having everything else sorted in descending order.
example of query:
example of query:
MS SQL Syntax (Toggle Plain Text)
SELECT completed FROM TABLE ORDER BY completed DESC
•
•
Join Date: Aug 2008
Posts: 1,160
Reputation:
Solved Threads: 137
add an extra column to the select
MS SQL Syntax (Toggle Plain Text)
SELECT completed, completed IS NULL AS isnull FROM TABLE ORDER BY isnull DESC, completed DESC
Custom Application & Software Development
www.houseshark.net
www.houseshark.net
•
•
Join Date: Aug 2008
Posts: 1,160
Reputation:
Solved Threads: 137
my bad, used my sql
here is the correct way
the order by might need to be changed, based upon the column type of completed, but the select works
here is the correct way
MS SQL Syntax (Toggle Plain Text)
SELECT completed, ISNULL(completed, NULL) AS 'isnull' FROM TABLE ORDER BY isnull DESC, completed DESC
the order by might need to be changed, based upon the column type of completed, but the select works
Custom Application & Software Development
www.houseshark.net
www.houseshark.net
•
•
Join Date: Aug 2008
Posts: 1,160
Reputation:
Solved Threads: 137
Change
to
MS SQL Syntax (Toggle Plain Text)
ORDER BY isnull DESC
to
MS SQL Syntax (Toggle Plain Text)
ORDER BY isnull
Custom Application & Software Development
www.houseshark.net
www.houseshark.net
That certainly got me a lot closer. However, things are ordered as if I had done this query:
Rather than one that is ordered by desc, with NULL values listed first.
MS SQL Syntax (Toggle Plain Text)
SELECT completed FROM TABLE ORDER BY completed
Rather than one that is ordered by desc, with NULL values listed first.
Last edited by J'Tok; Sep 5th, 2008 at 3:47 pm. Reason: Clarification
•
•
Join Date: Feb 2008
Posts: 42
Reputation:
Solved Threads: 13
Try this one:
MS SQL Syntax (Toggle Plain Text)
SELECT completed FROM TABLE ORDER BY case when completed IS NULL then 0 else 1 end, completed DESC
Hence Wijaya
www.ex-Soft.tk
www.ex-Soft.tk
![]() |
Similar Threads
- Please check my code below (Java)
- Open In New Window Php (PHP)
Other Threads in the MS SQL Forum
- Previous Thread: SQL - Select semi-duplicate rows?
- Next Thread: Interface design - SQLSERVER 2005 to ORACLE Data updation
| Thread Tools | Search this Thread |






