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 > if in select query

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 04-05-11, 14:23
kiminkibu kiminkibu is offline
Registered User
 
Join Date: Apr 2011
Posts: 1
if in select query

Hi,
I select 2 fields, and if the second is null I want to change the query.

in example:
I have events. All of them has start date and end date. But if its a one day event, it doesn't have an end date - its null. if its null, I have to use start date. how can I do that?

it should be sth like this:
select startdate,enddate from events where startdate>='xxxx-xx-xx' if(enddate!=null){ and enddate<='xxxx-xx-xx'} else{ startdate<='xxxx-xx-xx'}

but I don't know the if statement in select.

any help will be appreciated.
Reply With Quote
  #2 (permalink)  
Old 04-05-11, 17:44
it-iss.com it-iss.com is offline
Registered User
 
Join Date: Sep 2009
Location: San Sebastian, Spain
Posts: 620
The syntax for an IF statement is IF(condition, true expression, false expression).

SELECT startdate,enddate FROM events WHERE startdate>='xxxx-xx-xx' AND if(enddate IS NOT NULL,enddate,startdate) <='xxxx-xx-xx'
__________________
Ronan Cashell
Senior Oracle/MySQL DBA
http://www.it-iss.com
Reply With Quote
  #3 (permalink)  
Old 04-05-11, 18:20
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
you can change this --
Code:
IF(enddate IS NOT NULL,enddate,startdate)
to this --
Code:
COALESCE(enddate,startdate)
not only is it simpler, but COALESCE is standard SQL while IF is not

__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
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