DEFAULT Values
The DEFAULT constraint in SQL is used to provide a default value for a column when no value is specified during an insert. It helps ensure that all records have valid values without requiring manual input for every column.
This is especially useful for fields like status, created_at timestamps, or boolean flags.
Syntax
CREATE TABLE table_name (
column_name datatype DEFAULT default_value
);
To modify an existing table:
ALTER TABLE table_name
ALTER COLUMN column_name SET DEFAULT default_value;
Example: Add Default Gender to employees
Let’s assume most employees are male, so we set a default value for gender:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
department VARCHAR(50),
gender VARCHAR(50) DEFAULT 'male'
);
INSERT INTO employees (id, name, age, department)
VALUES (1, 'John', 28, 'IT');
-- This will insert 'male' as gender automatically
Key Points
- Default values are used when no explicit value is provided
- Can apply to most data types
- Helps avoid
NULLvalues unintentionally