Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL retrieve all records in current month/year

I have a datetime field called DateFinished. I need to be able to retrieve all records in which DateFinished is within the current month/year.

like image 789
korrowan Avatar asked Dec 05 '12 16:12

korrowan


People also ask

How do I get current month data in SQL query?

We can retrieve the current month value in SQL using the MONTH() and DATEPART() functions along with the GETDATE() function. To retrieve the name of the month functions in SQL such as DATENAME() and FORMAT() are used.

How do I get the current year in SQL query?

Just run these SQL queries one by one to get the specific element of your current date/time: Current year: SELECT date_part('year', (SELECT current_timestamp)); Current month: SELECT date_part('month', (SELECT current_timestamp)); Current day: SELECT date_part('day', (SELECT current_timestamp));

How do I get previous month data from current month in SQL?

select * from orders where order_date>now() - interval 1 month; In the above query, we select rows after past 1 month interval. We use INTERVAL clause and NOW() function to obtain the date 1 month in the past, from present date.


2 Answers

Just as an alternative - this should use an index on DateFinished.

SELECT * 
FROM MyTable
WHERE DateFinished BETWEEN 
     DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
     AND 
     DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0)
like image 108
Moose Avatar answered Oct 23 '22 05:10

Moose


If you've only got a small number of rows, this will do to get all rows where DateFinished is in this month of this year.

SELECT * 
FROM MyTable
WHERE Year(DateFinished) = Year(CURRENT_TIMESTAMP) 
                 AND Month(DateFinished) = Month(CURRENT_TIMESTAMP)

This could get quite slow over a large number of rows though - in which case using DateAdd, DatePart and BETWEEN is probably more appropriate, and can take advantage of indexes (I don't have time to write an answer involving those right now!)

like image 20
Bridge Avatar answered Oct 23 '22 06:10

Bridge