Dofactory.com
Dofactory.com
Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

SQL DEFAULT Constraint

A DEFAULT constraint specifies a default column value if no value is specified.

The default value also applies to UPDATEs when no value exists or is specified.

This constraint only applies if no value is specified. Any other value is acceptable.

Example

#

In this table the default for Country is 'UK'.

CREATE TABLE Customer (
  Id INT IDENTITY,
  FirstName NVARCHAR(50) NOT NULL,
  LastName NVARCHAR(50) NOT NULL,
  City NVARCHAR(50),
  Country NVARCHAR(50) DEFAULT 'UK'
)

Add DEFAULT

#

To add a default value to a column in an existing table use ALTER TABLE.

ALTER TABLE Customer
  ADD CONSTRAINT Df_City
  DEFAULT 'New York' FOR City

If no city value is provided, it will be set to 'New York'.


Remove DEFAULT

#

To remove a DEFAULT constraint use ALTER TABLE.

ALTER TABLE Customer
 DROP CONSTRAINT Df_City

This does not remove any columns, only the default value of these columns.
Only the new records will be affected by this change.


You may also like



Last updated on Dec 21, 2023

Earn income with your data and sql skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.