SQL DEFAULT constraint
Here is a clear, practical, and complete guide to the SQL DEFAULT constraint, including syntax, behavior, examples, and DB-specific differences.
✅ What the DEFAULT Constraint Does
A DEFAULT constraint automatically assigns a value to a column when no value is provided during an INSERT.
Useful for:
-
Timestamps
-
Status fields
-
Boolean flags
-
Counters
-
System-generated values
🔹 Basic Syntax (CREATE TABLE)
If status is omitted in an insert, it becomes 'active'.
🔹 Example: DEFAULT with Timestamp
PostgreSQL:
MySQL:
SQL Server:
🔥 DEFAULT on Numeric Fields
🔥 DEFAULT on Boolean Fields
🔥 DEFAULT with Expressions (Engine-Dependent)
PostgreSQL supports expressions:
MySQL supports some expressions:
SQL Server requires parents for functions:
🔹 DEFAULT in ALTER TABLE
PostgreSQL:
MySQL:
SQL Server:
(SQL Server requires naming a default constraint when added later.)
🔹 Remove DEFAULT Constraint
PostgreSQL:
MySQL:
SQL Server:
📌 Real-World Examples
1. Default user status
2. Auto-timestamp creation date
3. Default order quantity
4. Default JSON structure (PostgreSQL)
🧠 Important Behavior Notes
✔ DEFAULT applies only when the column is omitted — not when NULL is explicitly inserted.
Example:
→ status becomes NULL, not the default.
✔ Use NOT NULL + DEFAULT to guarantee a value:
✔ DEFAULT does not retroactively update existing rows.
✔ Triggers, functions, and computed columns may override defaults depending on DB engine.
🏎 Best Practices
✔ Always combine DEFAULT with NOT NULL for required fields
✔ Use default timestamps for audit fields (created_at)
✔ For boolean flags, set defaults (is_active DEFAULT TRUE)
✔ Name default constraints in SQL Server for easier maintenance
✔ Avoid complex expressions that hurt readability
✔ Ensure DEFAULT values reflect business logic
