Changing a column type
- SQL course
- Intermediate
- Lesson 109/115
- 4 min
Change a column type with ALTER COLUMN.
Changing column type
With ALTER COLUMN or MODIFY COLUMN you change a column's type.
ALTER TABLE products
ALTER COLUMN price TYPE DECIMAL(12,2);This query changes price type to DECIMAL(12,2).
Changing column type — details
Type changes can cause data loss. Small to large is safe; the reverse is risky.
For example, growing VARCHAR(50) to VARCHAR(100) is safe; shrinking it to VARCHAR(10) truncates longer values or raises an error.
Practice Changing column type
Change the price column type to DECIMAL(12,2).
Starter code
-- change type
ALTER TABLE productsSample solution
ALTER TABLE products
ALTER COLUMN price TYPE DECIMAL(12,2);Expected output
Tablo güncellendi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is a type change risky?
- From a smaller type to a larger one
- To the same type
- Never
- From a larger type to a smaller one Correct answer
Explanation: Large to small type change is risky.
2 Add ALTER COLUMN
ALTER TABLE products
____ price TYPE DECIMAL(12,2);
ALTER TABLE products
ALTER COLUMN price TYPE DECIMAL(12,2);
Explanation: ALTER COLUMN is the right answer.
3 Changing a column type: match the terms
| Term | Meaning |
|---|---|
ALTER COLUMN |
change type |
large to small |
risky |
data loss |
possible |
backup |
first |