You're encountering another DuckDB limitation! DuckDB doesn't currently support adding generated columns to existing tables with ALTER TABLE.
Here are your options to work around this:
Option 1: Recreate the Table (Most Common Solution)
If you have an existing table and want to add a generated column, you'll need to recreate it:
sql
-- Step 1: Create the new table structure with the generated column
CREATE TABLE mytable_new (
category VARCHAR,
-- your existing columns here...
dependent_value VARCHAR GENERATED ALWAYS AS (
CASE
WHEN category = 'error' THEN 'ERR-' || category
WHEN category = 'warning' THEN 'WARN-' || category
ELSE 'DEFAULT-' || category
END
) STORED
);
-- Step 2: Copy data from old table to new table
INSERT INTO mytable_new (category) -- list all non-generated columns
SELECT category FROM mytable; -- corresponding columns from old table
-- Step 3: Drop old table and rename new one
DROP TABLE mytable;
ALTER TABLE mytable_new RENAME TO mytable;
Option 2: Use a View Instead
If you don't need the computed values to be physically stored, create a view:
sql
CREATE VIEW mytable_with_dependent AS
SELECT
category,
CASE
WHEN category = 'error' THEN 'ERR-' || category
WHEN category = 'warning' THEN 'WARN-' || category
ELSE 'DEFAULT-' || category
END AS dependent_value
FROM mytable;
Then query the view instead of the base table:
sql
SELECT * FROM mytable_with_dependent;
Option 3: Compute at Query Time
Simply include the logic in your SELECT statements when needed:
sql
SELECT
category,
CASE
WHEN category = 'error' THEN 'ERR-' || category
WHEN category = 'warning' THEN 'WARN-' || category
ELSE 'DEFAULT-' || category
END AS dependent_value
FROM mytable;
Recommendation
Option 1 (recreate table) if you need the computed values stored physically and want the cleanest table structure
Option 2 (view) if you want a permanent abstraction but don't mind the computation happening at query time
Option 3 (query-time computation) for ad-hoc queries or if this is only needed occasionally
The table recreation approach is most common when you need to modify the schema significantly in DuckDB.
User
I want to add a column to my table with its values based on another VARCHAR column. I don't want to manually enter the values for the new column. The new column does not have to update its values automatically if I INSERT.
Assistant
Perfect! Since you don't need automatic updates for future INSERTs, you can simply add a regular column and populate it based on your existing VARCHAR column.
Here's how to do it:
Step 1: Add the new column
sql
ALTER TABLE mytable ADD COLUMN dependent_value VARCHAR;
Step 2: Populate the new column based on your existing VARCHAR column
sql
UPDATE mytable
SET dependent_value = CASE
WHEN category = 'error' THEN 'ERR-' || category
WHEN category = 'warning' THEN 'WARN-' || category
ELSE 'DEFAULT-' || category
END;
That's it! Now your table has the new column with values computed from your existing category column.