Ir al contenido principal

sqlite alter table change column type

 SQLite does not support changing a column's data type directly via the ALTER TABLE statement. 

Because SQLite lacks an ALTER COLUMN or MODIFY COLUMN command, any attempt to change a type results in a syntax error.

To change a column's type, you must perform a table rebuild within a transaction:

  1. Disable foreign keys: PRAGMA foreign_keys = OFF;

  2. Begin a transaction: BEGIN;

  3. Create a new table with the desired schema and column types.

  4. Copy data from the old table to the new table using INSERT INTO ... SELECT ... with explicit CAST() for the changed column.

  5. Drop the old table: DROP TABLE old_name;

  6. Rename the new table: ALTER TABLE new_name RENAME TO old_name;

  7. Recreate indexes and triggers that were on the original table.

  8. Commit: COMMIT;

  9. Re-enable foreign keys: PRAGMA foreign_keys = ON;

This process is necessary because SQLite stores schema and data together, and changing a type requires rewriting the entire table structure. Care must be taken to preserve indexes, triggers, and foreign key relationships, as these are lost during the drop/rename process. 

Comentarios