Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all where date in Last month sql [duplicate]

How can I get last month date like

select * from table where date in ( last month  )

I dont want the last 30 days AND how can I get last month automatically

like image 953
user3190075 Avatar asked Sep 16 '25 23:09

user3190075


2 Answers

Assuming you want all items where the date is within the last month i.e. between today and 30/31 days ago:

Select *
From Table
Where Date Between DATEADD(m, -1, GETDATE()) and GETDATE()
like image 76
Obsidian Phoenix Avatar answered Sep 18 '25 14:09

Obsidian Phoenix


Edit

if you mean last month from today. or previous month from a specific date then you need to do something like this

SELECT DATEPART(MONTH, DATEADD(MONTH, -1, [Date]))

Or to get records from previous month of the year you can do something like this

SELECT * FROM Table
WHERE  MONTH(Date) =  DATEPART(MONTH, DATEADD(MONTH, -1, [Date]))
AND YEAR(Date) =    DATEPART(YEAR, DATEADD(MONTH, -1, [Date]))    --<-- or pass year for which year you are checking 

To make your aquery SARGable (Suggested by t-clausen.dk)

select * from table 
where date >=dateadd(m, datediff(m, 0, current_timestamp)-1, 0) 
and date < dateadd(m, datediff(m, 0, current_timestamp)-1, 0)

Read here more about sargable Queries when working with date/datetime datatypes.

like image 25
M.Ali Avatar answered Sep 18 '25 15:09

M.Ali