I have a PostgreSQL table with a field named effective_date and data type is integer(epoch date). What I want to do is to select only the entries that have an effective_date of my choice (I only want to query by the month). My query is below and the problem is, it is not returning anything although the table do have many entries that match the selection criteria.
$query = "select *
from ". $this->getTable() ."
where pay_stub_entry_name_id = 43
AND to_char(effective_date, 'Mon') = 'Jul'
AND deleted = 0";
Use
extract(month from the_date)instead ofto_char. See datetime functions in the Pg docs.With
to_charyou’ll suffer from all sorts of issues with case, localisation, and more.Assuming you meant that the data type of
effective_datewastimestampordate, you’d write:If it’s
integerthen – assuming it’s an epoch date – you have to convert it to a timestamp withto_timestamp, then useextracton it. See theepochsection in the documentation linked to above, eg:The immediate cause of your problem was that you were calling
to_char(integer,text)with an integer epoch date. Only thetimestampversions ofto_chardo date formatting;Monisn’t special for the others, so it was simply output as a literal stringMon. Compare:Remember to parameterise your real-world versions of these queries to help avoid SQL injection.