It is possible to collect data of the whole month in postgresql

Asked

Viewed 1,626 times

2

How do I so that from a specific month I can get all data saved in the database: I think you should spend the year / month as parameter for example variable = "2016/10"; remembering that the data type in the database and timestamp

  SELECT * FROM dados WHERE data_registro = variavel

3 answers

3


Option 1: Use of TO_CHAR:

select * from dados where TO_CHAR(data_registro, 'MM/YYYY') = '01/2016'

Option 2: Use with ranges:

select * from dados where data_registro >= '2016-01-01'::DATE 
and data_registro <= '2016-01-31'::DATE

Option 3: Use of overlaps

select * from dados where (data_registro, data_registro) 
OVERLAPS ('2016-01-01'::DATE, '2016-01-31'::DATE);

Option 4: With Extract:

select * from dados 
where 
Extract(month from data_registro) >= Extract(month from '2016-01-01'::DATE)
and Extract(month from data_registro) <= Extract(month from '2016-01-31'::DATE)

Option 5: Use of intervals based on current date:

SELECT *
FROM   dados
WHERE  Extract(month from data_registro) >= Extract(month from Now())
AND    Extract(month from data_registro) <= Extract(month from Now() + Interval '20 day')
  • 1

    I took the test here of the first option and it worked, Perfect!

1

Only continuing the options already mentioned

Option with date_trunc

SELECT * FROM dados WHERE 
   date_trunc('month', data_registro) = date_trunc('month', '2015-03-01');

In this case the parameter can be any valid date in the month, it will truncate both for the same month.

Reference

0

Has to use BETWEEN:

SELECT dados
FROM   tabela
WHERE  tabela.data BETWEEN '2016-01-01' AND '2016-01-31'

If the field in question is of the TIMESTAMP type, depending on your BD, you should remember to do CAST (e.g.: Postgres tabela.data::DATE)

Browser other questions tagged

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