I'm trying to add a column to a firebird table. The column should have a default value 1 but initially for already existing rows the value should be set to 0. And that should happen in one transaction.
I tried
ALTER TABLE MYTABLE ADD MYCOLUMN SMALLINT DEFAULT 1 NOT NULL;
UPDATE MYTABLE SET MYCOLUMN = 0;
but that's not allowed in one transaction, because the update won't see the new column. I also tried:
ALTER TABLE MYTABLE ADD MYCOLUMN SMALLINT DEFAULT 0 NOT NULL;
ALTER TABLE MYTABLE ALTER COLUMN MYCOLUMN SET DEFAULT 1 NOT NULL;
Hoping that the column will be 0 afterwards but it will be 1.
More options to get what I want in one transaction?
Unfortunately you can't do this in a single transaction. Firebird doesn't allow updates/inserts to use objects created in the same transaction (in this case the column) because DDL is actually only really executed/completed at transaction commit, and for the same reason executing the two alter table
statements for the same column will behave as if only a single alter table
statement was issued (so the last default will be applied).
You have two options:
There are actually some more options, but that would only complicate matters (especially before Firebird 3), and require even more transactions.
As an aside: ALTER TABLE MYTABLE ALTER COLUMN MYCOLUMN SET DEFAULT 1 NOT NULL
should have given you a syntax error because in Firebird 2.5 changing NOT NULL
is not supported, and in Firebird 3 it requires a separate alter table mytable alter column set not null
.
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