Table of Contents
ToggleThe SQL DEFAULT Constraint is used to specify the default value for a column of a table. We usually set default value while creating the table.
The default values are treated as the column values if no values are provided while inserting the data, ensuring that the column will always have a value. We can specify default values for multiple columns in an SQL table.
Following is the syntax of the SQL DEFAULT Constraint −
In the following query we are creating the CUSTOMERS table using the CREATE TABLE statement. Here, we are adding a default constraint to the columns NAME, AGE, ADDRESS, and SALARY −
Following query inserts values into this table using the INSERT statement −
The table is created with default values in the NAME, AGE, ADDRESS, and SALARY columns for the first row as shown below −
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
While inserting data into a table, if the column names are not included in the INSERT query, to insert the default value into the record we need to pass “DEFAULT” as a value, as shown below −
The table obtained is as shown below −
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | Kaushik | 32 | Ahmedabad | 2000.00 |
| 4 | Chaitali | 32 | Ahmedabad | 2000.00 |
We can also add default constraints to an existing column of a table using the ALTER TABLE statement. This allows us to modify the structure of existing table by specifying default values, ensuring data consistency in the database.
Following is the syntax for adding a default constraint to a column in an existing table −
Assume we have created another table named BUYERS using the CREATE TABLE statement as shown below −
Following query, we adds a default constraint to the ADDRESS column of the BUYERS table.
Following INSERT statement inserts a record into the BUYERS table by providing values to all the columns except ADDRESS −
After inserting the record if you retrieve it back, you can observe the default value (“Delhi”) in the address column −
| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 01 | Rahul | 27 | Delhi | 50000.00 |
We can delete the default constraint from a table using the ALTER TABLE… DROP statement.
Following is the syntax to delete the default constraint from a table −
In here, we are removing the default constraint from the ADDRESS column of the CUSTOMERS table −
We can verify the table details (structure) and check whether there is a default constraint or not using the following query −
| Field | Type | Null | Key | Default | Extra |
|---|---|---|---|---|---|
| ID | int | NO | PRI | NULL | |
| NAME | varchar(20) | NO | Ramesh | ||
| AGE | int | NO | 32 | ||
| ADDRESS | char(25) | YES | NULL | ||
| SALARY | decimal(18,2) | YES | 2000.00 |
