Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return null for date_format when input is null in mysql

I'm doing something like this:

SELECT date_format(mydate, '%d/%m/%Y') FROM xyz;

When mydate is NULL, date_format returns 00/00/0000. This is correct, but how can I make it so that it returns NULL when the input is NULL?

like image 546
John Hunt Avatar asked Apr 07 '11 05:04

John Hunt


People also ask

Can MySQL function return NULL?

We can return 0 for NULL in MySQL with the help of IFNULL() method. The syntax of IFNULL() is as follows. IFNULL(YOUREXPRESSION,0);

How do I query NULL in MySQL?

To look for NULL values, you must use the IS NULL test. The following statements show how to find the NULL phone number and the empty phone number: mysql> SELECT * FROM my_table WHERE phone IS NULL; mysql> SELECT * FROM my_table WHERE phone = ''; See Section 3.3.

IS NULL NULL in MySQL?

In MySQL, NULL is considered as a 'missing, unknown value', as opposed to no value. Take a look at this MySQL Reference on NULL. Any arithmetic comparison with NULL does not return true or false, but returns NULL instead., So, NULL != 'C' returns NULL , as opposed to returning true.

Is NULL in case statement MySQL?

The CASE statement cannot have an ELSE NULL clause, and it is terminated with END CASE instead of END . For the first syntax, case_value is an expression. This value is compared to the when_value expression in each WHEN clause until one of them is equal.


2 Answers

SELECT IF(mydate,date_format(mydate, '%d/%m/%Y'),NULL) FROM xyz;

Source: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html

like image 78
amosrivera Avatar answered Sep 18 '22 23:09

amosrivera


You can wrap this into a IF-Clause, like this:

SELECT IF(mydate,DATE_FORMAT(mydate, '%d/%m/%Y'),NULL) FROM xyz;

That said, if your variable mydate is not a date value, the query in your post should return (NULL) anyway.

like image 21
Bjoern Avatar answered Sep 18 '22 23:09

Bjoern