>SQL Server: Sorting Data in Ascending Order but NULL at the End


>

Sometime a very simple task becomes challenging for a developer. A friend of mine, who is a talented database developer, asked me that “He needs to sort his query output rows (as we normally do) but he need to push NULL values at the end”.  To be very frank, first I laughed at his question as I thought it’s a simple ORDER BY clause case, but when I tried it, I failed in first attempt ;).
Anyhow, here is a simple solution of sorting any column in ascending order but with NULL at the end.
-- Create temporary
CREATE TABLE #TestSort (RecID INT, RecDesc VARCHAR(50),RecDate DATETIME)
-- Insert rows
INSERT INTO #TestSort
SELECT 1,'FirstRec','2001-07-01 00:00:00'
UNION ALL
SELECT 2,NULL,'2001-08-01 00:00:00'
UNION ALL
SELECT NULL,'ThirdRec',NULL
UNION ALL
SELECT 0,'ForthRec',NULL
UNION ALL
SELECT 5,NULL,'2001-11-01 00:00:00'
GO
---- Sort by INT column "RecID"
SELECT * FROM #TestSort
ORDER BY CASE  WHEN RecID IS NULL  THEN 1 ELSE 0 END,RecID
--- Sort by VARCHAR column "RecDesc"
SELECT * FROM #TestSort
ORDER BY CASE  WHEN RecDesc IS NULL  THEN 1 ELSE 0 END,RecDesc
--- Sort by DATETIME column "RecDate"
SELECT * FROM #TestSort
ORDER BY CASE  WHEN RecDate IS NULL  THEN 1 ELSE 0 END,RecDate
 
-- Drop table when not required
DROP TABLE  #testsort

http://rcm.amazon.com/e/cm?t=co04b8-20&o=1&p=8&l=bpl&asins=B004U9USEA&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=FFFFFF&bg1=FFFFFF&f=ifrhttp://rcm.amazon.com/e/cm?t=co04b8-20&o=1&p=8&l=bpl&asins=1590599586&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=FFFFFF&bg1=FFFFFF&f=ifr

Advertisements

Posted on April 22, 2011, in Sql Server 2005, Sql Server 2008, TSQL Tips n Tricks. Bookmark the permalink. 1 Comment.

  1. order by case when isnull(vw.TradeShow,'')='' then 'z' else vw.TradeShow end,ClientName

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: