SQL DEFAULT constraint

SQL DEFAULT constraint (Beginner → Advanced)
In SQL DEFAULT constraint is used to automatically assign a value to a column when no value is provided during an INSERT operation.
What is the DEFAULT Constraint?
The DEFAULT constraint sets a predefined value for a column if no value is specified.
- Prevents NULL values
- Simplifies INSERT statements
- Improves data consistency
Basic Syntax
While Creating a Table
- If marks is not provided, it will be 0 by default.
DEFAULT with INSERT Statement
- marks will automatically be set to 0
Explicitly Using DEFAULT
- Forces default value
DEFAULT with Different Data Types
Numeric
String
Date / Time
or
Adding DEFAULT to Existing Table
Syntax may vary by database:
MySQL
SQL Server
Dropping a DEFAULT Constraint
MySQL / PostgreSQL
SQL Server
DEFAULT vs NULL
| Feature | DEFAULT | NULL |
|---|---|---|
| Value assigned | Automatic | No value |
| Prevents empty data | Yes | No |
| Used in insert | When value missing | When explicitly set |
- Best practice: use both together
Real-Life Example
Orders Table
Common Mistakes
- Assuming
DEFAULTapplies whenNULLis explicitly inserted - Forgetting quotes for string defaults
- Using unsupported expressions as default
- Confusing
DEFAULTwithNOT NULL
Interview Questions (Must Prepare)
What is the
DEFAULTconstraint in SQL?When is the default value applied?
Difference between
DEFAULTandNOT NULL?Can a column have both
DEFAULTandNOT NULL?Can
DEFAULTuse functions likeCURRENT_DATE?What happens if
NULLis explicitly inserted?
Summary
- DEFAULT assigns automatic values
- Applied when column value is missing
- Works with numbers, strings, dates
- Can be combined with NOT NULL
- Very useful for real-world databases & interviews
