SQL

How To Add Column With Default Value In SQL

In this article, we will learn how to add a column with default value using the DEFAULT constraint in SQL.

To provide a default value for a column, the DEFAULT constraint is used.

If no value is specified, the default value will be added to all these records.

 

DEFAULT – CREATE TABLE:

Please check How To Create Table Using Query In SQL, to get a brief description of the CREATE TABLE statement.

Example

The subsequent statement would set a DEFAULT value for the “Author”, “Views”, and “CDate” columns when the “Article” table is created:

CREATE TABLE Article (
    ID int,
    Title varchar(100),
    Author varchar(100) DEFAULT 'Yasin',
    Views int DEFAULT 0,
    CDate date DEFAULT GETDATE()
);

 

DEFAULT – ALTER TABLE:

Please check How To Alter Table Using Query In SQL, to get a brief description of the ALTER TABLE statement.

  • To ADD a DEFAULT Constraint

Syntax

ALTER TABLE TABLE_NAME 
ADD CONSTRAINT CONSTRAINT_NAME DEFAULT Value FOR columnName;

Example

The subsequent statement would add a DEFAULT constraint on the “Views” column using ALTER TABLE statement:

ALTER TABLE Article 
ADD CONSTRAINT DFArticle DEFAULT 0 FOR Views;
  • To DROP a DEFAULT Constraint

Syntax

ALTER TABLE TABLE_NAME 
ALTER COLUMN columnName DROP DEFAULT;

Example

The subsequent statement would delete a DEFAULT constraint using ALTER TABLE statement:

ALTER TABLE Article 
ALTER COLUMN Views DROP DEFAULT;

 

Also, check How To Use CHECK Constraint In SQL

Yasin Panwala

Yasin Panwala is a Web Developer and Author at TheCodeHubs. He has experience in Web Developing and Designing and also in Writing. He has got his skills in working on technologies like .NET Core, ADO.NET, AJAX, Angular, AngularJS, ASP.NET, ASP.NET MVC, Bootstrap, C#, CSS, Entity Framework, Express.js, GraphQL, HTML, JavaScript, JQuery, JSON, LINQ, Microsoft Office, MongoDB, MySQL, Node.js, PostgreSQL, SQL, SQL Server, TypeORM, TypeScript, Visual Basic .NET, Web API. He also got his skills in working with different integration and some known versioning tools. He is always ready to learn new things and he always tries his best on tasks that are assigned to him and gives the best possible outputs.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago