Wednesday, August 12, 2015

SQL Query by Date and Get 4 Nearest Record

Today here to play around with the SQL script and I try to revise my SQL script.

When come to date calculation, there is a build in function to calculate the date different. The function name is datediff(). How to use this function as it simple and you have to pass 2 value into this function and it will return the difference of day between the 2 value.

Example:
Value A: 2015-08-20; Value B: 2015-08-12 and the different of these2 day are 8

SELECT datediff('2015-08-20 00:00:00','2015-08-12') as 'dayto'

For today date there is a build in function too which is CURDATE()

In SQL if you want to get specific numbers of result return by SQL server you may using LIMITthen follow by the number of record.

Example to return 10 record.
Limit 10

Well the complete SQL script to get the top 4 nearest evetStartDate date from today as follow.

SELECT datediff(`evetStartDate`,CURDATE()) as 'dayto', `eventguid`,`eventName`,`evetStartDate`
FROM event
WHERE `evetStartDate` > NOW()
ORDER BY `evetStartDate` ASC
LIMIT 4"



No comments:

Post a Comment