I have a column with the type date and I want to update only the year in the dates while leaving the day and month as they are. I want to set the year to a specific value regardless of what the current value is. The answers currently on stack overflow involve adding or subtracting years from the date which doesn't seem to be what I need.
-
1you can use your accepted answer, but it may be error one day. because if your current date is 29 february 2024, plus 1 year will become 29 february 2025, which is invalid date. @helwil's answer is safer.Jacky Supit– Jacky Supit2024-09-23 10:26:46 +00:00Commented Sep 23, 2024 at 10:26
Add a comment
|
2 Answers
You can set a specific year like this:
UPDATE my_table SET date_column = date_column +
MAKE_INTERVAL(YEARS := ***year*** - EXTRACT(YEAR FROM date_column)::INTEGER)
where ***year***is the specific year as integer. For instance
UPDATE my_table SET date_column = date_column +
MAKE_INTERVAL(YEARS := 2001 - EXTRACT(YEAR FROM date_column)::INTEGER)
will set the year of all dates to 2001.
Comments
You can do it like this:
UPDATE yourTable SET date_field = date_field + interval '1 year';
Edit:
But that's what you find also here on stackoverflow. What exactly is not working for you? This statement takes the date, adds one year on it and saves it back to database.
2 Comments
Qwertie
This doesn't work for me because it requires that I know the amount of time I want to add/subtract while writing the sql when I actually want to set every date to a specific year.
gdibble
This was perfect for me because I wanted to increment by a set number. Thanks for posting this tip. 🙌