// dialect comparison

Añadir una columna a una tabla existente

The most common ALTER: extend the table without losing data.

Filed under Tables & schema

The verdict

Same verb everywhere. The practical rules: a nullable column is instant, a NOT NULL column needs a DEFAULT, SQLite takes one column per statement, and only MySQL lets you choose the position.

Where they differ

Adding a nullable column without a default only changes metadata in all five engines, so it is instant even on huge tables. The differences: SQLite allows one column per statement, MySQL can position the column, and a NOT NULL column on a table with rows needs a DEFAULT to fill them.

How each engine writes it

SQL Server

ALTER TABLE customers ADD phone VARCHAR(40) NULL;

No COLUMN keyword; comma-separate several columns. Adding NOT NULL with a constant DEFAULT is metadata-only on Enterprise edition (2012+); other editions write the default into every row.

PostgreSQL

ALTER TABLE customers ADD COLUMN phone TEXT;

COLUMN is optional. Since 11, NOT NULL with a constant DEFAULT also skips the table rewrite; a volatile default such as random() still rewrites.

MySQL

ALTER TABLE customers ADD COLUMN phone VARCHAR(40) AFTER email;

FIRST and AFTER position the column. ALGORITHM=INSTANT covers columns added last from 8.0.12 and at any position from 8.0.29.

SQLite

ALTER TABLE customers ADD COLUMN phone TEXT;

One column per statement, always appended last. It can't be PRIMARY KEY or UNIQUE, and NOT NULL needs a non-NULL default; defaults must be constants.

Oracle

ALTER TABLE customers ADD (phone VARCHAR2(40));

The parenthesized list adds several columns at once. Adding a column with a DEFAULT is metadata-only too: for NOT NULL columns since 11g, for nullable ones since 12c.

Questions that come up

Why does NOT NULL need a DEFAULT?

Existing rows must get some value for the new column. With a constant DEFAULT, most current versions record it once in the metadata instead of rewriting every row. On an empty table, NOT NULL without a default is accepted everywhere except SQLite.

Can I add a column with a computed value?

Add the column, then fill it with an UPDATE, in batches on a big table. If the value should always be derived from other columns, declare a generated column instead (see generated-columns).

How do I add a column in the middle of the table?

Only MySQL (and MariaDB) offer FIRST and AFTER. Elsewhere you would have to rebuild the table, and column order only matters to SELECT *, which application code shouldn't rely on.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.