Skip to content
Advertisement

How to add a column in MSSQL with default value?

In MSSQL 2014 I would like to use an update syntax which is adding a new column with a default value. Is this possible somehow?

Advertisement

Answer

Here is a complete reproducible example.

Create table

CREATE TABLE employees
( employee_id INT NOT NULL,
  last_name VARCHAR(50) NOT NULL,
  first_name VARCHAR(50) NOT NULL,
  salary MONEY
);

INSERT INTO employees
VALUES (1, 'Miller', 'Peter', 80000);

INSERT INTO employees
VALUES (2, 'Myer', 'Joana', 90000);

Check contents

SELECT * FROM employees;

employee_id last_name   first_name  salary  
1           Miller      Peter       80000   
2           Myer        Joana       90000   

Add new column with default value

ALTER TABLE employees
ADD email VARCHAR(50) DEFAULT 'info@company.com' NOT NULL;

Check the result

SELECT * FROM employees;

employee_id last_name   first_name  salary  email
1           Miller      Peter       80000   info@company.com
2           Myer        Joana       90000   info@company.com

Here is a SQL fiddle with this example.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement