Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare month and year in postgres

Tags:

sql

postgresql

I'm trying this:

select * from venda where to_char(data_venda, 'MM-YYYY') = '07/2017'

Nothing returns.

The database does have two records with this date:

'21/07/2017'.

like image 429
HawkB Avatar asked Jul 21 '17 19:07

HawkB


1 Answers

Use the same separator:

select v.*
from venda v
where to_char(v.data_venda, 'MM-YYYY') = '07-2017';

There are other ways to write this that don't involve changing data types:

where date_trunc('month', v.data_venda) = '2017-07-01'
where v.data_venda >= '2017-07-01' and v_data_venda < '2017-08-01'

The latter is nice, because it can readily use an index.

like image 71
Gordon Linoff Avatar answered Oct 22 '22 23:10

Gordon Linoff