PostgreSQL ADD COLUMN

PostgreSQL ADD COLUMN (Beginner → Advanced)
The ADD COLUMN command in PostgreSQL is used to add a new column to an existing table without deleting existing data.
It’s one of the most common schema-evolution operations.
What is ADD COLUMN?
ADD COLUMNadds a new field (column) to an existing table.
- Table remains intact
- Existing rows stay safe
- New column is added to all rows
Basic ADD COLUMN Example
Table: students
| id | name | marks |
Add a new column
Result:
| id | name | marks | age |
|---|---|---|---|
| 1 | Rahul | 85 | NULL |
- Existing rows get
NULLby default
ADD COLUMN with DEFAULT
- New column added
- Existing rows get
'Active'automatically - Future inserts also use default
ADD COLUMN with NOT NULL
This may fail if table has rows
Correct & Safe Way
- Avoids constraint violation
- Interview-friendly approach
Add Multiple Columns at Once
- Faster
- Cleaner migrations
ADD COLUMN IF NOT EXISTS (Safe Practice)
- Prevents error if column already exists
- Useful in deployment scripts
Add Column with Constraints
UNIQUE
CHECK
ADD COLUMN and Performance
Adding a nullable column without default → very fast
Adding a column with DEFAULT:
PostgreSQL 11+ → optimized (no full rewrite)
Older versions → table rewrite (slow)
Best practice for large tables:
ADD COLUMN vs ALTER COLUMN
| Operation | Purpose |
|---|---|
ADD COLUMN | Add a new column |
ALTER COLUMN | Modify existing column |
DROP COLUMN | Remove a column |
Check Columns After Adding
Common Mistakes
- Adding
NOT NULLwithout default - Forgetting
IF NOT EXISTS Adding many columns one by one- Running on production without testing
Interview Questions (Must Prepare)
How do you add a column in PostgreSQL?
What happens to existing rows?
How to add a
NOT NULLcolumn safely?Can we add multiple columns at once?
Difference between
ADD COLUMNandALTER COLUMN?What is
IF NOT EXISTS?
Summary
- ADD COLUMN adds new fields safely
- Existing rows get NULL or DEFAULT
- Use IF NOT EXISTS for safe scripts
- Combine with constraints if needed
- Be careful with NOT NULL on large tables
- Essential for schema changes & interviews
