Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF statement inside where clause in SQL

Tags:

sql

mysql

I'm developing a calendar app. It stores times in two formats. The table have following columns title, startDate, startTime. If the user provides start time plus start date. The database stores UNIX time stamp(number of seconds since UNIX epok) in the column startTime, while startDate is NULL. If the user only provide a start date, the database stores the date in format nnnn-mm-dd in startDate and NULL in ´startTime`. I have this DB structure, because it's easier to display times around the world, because different timezones have different daylight saving times.

I want select the events that are occurring after a specified date. The client computer provide the server with a UNIX timestamp of the beginning of that day($unix) and a date($date) in the format nnnn-mm-dd to select the correct dates.

The problem is, I don't know how to select those days that are occurring as specified above. This solution is not applicable for me, even though it works:

SELECT *
  FROM events
 WHERE startDate >= '$date'
   OR startTime >= '$unix'

The thing is I have in some rows where unix time stamp is provided in startTime, I also have a date provided in startDate and other reason I which I don't want to explain. And because of that I can't use the solution above.

I need some kind of solution that have an IF statement inside the Where clause like:

SELECT *
  FROM events
 WHERE IF(startTime = NULL, startDate >= '$date', startTime >= '$unix')

I'm just guessing this solution. But is it right?

like image 859
einstein Avatar asked May 13 '11 04:05

einstein


2 Answers

WHERE (startTime IS NULL AND startDate >= '$date')
   OR (startTime IS NOT NULL AND startTime >= '$unix')
like image 68
zerkms Avatar answered Nov 05 '22 10:11

zerkms


All SQL dialects support CASE WHEN:

SELECT *
 FROM events
WHERE CASE WHEN startTime is null
           THEN startDate >= '$date'
           ELSE startTime >= '$unix'
like image 36
Ken Downs Avatar answered Nov 05 '22 09:11

Ken Downs