I need to manipulate column data in postgres
When I run the query-
SELECT t.date::varchar
FROM generate_series(timestamp '2020-02-27'
, timestamp '2020-03-01'
, interval '1 day') AS t(date);
it returns -
2020-02-27 00:00:00
2020-02-28 00:00:00
2020-02-29 00:00:00
2020-03-01 00:00:00
I want -
20200227
20200228
20200229
20200301
Removed '-' and truncated from end. Can someone guide
CodePudding user response:
- If you don't specifically need some features of a
varchar, by default usetextinstead. - You don't need to cast every time -
generate_series()will do that automatically once it detects your step is aninterval. That's unless you specifically want thegenerate_series(timestamp,timestamp,inteval)variant, notgenerate_series(timestamptz,timestamptz,inteval). - If you cast to be explicit, cast your dates as
date. Regardless of whether you leave it as text literal or make them actual dates, PostgreSQL will have to cast them to match the function definition. - If you're planning to group things by a text-based date or do that to truncate timestamps, consider
date_bin()anddate_trunc()as well as simply holding things as a nativedatetype. It'll take less space, run faster and enable native date-specific functions. - Make sure you're using
to_char()to its full potential - it can save a lot of formatting later.
SELECT to_char(t.date,'YYYYMMDD') as date
FROM generate_series('2020-02-27'
, '2020-03-01'
, interval '1 day') AS t(date);
-- date
------------
-- 20200227
-- 20200228
-- 20200229
-- 20200301
