Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Find date closest to current date

Tags:

sql

mysql

I'm having some trouble with my SQL query. I got this table:

insert into Table1 (date, personssn)
insert ('2012-01-21 12:01:33', '123456789');
insert into Table1 (date, personssn)
insert ('2012-02-22 12:01:33', '123456789');

The problem is that I want to select the personssn who have a date CLOSEST to the current date. I've been working with "CURDATE()" but can't seem to get it to work. Anyone that can help me in the right direction?

Thanks.

like image 332
Erik Åstrand Avatar asked May 06 '13 12:05

Erik Åstrand


People also ask

How can I compare two dates in SQL?

Here we will see, SQL Query to compare two dates. This can be easily done using equals to(=), less than(<), and greater than(>) operators. In SQL, the date value has DATE datatype which accepts date in 'yyyy-mm-dd' format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement.

Can I use datediff in SQL?

Two Ways to Use DATEDIFF() Function in SQL: It may return the result into the table of data. Use of DATEDIFF() to find the differences between two date values. In this type, the DATEDIFF() function is used to find the number of days or years or any other count between the two DATE values.

How do you use absolute in SQL?

ABS() function : This function in SQL Server is used to return the absolute value of a specified number. Absolute value is used for depicting the distance of a number on the number line from 0. The direction of the number from zero is not considered since the absolute value of a number is never negative.

How do I get today's date in SQL?

To get the current date and time in SQL Server, use the GETDATE() function. This function returns a datetime data type; in other words, it contains both the date and the time, e.g. 2019-08-20 10:22:34 . (Note: This function doesn't take any arguments, so you don't have to put anything in the brackets.)


3 Answers

select  *
from    Table1
order by
        abs(now() - date) desc
limit   1
like image 151
Andomar Avatar answered Oct 11 '22 14:10

Andomar


Use datediff. It returns the Difference between two dates. However, you can have dates before and after today in your database. That's why you need ABS() without it the smallest value would be selected first, but we want the value closest to 0. IE a Date-Difference of 3 is “bigger” than -250, but 3 days off is closer. That is why you use the absolute value.

SELECT t1.date, t1.personssn 
  FROM Table1 AS t1
 ORDER BY ABS(DATEDIFF(t1.date, NOW())) ASC
 LIMIT 5
like image 20
Deniyal Tandel Avatar answered Oct 11 '22 14:10

Deniyal Tandel


Try this with simple order by :

SELECT date,personssn FROM Table1 ORDER BY date desc
like image 31
Anvesh Avatar answered Oct 11 '22 14:10

Anvesh