erd.sketch

SQL migration: the ALTERs between two versions of a schema

On the left the schema as it was, on the right as it became. Below is what the editor emits to turn one into the other — real output, not an example from the docs.

Beforev1.sql
CREATE TABLE users (
    id BIGSERIAL PRIMARY KEY,
    email VARCHAR(120) NOT NULL,
    created_at TIMESTAMPTZ
);

CREATE TABLE orders (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL,
    total NUMERIC(12,2) NOT NULL
);
Afterv2.sql
CREATE TABLE users (
    id BIGSERIAL PRIMARY KEY,
    email VARCHAR(255) NOT NULL,
    phone VARCHAR(120),
    created_at TIMESTAMPTZ NOT NULL,
    CONSTRAINT uq_users_email UNIQUE (email)
);

CREATE TABLE orders (
    id BIGSERIAL PRIMARY KEY,
    user_id BIGINT NOT NULL,
    total NUMERIC(12,2) NOT NULL,
    CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);

CREATE INDEX idx_orders_user ON orders (user_id);
What comes outPostgreSQL
ALTER TABLE users ADD COLUMN phone VARCHAR(120);
ALTER TABLE users ALTER COLUMN email TYPE VARCHAR(255);
ALTER TABLE users ALTER COLUMN created_at SET NOT NULL;
ALTER TABLE users ADD CONSTRAINT uq_users_email UNIQUE (email);

CREATE INDEX idx_orders_user ON orders (user_id);

ALTER TABLE orders ADD CONSTRAINT fk_orders_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
Open the editor

The script stays in the browser: both parsing and generation run on your machine, nothing goes to a server.

The same change in different dialects

PostgreSQLALTER TABLE users ALTER COLUMN email TYPE VARCHAR(255);
MySQL / MariaDBALTER TABLE users MODIFY COLUMN email VARCHAR(255) NOT NULL;
SQL ServerALTER TABLE users ALTER COLUMN email NVARCHAR(255) NOT NULL;
OracleALTER TABLE users MODIFY (email VARCHAR2(255));