Set the column value to the default value

I have several existing tables in which I need to modify various columns to have a default value.

How can I use the default value to the old records that are NULLso old records will comply with the new

ALTER TABLE "mytable" ALTER COLUMN "my_column" SET DEFAULT NOW();

After changing the table, it looks something like this:

    Table "public.mytable"
 Column      |            Type             |                        Modifiers
-------------+-----------------------------+-----------------------------------------------
 id          | integer                     | not null default nextval('mytable_id_seq'::regclass)
 ....

 my_column   | timestamp(0) with time zone | default now()

Indexes:
  "mytable_pkey" PRIMARY KEY, btree (id)

Is there an easy way to have all columns that are currently null and also that have a default value for the default value?

+4
source share
2 answers

I just tried it and it is as simple as

update mytable
set my_column = default
where my_column is null

See sqlfiddle

+2
source

: olaf answer - , .

information_schema , UPDATE

UPDATE mytable set my_column = (
  SELECT column_default
  FROM information_schema.columns
  WHERE (table_schema, table_name, column_name) = ('public', 'mytable','my_column')
)::timestamp
WHERE my_column IS NULL;

, typecast .

, column_default , , NOW(), say (NOW()+ interval ' 7 days')

,

0

Source: https://habr.com/ru/post/1657840/


All Articles