If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Use different column in order by clause if value is NULL

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 06-30-10, 07:34
dajense dajense is offline
Registered User
 
Join Date: Jul 2009
Posts: 17
Use different column in order by clause if value is NULL

Hi,

I need some advice.

Let's say I have a table article(id, publ_date, creat_date) and I want to order this table by publ_date. Problem, sometimes publish date may be NULL, so only if the publ_date for a row is NULL I want MySQL to use the creat_date for the order by clause.

So I need a way to substitute the attribute value within the statement, only if the attribute is NULL, and then only for this specific row. I was thinking of creating a virtual column or using control flow functions, but both are new to me, so if anybody has some experience if this is possible using either of the two or any other ideas how to solve this, I would really appreciate your advice.
Reply With Quote
  #2 (permalink)  
Old 06-30-10, 07:57
shammat shammat is offline
Registered User
 
Join Date: Nov 2003
Posts: 2,407
Something along the lines
Code:
SELECT <your column list>
FROM article
ORDER BY 
   CASE 
      WHEN publ_date IS NULL THEN creat_date
      ELSE publ_date
   END;
Reply With Quote
  #3 (permalink)  
Old 06-30-10, 08:18
dajense dajense is offline
Registered User
 
Join Date: Jul 2009
Posts: 17
Thanks a lot. That's pretty much exactly what I need.
Reply With Quote
  #4 (permalink)  
Old 06-30-10, 08:27
gvee gvee is offline
www.gvee.co.uk
 
Join Date: Jan 2007
Location: UK
Posts: 10,156
Personally, in this scenario I'd use the Coalesce() function
Code:
ORDER
    BY Coalesce(publ_date, creat_date)
__________________
George
Twitter | Blog
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On