Sunday, January 12, 2025
HomeProgrammingHow to add a Column with a Default Value to an Existing...

How to add a Column with a Default Value to an Existing Table in SQL?

To add a column with a default value to an existing table in SQL, you can use the ALTER TABLE statement with the ADD clause and specify the default value. Here’s the general syntax:

sql Copy code

ALTER TABLE table_name

ADD column_name data_type DEFAULT default_value;

Example

Suppose you have a table named employees, and you want to add a column called status with a default value of ‘active’. Here’s how you can do it:

See also  Android: Where are Downloaded Files Saved? [closed]

sql Copy code

ALTER TABLE employees

ADD status VARCHAR(10) DEFAULT ‘active’;

Points to Note:

Default Value: The value specified in the DEFAULT clause will be used for existing and future rows if no other value is provided.

See also  How to calculate percentage with a SQL statement

Nullable Columns: If you do not add a NOT NULL constraint, the column can still store NULL values if explicitly specified in future inserts.

Updating Existing Rows: In most SQL databases, existing rows will automatically take the default value unless otherwise specified.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x