Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a part of a timestamp field in postgres?

Example: My timestamp: 2018-01-01 00:00:00.000 in table temp and field temp_date. I want to update 2018 to 2016 by SQL. How can I ?

like image 938
Nguyễn Thắng Avatar asked Jun 17 '16 03:06

Nguyễn Thắng


2 Answers

UPDATE temp
SET temp_date = temp_date - interval '2 years'
WHERE EXTRACT (YEAR FROM temp_date) = 2018;

If you want to set it to an exact year, e.g. if your WHERE clause uses something other than the year, or if you're not using a WHERE clause at all:

UPDATE temp
SET temp_date = temp_date +
    (2016 - EXTRACT(YEAR FROM temp_date) || ' years')::interval
WHERE foo = 'bar';

For more details, refer to the mailing list.

like image 147
Patrick Avatar answered Nov 19 '22 15:11

Patrick


Try:

UPDATE temp
   SET temp_date = temp_date - (date_trunc('year', temp_date ) - date '2016-1-1')

The above update assigns '2016' to all dates in the table,
leaving remaining date parts (month-day-hour etc.) unchanged

like image 2
krokodilko Avatar answered Nov 19 '22 16:11

krokodilko