Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2011
    Posts
    1

    Unanswered: 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.

  2. #2
    Join Date
    Sep 2009
    Location
    San Sebastian, Spain
    Posts
    880
    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
    Certified Oracle DBA/Certified MySQL Expert (DBA & Cluster DBA)
    http://www.it-iss.com
    Follow me on Twitter

  3. #3
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    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

    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •