SQL DEFAULT constraint

SQL Tutorial

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

FeatureDEFAULTNULL
Value assignedAutomaticNo value
Prevents empty dataYes No
Used in insertWhen value missingWhen explicitly set
marks INT DEFAULT 0 NOT NULL
  •  Best practice: use both together

 Real-Life Example

Orders Table

  • Status auto-set
  •  Timestamp auto-generated

Common Mistakes

  •  Assuming DEFAULT applies when NULL is explicitly inserted
  •  Forgetting quotes for string defaults
  •  Using unsupported expressions as default
  •  Confusing DEFAULT with NOT NULL

Interview Questions (Must Prepare)

  1. What is the DEFAULT constraint in SQL?

  2. When is the default value applied?

  3. Difference between DEFAULT and NOT NULL?

  4. Can a column have both DEFAULT and NOT NULL?

  5. Can DEFAULT use functions like CURRENT_DATE?

  6. What happens if NULL is 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

You may also like...