1

I want to create a NOT NULL column in my table with values from an other column as default values. How I can do that?

ALTER TABLE mytable
    ADD COLUMN not_null_column TIME WITHOUT TIME ZONE NOT NULL DEFAULT old_column

but that not works because old_column is not constant

Any idea?

5
  • 2
    What DBMS are you using? Commented Mar 31, 2021 at 13:40
  • 1
    "that not works because old_column is not constant" Define "not works". What should happen? What happens instead? What does it mean for a column not to be constant, and how does that related to a default value on another column? Commented Mar 31, 2021 at 13:44
  • I need to do a migration with flyway, but I can manage my db with Intellij's tool Commented Mar 31, 2021 at 13:44
  • @underscore_d constant is something like '2021-01-45' written in raw. It's not working means my migration can't be applied, an error pops Commented Mar 31, 2021 at 13:46
  • You could add the column them update it: ALTER TABLE mytable ADD COLUMN not_null_column TIME WITHOUT TIME ZONE NOT NULL DEFAULT NOW(); UPDATE mytable SET not_null_column=old_column; Commented Mar 31, 2021 at 14:39

2 Answers 2

4

This is not possible.

The reason is explained in the manual where the DEFAULT clause in a CREATE TABLE is documented:

The DEFAULT clause assigns a default data value for the column whose column definition it appears within. The value is any variable-free expression (in particular, cross-references to other columns in the current table are not allowed).

(emphasis mine)

If you really need something like that, you will have to create a (before insert) trigger that populates not_null_column with the value of the other column.

Sign up to request clarification or add additional context in comments.

Comments

2

I did something like that :

ALTER TABLE mytable
    ADD COLUMN not_null_column TIME WITHOUT TIME ZONE;

UPDATE mytable
SET not_null_column = old_column;


ALTER TABLE mytable
    ALTER COLUMN not_null_column SET NOT NULL;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.