Search code examples
phpmysqldatabase

How to output the next date in SQL?


I have a table where one column contains a date. How can I output the record with the next date in the future?

My table:

news_titel news_date news_time news_location news_notes
event 1 2020-12-15 10-00 there -
event 2 2020-12-20 10-00 there -
event 3 2020-12-25 10-00 there -

Let's say today is 2020-12-18, then I want the record with the date 2020-12-20 to be displayed.

My previous code:

$sql = "SELECT news_titel, news_date, news_time, news_location, news_notes FROM 
$table WHERE news_date >= NOW() ORDER BY news_date LIMIT 1";

(Note that I didn't make the date handling really nice back then. It would be better if the time and date were combined.)


Solution

  • This would be a good SQL query to accomplish my goal. First you select the columns you want to output from which table, then you check if the date is in the future. Next, sort the records in ascending order and limit the record to be output to one. This will output the next record.

    SELECT name, Date FROM Datesort WHERE Date >= NOW() ORDER BY Date LIMIT 1;