Loading...
SQL DEFAULT
DEFAULT in SQL
The DEFAULT constraint in SQL is used to set a default value for a column. When a new record is inserted into the table and no value is specified for a column with a DEFAULT constraint, the default value is automatically applied. This ensures that no column is left empty unless explicitly specified.
Characteristics of the DEFAULT Constraint
- The
DEFAULTconstraint is applied to columns during table creation or modification. - It applies to new rows only; existing rows remain unaffected when the default value is added.
- Supports both static values (e.g., a string or number) and system-generated values (e.g., functions like
GETDATE()orCURRENT_TIMESTAMP).
How to Apply DEFAULT Constraint
The DEFAULT constraint can be applied when creating a table or added to an existing table.
1. Adding DEFAULT During Table Creation
Static Default Value
mysql
6 lines
|44/ 500 tokens
1 2 3 4 5 6CREATE TABLE Employees ( EmployeeID INT NOT NULL, Name VARCHAR(100) NOT NULL, Department VARCHAR(50) DEFAULT 'General', HireDate DATE DEFAULT '2024-01-01' );
- The
Departmentcolumn defaults to "General" if no value is provided. - The
HireDatecolumn defaults to2024-01-01.
System-Generated Default Value
mysql
5 lines
|33/ 500 tokens
1 2 3 4 5CREATE TABLE Orders ( OrderID INT NOT NULL, OrderDate DATE DEFAULT GETDATE(), Status VARCHAR(20) DEFAULT 'Pending' );
- The
OrderDatecolumn defaults to the current date using theGETDATE()function. - The
Statuscolumn defaults to "Pending".
2. Adding DEFAULT to an Existing Table
If the table already exists, you can use the ALTER TABLE statement to add a default constraint.
MySQL
mysql
2 lines
|18/ 500 tokens
1 2ALTER TABLE Employees ALTER COLUMN Department SET DEFAULT 'General';
SQL Server
mysql
2 lines
|22/ 500 tokens
1 2ALTER TABLE Employees ADD CONSTRAINT df_Department DEFAULT 'General' FOR Department;
3. Removing a DEFAULT Constraint
You can drop a DEFAULT constraint if it's no longer needed.
MySQL
mysql
2 lines
|16/ 500 tokens
1 2ALTER TABLE Employees ALTER COLUMN Department DROP DEFAULT;
SQL Server / Oracle
mysql
2 lines
|14/ 500 tokens
1 2ALTER TABLE Employees DROP CONSTRAINT df_Department;
Common Use Cases
- Default Status: Set default values for order statuses (e.g., "Pending").
- Default Location: Set default locations like country or city when unspecified.
- System-Generated Timestamps: Automatically add current dates or times to records when they are created.
Key Points to Remember
- The
DEFAULTconstraint sets a predefined value for a column when no value is provided. - It supports both static values and system-generated values using functions.
- You can add or remove default constraints using
ALTER TABLE. - Default constraints apply to new records only; they do not affect existing data in the table.