I have few existing tables in which I have to modify various columns to have a default value.
How can I apply the default value to old records which are NULL
, so that the old records will be consistent with the new ones
ALTER TABLE "mytable" ALTER COLUMN "my_column" SET DEFAULT NOW();
After modifying table 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 a simple to way to have all columns which are currently null and also which have a default value to be set to the default value ?
Default values can be NULL, or they can be a value that matches the data type of the column (number, text, date, for example).
To change a default value, use ALTER col_name SET DEFAULT : ALTER TABLE mytbl ALTER j SET DEFAULT 1000; Default values must be constants. For example, you cannot set the default for a date-valued column to NOW( ) , although that would be very useful.
Deriving from insert into
, I just tried this, and it is as simple as
update mytable
set my_column = default
where my_column is null
See sqlfiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With