Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL: comparing a NULL date to CURRENT_DATE

Tags:

date

mysql

I have a MYSQL table with news articles with the fields "date_start" and "date_end" to indicate which news to show on a web site. Articles are public if date_start is before today and the date_end hasn't already gone by (after today).

The problem: I'd like to let the admin leave date_end NULL if the article is of permanent nature and doesn't expire. This of course doesn't work with my select:

 SELECT * FROM pf_news WHERE date_start <= CURRENT_DATE() AND date_end >= CURRENT_DATE()

It leaves out articles with a NULL date_end. I tried playing a bit with IF statements but it got confusing for me. Is there a simple way of doing this, or should I just set date_end to 3000-01-01 if it's left empty? :)

like image 759
Ville Avatar asked Jun 30 '10 13:06

Ville


People also ask

How do you compare dates in MySQL?

The DATE() function can be used for the comparison of the date of a number of purposes, some of them are: To extract the specific data on the basis of the date by using the inequality or equality signs. To extract the specific data on the basis of the date between different columns.

How can I compare two date fields in MySQL?

To count the difference between dates in MySQL, use the DATEDIFF(enddate, startdate) function. The difference between startdate and enddate is expressed in days.

Can date be NULL in MySQL?

The . NET DateTime data type cannot handle NULL values. As such, when assigning values from a query to a DateTime variable, you must first check whether the value is in fact NULL .

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.


1 Answers

Your last proposal sounds correct. You can use the IFNULL function. It has two arguments. If the first argument is non-null, it returns the first argument. The second argument is what to return if the first argument is null. So in your statement, you can say this:

SELECT * FROM pf_news WHERE date_start <= CURRENT_DATE() AND IFNULL(date_end, '3000-01-01') >= CURRENT_DATE()

This can also be used in SQL Server, but they call it the "ISNULL" function.

Just set a calendar reminder for yourself on 12/31/2999 to change your code! :)

like image 177
brentlightsey Avatar answered Sep 27 '22 19:09

brentlightsey