clintgh
clintgh

Reputation: 2077

Set default value of a column to another column's value in CREATE statement?

In creating a new table, how do I set the default value of a column to another column's value from the same table?

so for example:

CREATE TABLE app_version
(
  id serial NOT NULL,
  version_name character varying(50),
  version_number numeric
)

I want version_name to be version_number if no name was provided.

Can I do version_name character varying(50) default version_number?

Is this possible? If so, how? Thanks

I can't seem to find anything about this on the forums, it's always on INSERT or UPDATE.

Upvotes: 4

Views: 8403

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270873

The documentation is quite clear that the default value cannot refer to other columns:

DEFAULT default_expr

The DEFAULT clause assigns a default data value for the column whose column definition it appears within. The value is any variable-free expression (subqueries and cross-references to other columns in the current table are not allowed). The data type of the default expression must match the data type of the column.

The default expression will be used in any insert operation that does not specify a value for the column. If there is no default for a column, then the default is null.

Hence, you cannot do what you want with a DEFAULT clause.

Upvotes: 4

Related Questions