Got it! Since DuckDB doesn't yet support adding a generated column (GENERATED ALWAYS AS) after table creation, and you don't need the new column to automatically update on future inserts, here's the best approach:
Solution: Add a Regular Column & Update It in Bulk
- Add a normal column (not generated).
- Populate it in bulk using an
UPDATE statement with your logic.
- Future inserts will require manually setting the value (or you can use a
DEFAULT if the logic is static).
Step-by-Step Example
1. Original Table (Example)
Assume your table looks like this:
CREATE TABLE my_table (
id INTEGER,
category VARCHAR
);
INSERT INTO my_table (id, category) VALUES
(1, 'error'),
(2, 'warning'),
(3, 'info');
2. Add the New Column
ALTER TABLE my_table ADD COLUMN dependent_value VARCHAR;
3. Update the New Column Based on category
UPDATE my_table
SET dependent_value =
CASE
WHEN category = 'error' THEN 'ERR-' || category
WHEN category = 'warning' THEN 'WARN-' || category
ELSE 'DEFAULT-' || category
END;
4. Verify the Result
SELECT * FROM my_table;
Output:
┌───────┬───────────┬───────────────────┐
│ id │ category │ dependent_value │
├───────┼───────────┼───────────────────┤
│ 1 │ error │ ERR-error │
│ 2 │ warning │ WARN-warning │
│ 3 │ info │ DEFAULT-info │
└───────┴───────────┴───────────────────┘
5. (Optional) Set a Static DEFAULT for Future Inserts
If new rows should have a fixed default (not dynamically computed), you can modify the column:
ALTER TABLE my_table
ALTER COLUMN dependent_value SET DEFAULT 'UNKNOWN';
Now, if you insert without specifying dependent_value:
INSERT INTO my_table (id, category) VALUES (4, 'new');
It will get dependent_value = 'UNKNOWN'.