SQL Default

HTML
CSS
C#
SQL

SQL Default

Whenever a default constraint is applied to the table’s column, and the user has not specified the value to be inserted in it, then the default value which was specified while applying the default constraint will be inserted into that particular column.

The DEFAULT constraint is used to set a default value for a column. The default value will be added to all new records if no other value is specified.

Example:

CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value, ColumnName2 datatype,…., ColumnNameN datatype);

The following SQL sets a DEFAULT value for the “City” column when the “Persons” table is created:

CREATE TABLE Persons (

    ID int,

    LastName varchar(255) ,

    FirstName varchar(255),

    Age int,

    City varchar(255) DEFAULT ‘Sandnes’

);

To create a DEFAULT constraint on the “City” column when the table is already created, use the following SQL:

ALTER TABLE Persons ADD CONSTRAINT df_City DEFAULT ‘Sandnes’ FOR City;

To drop a DEFAULT constraint, use the following SQL:

ALTER TABLE Persons ALTER COLUMN City DROP DEFAULT;

ALTER TABLE Persons DROP CONSTRAINT df_City;

Course Video

NOTE: Practice below practice questions on MSSQL SERVER, it will not execute on site editor.

1. create table tourist and add 5 columns in it also add language column and set default value English in the column.

2. Create table with 5 column and add default constraint to two columns.

Hint: Default constraint is added on EducationLevel  and Position column

3.create a table and add 2 default constraint using alter table.

Hint: Default constraint is added on Department and Position column using alter table

4. create table and add default constraint of user define name

5. Write a sql query to drop above default constrain