Skip to content
Related Articles

Related Articles

Improve Article

MySQL | DEFAULT() Function

  • Last Updated : 25 Mar, 2019

The DEFAULT() function returns the default value for table column.

DEFAULT value of a column is a value used in the case, there is no value specified by user.

In order, to use this function there should be a DEFAULT value assign to the column. Otherwise, it will generate an error.

Syntax:

DEFAULT ( column_name)

column_name: Name of column whose default value is written.

Example: Consider two relations student and result



Structure of table “student”-

FieldTypeNullDefault
sidint(11)YESNULL
snamevarchar(10)YESNULL
subjectvarchar(10)YESNULL
marksint(11)YES0

Structure of table “result”-

FieldTypeNullDefault
lowest_marksint(11)YESNULL
lohighest_marksint(11)YESNULL
gradevarchar(5)YESFAIL

Data in the tables-

Select * from student;



sidsnamesubjectmarks
1aayushiO.S89
2yogeshD.A.A75
3chesthaT.O.C0
4manasviO.S60
5hardikD.A.A99
6shanuE.S.D35

Select * from result;

lowest_markshighest_marksgrade
85100A
6085B
4060C

Problem Description: We have to find result of all the students-

Query:

Select sid, sname, subject, marks, 
    IF ( grade is NULL, DEFAULT ( grade ), grade )
AS grade  FROM  student LEFT JOIN result 
    ON marks > lowest_marks 
AND marks < = highest_marks;

Output:

sidsnamesubjectmarksgrade
1aayushiO.S89A
2yogeshD.A.A75B
3chesthaT.O.C0FAIL
3chesthaT.O.C0FAIL
4manasviO.S60C
5hardikD.A.A99A
6shanuE.S.D35FAIL

Explanation: Here, default() function is use to return default grade i.e “FAIL”. This default value is used in place where student marks doesn’t match according to joining condition. Those students results is shown as FAIL.

Note: The default function with select statement will return default value for all rows. That means, instead of getting a single default value of the column, we will get list of default values for that column.

For example for above table result, Output of query is-

Select default ( grade) from result;

Output:

default ( grade )
FAIL
FAIL
FAIL

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :