Sub topic 6
Changing a column's type
This chapter assumes you can write CREATE TABLE, know the common data types (INTEGER, VARCHAR, NUMERIC, TIMESTAMP), and have used ALTER TABLE ... ADD COLUMN. It covers how to change the data type of an existing column, what the database does while it does so, and the errors you are most likely to hit.
Why type changes are different
Adding a column touches only the table definition. Changing a column's type can touch every stored row. The database has to decide whether each existing value fits the new type, and it may have to rewrite the whole table to store the values in the new format.
Typical reasons to change a type:
- A
VARCHAR(100)name column turns out to be too short. - A price stored as
INTEGERneeds cents, so it becomesNUMERIC(10, 2). - A date was stored as text and should be a real
DATE. - A counter outgrows
INTEGERand needsBIGINT.
The syntax in three dialects
The standard SQL form is not widely implemented, so each database uses its own syntax. The same change, widening name to 200 characters, looks like this:
-- PostgreSQL
ALTER TABLE customers ALTER COLUMN name TYPE VARCHAR(200);
-- MySQL
ALTER TABLE customers MODIFY COLUMN name VARCHAR(200) NOT NULL;
-- SQL Server
ALTER TABLE customers ALTER COLUMN name VARCHAR(200) NOT NULL;Pay attention to NOT NULL in the MySQL and SQL Server versions. In those systems the statement describes the whole new column definition, not only the type. If you leave NOT NULL out, the column becomes nullable. PostgreSQL treats type, nullability and default as separate settings, so changing the type there leaves nullability alone.
| Behavior | PostgreSQL | MySQL | SQL Server |
|---|---|---|---|
| Keyword | `ALTER COLUMN ... TYPE` | `MODIFY COLUMN` (or `CHANGE COLUMN`) | `ALTER COLUMN` |
| Nullability if omitted | Unchanged | Reset to nullable | Reset to nullable |
| Default if omitted | Unchanged | Dropped | Unchanged, but an existing default constraint can block the change |
| Needs a conversion hint | Sometimes (`USING`) | No, converts implicitly | No, converts implicitly |
SQLite has no statement for changing a column's type. The usual approach is to create a new table with the desired definition, copy the rows across, drop the old table, and rename the new one. Its ALTER TABLE supports only adding, renaming and dropping columns, plus renaming tables.
Safe changes and risky changes
Think of a type change as one of three kinds.
- Widening. The new type can hold every value the old type could:
VARCHAR(100)toVARCHAR(200),INTEGERtoBIGINT,NUMERIC(8,2)toNUMERIC(12,2). Conversion cannot fail. - Narrowing. The new type may not hold every existing value:
VARCHAR(200)toVARCHAR(50),BIGINTtoINTEGER,TIMESTAMPtoDATE. The change fails if any row does not fit, or, in some MySQL configurations, silently truncates the data. - Reinterpreting. The type family changes: text to number, text to date, number to boolean. The database must parse each value, and any value it cannot parse stops the statement.
Widening is usually cheap and safe. The other two deserve a check of the data first.
-- Will narrowing to VARCHAR(50) lose anything?
SELECT id, name, LENGTH(name) AS len
FROM customers
WHERE LENGTH(name) > 50;If this query returns rows, decide what to do with them before running the ALTER. SQL Server spells the function LEN.
Converting between type families with USING
PostgreSQL refuses a change when no implicit conversion exists between the two types. Suppose a table stores quantities as text:
CREATE TABLE shipments (
id INTEGER PRIMARY KEY,
quantity VARCHAR(20) NOT NULL
);
INSERT INTO shipments (id, quantity) VALUES (1, '12'), (2, '40');
ALTER TABLE shipments ALTER COLUMN quantity TYPE INTEGER;The last statement fails with an error like column "quantity" cannot be cast automatically to type integer. The fix is a USING clause, which supplies the expression that converts each old value:
ALTER TABLE shipments
ALTER COLUMN quantity TYPE INTEGER
USING quantity::INTEGER;USING can hold any expression over the row's columns. This makes it useful for cleaning data during the change. For example, to strip a unit suffix such as '12 kg':
ALTER TABLE shipments
ALTER COLUMN quantity TYPE INTEGER
USING regexp_replace(quantity, '[^0-9]', '', 'g')::INTEGER;MySQL and SQL Server convert implicitly instead. That is convenient but riskier, because the rules for what happens to bad values depend on settings. In MySQL with strict mode on, an unparsable value makes the statement fail. With strict mode off, MySQL may convert it to 0 or truncate it with only a warning. Check SELECT @@sql_mode; before relying on either behavior.
Defaults and dependent objects
A column's default value has its own type. In PostgreSQL, if the default cannot be converted to the new type, the statement fails. The usual workaround is to drop the default, change the type, and set the default again:
ALTER TABLE shipments ALTER COLUMN quantity DROP DEFAULT;
ALTER TABLE shipments ALTER COLUMN quantity TYPE INTEGER USING quantity::INTEGER;
ALTER TABLE shipments ALTER COLUMN quantity SET DEFAULT 0;Other objects can also block a type change:
- Views. PostgreSQL will not change the type of a column that a view uses. You must drop and recreate the view.
- Indexes. The database rebuilds them automatically, which adds time to the change.
- Foreign keys. Both sides of a foreign key must have compatible types. If you change
customers.idfromINTEGERtoBIGINT, you must also changeorders.customer_id, and some systems require you to drop the foreign key first and add it back afterwards. - Check constraints and defaults in SQL Server. A default or check constraint that references the column must be dropped before
ALTER COLUMN.
What happens inside the database
Whether the table is rewritten depends on the change and the database.
Rather than rely on memory, treat the rewrite question as a property you verify for your database and version.
Examples in PostgreSQL: increasing the length limit of a VARCHAR is a metadata-only change in modern versions, but INTEGER to BIGINT rewrites the table because the stored width differs. In MySQL with InnoDB, some changes can run in place and some copy the table. You can request a specific behavior and get an error if it is not possible:
-- MySQL: fail instead of silently copying the table
ALTER TABLE customers
MODIFY COLUMN name VARCHAR(200) NOT NULL,
ALGORITHM=INPLACE, LOCK=NONE;A rewrite on a large table can take minutes or hours, and during that time writes, and sometimes reads, are blocked. The locking chapter covers this in detail.
Common errors
| Symptom | Likely cause | What to do |
|---|---|---|
| `cannot be cast automatically to type` | PostgreSQL has no implicit conversion | Add a `USING` clause |
| `value too long for type` or `Data too long` | Narrowing with rows that do not fit | Find and fix long values first |
| `invalid input syntax for type integer` | A text value is not a number | Clean the data, or handle it in `USING` |
| Column became nullable after the change | MySQL or SQL Server definition omitted `NOT NULL` | Repeat the full definition |
| `cannot alter type of a column used by a view` | A view depends on the column | Drop and recreate the view |
| Statement hangs | Another transaction holds a lock on the table | Find the blocking session; see the locking chapter |
A safe workflow
- Take a backup, or at least copy the table:
CREATE TABLE shipments_backup AS SELECT * FROM shipments; - Query for rows that will not convert or will not fit.
- Check what depends on the column: views, indexes, foreign keys, defaults.
- Run the change inside a transaction where your database supports transactional DDL (PostgreSQL does, MySQL does not).
- Verify with a query on the new type and on a sample of the data.
-- PostgreSQL
BEGIN;
ALTER TABLE shipments
ALTER COLUMN quantity TYPE INTEGER USING quantity::INTEGER;
SELECT id, quantity, pg_typeof(quantity) FROM shipments;
COMMIT; -- or ROLLBACK; if the result looks wrongExercise
A PostgreSQL table events has a column happened_on VARCHAR(10) holding values like '2026-11-27'. You run ALTER TABLE events ALTER COLUMN happened_on TYPE DATE; and it fails. What is the most likely reason, and what statement would you run instead?
Show answer
PostgreSQL has no implicit cast from VARCHAR to DATE for ALTER COLUMN, so it asks for an explicit conversion. Run: ALTER TABLE events ALTER COLUMN happenedon TYPE DATE USING happenedon::DATE; Check first for values that are not valid dates, because the USING cast fails on the first one it cannot parse.
Exercise
You run ALTER TABLE customers MODIFY COLUMN name VARCHAR(200); on MySQL, where name was originally VARCHAR(100) NOT NULL. What else changed about the column, and how do you avoid it?
Show answer
The column is now nullable, because MODIFY replaces the whole column definition and NOT NULL was left out. Avoid this by repeating the full definition: ALTER TABLE customers MODIFY COLUMN name VARCHAR(200) NOT NULL;