In DuckDB, you can achieve this using a generated column or a default expression that references another column. I'll show you both approaches.
Approach 1: Generated Column (Recommended)
You can create a generated column, which is a column that is computed on the fly based on an expression. In this case, we'll use a GENERATED ALWAYS column with a CASE expression that references the other VARCHAR column.
Here's an example:
sql
CREATE TABLE mytable (
category VARCHAR,
label VARCHAR GENERATED ALWAYS AS (
CASE
WHEN category = 'error' THEN 'ERR-' || category
ELSE category
END
) STORED
);
In this example:
category is the VARCHAR column you want to depend on.
label is the generated column with a default value based on category.
The CASE expression checks the value of category. If it's 'error', it prefixes the value with 'ERR-'. Otherwise, it just uses the category value as is.
The STORED keyword means the generated value will be physically stored in the table (not just computed at query time).
Now, when you insert data:
sql
INSERT INTO mytable (category) VALUES ('error'), ('warning'), ('info');
The label column will automatically get the computed values: