Skip to main content

Add a default value for new columns

When you add a new column to a table, ClickHouse will add it with the default value:

CREATE TABLE local
ENGINE = MergeTree
ORDER BY number AS
SELECT *
FROM numbers(1000000);

ALTER TABLE local
ADD COLUMN IF NOT EXISTS `date` DateTime;

OPTIMIZE TABLE local FINAL; -- To speed up the mutation / lazy way to know it has finished

SELECT *
FROM local
LIMIT 10

Query id: b5fedb97-a1c8-475f-a674-0b1658c8e889

┌─number─┬────────────────date─┐
01970-01-01 01:00:00
11970-01-01 01:00:00
21970-01-01 01:00:00
31970-01-01 01:00:00
41970-01-01 01:00:00
51970-01-01 01:00:00
61970-01-01 01:00:00
71970-01-01 01:00:00
81970-01-01 01:00:00
91970-01-01 01:00:00
└────────┴─────────────────────┘

To change the default value for old rows you need to declare the default in the column definition:

ALTER TABLE local
ADD COLUMN IF NOT EXISTS `new_date` DateTime DEFAULT now();

OPTIMIZE TABLE local FINAL;

SELECT *
FROM local
LIMIT 10

Query id: b5ff3afd-78f7-4ea3-8d43-adc7fe14f0a0

┌─number─┬────────────────date─┬────────────new_date─┐
01970-01-01 01:00:002022-09-23 13:53:38
11970-01-01 01:00:002022-09-23 13:53:38
21970-01-01 01:00:002022-09-23 13:53:38
31970-01-01 01:00:002022-09-23 13:53:38
41970-01-01 01:00:002022-09-23 13:53:38
51970-01-01 01:00:002022-09-23 13:53:38
61970-01-01 01:00:002022-09-23 13:53:38
71970-01-01 01:00:002022-09-23 13:53:38
81970-01-01 01:00:002022-09-23 13:53:38
91970-01-01 01:00:002022-09-23 13:53:38
└────────┴─────────────────────┴─────────────────────┘

10 rows in set. Elapsed: 0.002 sec.

Note that this means that new rows will also get the default value if it's not declared on insertion.

ALTER TABLE local
MODIFY COLUMN `new_date` DateTime DEFAULT yesterday();

INSERT INTO local(number) VALUES (999999999);

SELECT *
FROM local
WHERE number = 999999999

Query id: 02527ad6-4644-42ff-8755-8869a9df30fa

┌────number─┬────────────────date─┬────────────new_date─┐
9999999991970-01-01 01:00:002022-09-22 00:00:00
└───────────┴─────────────────────┴─────────────────────┘