Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL CASE statements using dates

Tags:

sql

mysql

case

I'm trying to use a CASE statement in a SQL query I have and it's not working the way I thought it would do.

Basically, I have three scenarios I need to fulfil and it using a date field so for example I have the following data:

id | date_activated
1  | 2011-10-10 07:00:06
2  | 2011-03-12 10:00:00
3  | 2011-11-27 18:10:36
4  | 2010-01-25 14:30:43
5  | 0000-00-00 00:00:00

using the following SQL:

select id,
case date_activated
when date_activated > '2011-11-23 18:30:00' then 'after'
when date_activated > '2010-01-20 00:00:00' then 'before'
else 'not yet'
end as date_note
from table1

should bring out:

id | date_activated       | date_note
1  | 2011-10-10 07:00:06  | before
2  | 2011-03-12 10:00:00  | before
3  | 2011-11-27 18:10:36  | after
4  | 2010-01-25 14:30:43  | before
5  | 0000-00-00 00:00:00  | not yet

However, it's pulling this out:

id | date_activated       | date_note
1  | 2011-10-10 07:00:06  | not yet
2  | 2011-03-12 10:00:00  | not yet
3  | 2011-11-27 18:10:36  | not yet
4  | 2010-01-25 14:30:43  | not yet
5  | 0000-00-00 00:00:00  | after

I can't understand what I'm doing wrong but I bet it's something simple!

like image 991
Jo H Avatar asked Nov 28 '11 14:11

Jo H


People also ask

How do I query a date in MySQL?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column.

Can we use CASE statement in MySQL?

The MySQL CASE StatementThe CASE statement goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.

Is date function in MySQL?

MySQL date/time Functions. The date() function is used to get the date from given date/datetime. The adddata() function is used to get the date in which some time/date intervals are added. The curdate() function is used to get the current date.

How do you insert a date in MySQL?

The default way to store a date in a MySQL database is by using DATE. The proper format of a DATE is: YYYY-MM-DD.


1 Answers

Try this one -

SELECT
  id,
  CASE
    WHEN date_activated > '2011-11-23 18:30:00' THEN 'after'
    WHEN date_activated > '2010-01-20 00:00:00' THEN 'before'
    ELSE 'not yet'
  END AS date_note
FROM table1;

There are two CASE flow functions in MySQL, you should use one with conditions.

like image 91
Devart Avatar answered Sep 28 '22 04:09

Devart