Widen a column type
The email fits in 50 characters until someone uses a 60-character address. Widening types is routine, but it is cheap on some engines and a full table rewrite on others.
The task
Inserts are starting to fail with data-too-long errors, so the column has to grow, and it helps to know what that will cost before running it on a production table.
The snippet
Written for MySQL. Versions for SQL Server, PostgreSQL and SQLite are under Variations.
ALTER TABLE products
MODIFY COLUMN name VARCHAR(255) NOT NULL;
-- restating the whole definition is required, including NOT NULL
How it works
MySQL requires MODIFY COLUMN to restate the complete column definition, so copy it from SHOW CREATE TABLE first, or a missing NOT NULL, DEFAULT or COMMENT is silently dropped. Growing a VARCHAR is in place only while the maximum byte length stays on the same side of 255, because that decides whether InnoDB stores a 1- or 2-byte length prefix. With utf8mb4 (4 bytes per character) VARCHAR(50) to VARCHAR(60) is in place, but VARCHAR(50) to VARCHAR(255) copies the whole table. int to bigint always copies it.
Variations
PostgreSQL
PostgreSQLALTER TABLE products
ALTER COLUMN name TYPE varchar(255);
-- raising a varchar limit (or removing it) is catalog-only,
-- but both statements fail while a view uses the column:
-- drop and recreate the view around them.
-- int -> bigint rewrites the table and its indexes under
-- an ACCESS EXCLUSIVE lock:
ALTER TABLE products
ALTER COLUMN id TYPE bigint;
SQL Server
SQL ServerALTER TABLE dbo.Products
ALTER COLUMN Name NVARCHAR(255) NOT NULL;
-- a longer varchar/nvarchar is metadata-only, even on an indexed
-- column. int -> bigint updates every row, and indexes or
-- constraints on the column must be dropped first
SQLite
SQLite-- SQLite is loosely typed and ignores VARCHAR length limits,
-- so widening is usually unnecessary; if you must:
-- rebuild the table (new table, copy, drop, rename)
Questions that come up
Should I just use TEXT/NVARCHAR(MAX) everywhere to avoid this?
On PostgreSQL that is reasonable: varchar(n) and text are stored the same way, and the limit only acts as a check. On SQL Server, NVARCHAR(MAX) columns cannot be index key columns and inflate the memory grants the optimizer requests for sorts, and on MySQL a TEXT column accepts no literal default (only an expression default such as DEFAULT (''), from 8.0.13) and cannot be indexed without a prefix length. On those engines keep bounded lengths and widen when needed.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.