DEFAULT
DEFAULT is a constraint in SQL that sets a default value for a column in a database table. If no value is specified for that column when a new record is inserted, the DEFAULT value will be used. However, if a value is specified, it overrules the DEFAULT constraint. It helps in maintaining data consistency if a column entry is omitted during data insertion.
Example
Output
Explanation
In this example, a new table named ‘Employees’ is created with three columns ‘ID’, ‘Name’, and ‘HasInsurance’. The ‘HasInsurance’ column has a default value of 1. Then, a new record is added where only the ‘ID’ and ‘Name’ values are specified. However, when all records are selected from the table, we see that the ‘HasInsurance’ field for John contains the default value of 1, since no particular value was specified during the row ‘John’ insertion.
Example
Output
ID | Name | SignDate |
---|---|---|
1 | John Doe | 2022-01-12 |
Output
ID | LastName | FirstName | Age |
---|---|---|---|
1 | Doe | John | 30 |
Explanation
In the provided SQL code, a table named ‘Persons’ is created with columns ID, LastName, FirstName, and Age. The Age column is assigned a DEFAULT value of 30. So, when a new record is inserted into the ‘Persons’ table without providing a value for Age, SQL Server will automatically insert the DEFAULT value, which is 30 in this case. The output table shows the record of person named John Doe with an Age value of 30, despite no explicit Age value was provided during insertion.
Example
Output
Explanation
The DEFAULT constraint is used to provide a default value for a column. In the given example, when a new record in the Employees table is being inserted without a value for the City field, the DEFAULT ‘Unknown’ will be implemented. Hence, under the City field for John Doe, the output shows ‘Unknown’.
Example
Output
Explanation
The SQL query created a table Employees
with a DEFAULT
value for the Salary
column. When a new entry is inserted without specifying the Salary
, as was done for ‘John Doe’, the DEFAULT
value of 50000 is assigned.