Select the first and last day of the previous month

Asked

Viewed 2,740 times

2

I have the following query:

select  
ADDDATE(LAST_DAY(SUBDATE(CURDATE(), INTERVAL 1 MONTH)), 1) primeiro_dia, 
last_day(sysdate()) ultimo_dia

That returns me the first and last day of the current month according to the date of the system. How could return the first and last day of the previous month according to the date of the system also?

2 answers

3


Considering the query you already have, just search the same data subtracting from the date a month:

select
   ADDDATE(LAST_DAY(SUBDATE(CURDATE(), INTERVAL 1 MONTH)), 1) primeiro_dia, 
   last_day(sysdate()) ultimo_dia,
   ADDDATE(LAST_DAY(SUBDATE(DATE_SUB(curdate(), INTERVAL 1 MONTH), INTERVAL 1 MONTH)), 1) primeiro_dia_mes_passado, 
   last_day(DATE_SUB(curdate(), INTERVAL 1 MONTH)) ultimo_dia_mes_passado
  • Ta giving error when running your SQL @rLinhares

  • @R.Santos what the mistake?

  • Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')), 1) primeiro_dia_mes_passado, last_day(DATE_SUB(curdate(), INTERVAL 1 MONTH)' at line 4

  • had an extra parenthesis, now it’s okay.

  • 1

    Ah closed all, already mark as correct :)

0

SELECT 
   DATE_ADD(LAST_DAY(NOW() - INTERVAL 2 MONTH), INTERVAL 1 DAY) primeiro_dia_mes_anterior,
   (LAST_DAY(NOW() - INTERVAL 1 MONTH)) ultimo_dia_mes_anterior

Browser other questions tagged

You are not signed in. Login or sign up in order to post.