Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting date and time of datetime (bug in MySQL?)

Tags:

mysql

Running the following statement, MySQL seems to mix things up:

select now(), if(false, date(now()), time(now()));

| 2013-07-24 10:06:21 | 2010-06-21 00:00:00 |

If replacing the second argument of the if with a literal string, the statement behaves correctly:

select now(), if(false, 'Banana', time(now()));

| 2013-07-24 10:06:21 | 10:06:21 |

Is this a bug or some really strange quirk?

like image 523
forthrin Avatar asked Jul 24 '13 08:07

forthrin


People also ask

How can we get current date and time in MySQL?

MySQL NOW() Function The NOW() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH:MM:SS" (string) or as YYYYMMDDHHMMSS. uuuuuu (numeric).

How can get date in dd mm yyyy format in MySQL?

The following is the output. The following is the query to format the date to YYYY-MM-DD. mysql> select str_to_date(LoginDate,'%d. %m.

How do I get the date and time in UTC in MySQL?

UTC_TIMESTAMP() function in MySQL is used to check current Coordinated Universal Time (UTC) date and time value. It returns the current UTC date and time value in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS. uuu format, depending on whether the function is used in string or numeric context.

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. (In our example, we use a column of the timestamp data type.)


1 Answers

The return type of IF has to be a datatype that includes the types of both arguments. So if one of the arguments is a DATE and the other is a TIME, the type of IF will be DATETIME.

This doesn't seem necessary in the trivial example query, but consider something like:

SELECT IF(col1, date(col2), time(col2)) AS dt
FROM Table

All the rows of the result have to have the same datatype in the dt column, even though the specific data will depend on what's in that row.

If you want just the date or time, convert it to a string.

like image 199
Barmar Avatar answered Sep 28 '22 04:09

Barmar