Skip to content
Advertisement

How can I get the months between two dates in Oracle SQL

I need to get the numbers of the months between two dates. For example, between those dates: “03/03/2020 – 06/06/2020” I need something like “(03,04,05,06)”.

Advertisement

Answer

For Oracle:

SQL> column months format a24
SQL> select banner from v$version where rownum=1;

BANNER
--------------------------------------------------------------------------------
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production

SQL> select '(' || listagg(m, ',') || ')' as months
  2  from (
  3   select
  4   extract(month from to_date('03/03/2020')) m1,
  5   extract(month from to_date('06/06/2020')) m2
  6   from dual) mm
  7  inner join (
  8   select level as m
  9   from dual
 10   connect by level <= 12) l
 11  on m >= m1 and m <=m2
 12  ;

MONTHS
------------------------
(3,4,5,6)

SQL> 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement