DEFAULT Constraint
All SQL topics∙ Topic
DEFAULT Constraint
The DEFAULT constraint in SQL is used to assign a default value to a column when no value is specified during an INSERT operation.
Syntax
CREATE TABLE table_name (
column_name datatype DEFAULT value
);
📝 Edit Code
👁 Preview
💡 This preview does not execute SQL; itβs for reading/editing the query.
What is DEFAULT Constraint?
- 1Assigns a default value to a column.
- 2Used when no value is provided.
- 3Improves data consistency.
- 4Works during INSERT operations.
How DEFAULT Works
- 1If value is not specified, default is used.
- 2Database automatically fills the value.
- 3Works at insert time only.
- 4Can use constants or functions.
Examples of DEFAULT
- 1Status DEFAULT 'Active'.
- 2CreatedAt DEFAULT CURRENT_DATE.
- 3Quantity DEFAULT 1.
- 4Country DEFAULT "India".
Use Cases of DEFAULT
- 1User registration systems.
- 2Order management systems.
- 3Logging and tracking tables.
- 4Inventory management.
Advantages of DEFAULT
- 1Reduces manual input.
- 2Ensures consistent data.
- 3Simplifies INSERT queries.
- 4Prevents NULL values in optional fields.
Limitations of DEFAULT
- 1Does not apply on UPDATE.
- 2May hide missing input errors.
- 3Limited to simple expressions in some DBs.
- 4Can be overridden explicitly.
Real-world
- 1Set default user status as Active.
- 2Automatically assign current date.
- 3Simplify insert operations.
- 4Ensure consistent data values.
- 5Reduce missing field errors.
Common Mistakes
- 1Using incorrect default data types.
- 2Assuming default applies on updates.
- 3Forgetting database-specific functions.
- 4Overusing default values unnecessarily.
Best Practices
- 1Use meaningful default values.
- 2Apply defaults for optional fields.
- 3Combine with NOT NULL when needed.
- 4Avoid complex expressions as defaults.
Quick Summary
- DEFAULT sets automatic values for columns.
- Used when no value is provided in INSERT.
- Improves data consistency.
- Works only during insertion.
- Common for status and timestamps.
Interview Questions
Q1. What is DEFAULT constraint?
Answer: It sets a default value for a column when no value is provided.
Q2. When is DEFAULT applied?
Answer: During INSERT operations.
Q3. Does DEFAULT work on UPDATE?
Answer: No, it only works on INSERT.
Q4. Can DEFAULT use functions?
Answer: Yes, like CURRENT_DATE or NOW().
Q5. Why use DEFAULT constraint?
Answer: To simplify inserts and ensure consistent values.
Quiz
What does DEFAULT constraint do?