Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the value of a column to its default value

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 ?

like image 598
Manquer Avatar asked Oct 15 '16 07:10

Manquer


People also ask

What is the default value of column?

Default values can be NULL, or they can be a value that matches the data type of the column (number, text, date, for example).

How do I change the default value in SQL?

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.


1 Answers

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

like image 103
Olaf Dietsche Avatar answered Sep 20 '22 17:09

Olaf Dietsche