Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When to_char's output in postgres is converted to Varchar, why is not comparing correctly with other varchars?

I’m using to_char to get the day from the timestamp in postgres. On converting the result of that timestamp to varchar, because I want to apply some filters of type varchar, it doesn’t give the correct result.

This query –

select * from (SELECT to_char(date (tableA.date), 'Day') AS day from tableA) a ;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

gives weekdays in day column, which are days.

This query –

select * from (SELECT pg_typeof( to_char(date (tableA.date), 'Day')) AS day from tableA) a ;

gives text in day column. because the type of it is "text".

And this final query gives 0 rows, it should give all the matching results.

select * from (SELECT to_char(date (table.date), 'Day')::VARCHAR AS day from table) a where day IN ('Thursday');

Actual Output is 0 rows, Expected Output is 10 rows.

>Solution :

to_char(date, 'Day') returns a padded version of the day name, e.g. 'Thursday ' instead of 'Thursday'.

If you want to remove the padding you can either use the FM modifier: to_char(table.date, 'FMDay') or trim: trim(to_char(date, 'Day'))

In general I would be very cautions about using locale specific comparisons e.g. on my computer this comparison would fail even if the padded spaces are removed, as it won’t return Thursday. It’s better to use numeric values, e.g. extract(isodow from date) = 5

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading