×
>
<

Aptitude

Default Constraints

Default

Suppose in real time you are having a column in a table where the majority of the data values that column is frequently repeated and in that case why should you enter the same value, again and again, each time while entering a row

For example, if Hyderabad is the city for all employees in the company then a city column with Hyderabad value is the default column in the table that is you need not enter this value you whenever you insert a new row.

CREATE
DEFAULT clause

  • Default clause in SQL is used to add default data to the columns
  • When a column is specified as default with some value then all the rows will use the same value i.e each and every time while entering the data we need not enter that value 
  • But default column value can be customized i.e it can be overridden  when inserting a data for that row based on the requirement.

Example for DEFAULT clause

The following SQL sets a DEFAULT value for the “city� column when the “emp� table is created:

My SQL / SQL Server / Oracle / MS Access:

  
CREATE TABLE emp (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    City varchar(255) DEFAULT 'hyderabad'
);
  

Upon using a select query on the emp table following data is displayed

IDLastNameFirstNameAgeCity
66DunphyAlex21hyderabad
67TuckerLily22hyderabad
68DunphyLuke22hyderabad
69PritchettAlex23hyderabad

  • You can see that all the values of the city column are  same i.e Hyderabad this is because we have set city column as default column with a default value of Hyderabad 
  • As a result, whenever you insert a new row each time you need not enter a value for this default column  that is entering a column value for a default column is optional and if you don’t enter the same value is considered that is used in the default clause