SQL

ALTER TABLE — Add / Drop / Rename Column

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Evolve your schema in place. Most DBs run these as cheap metadata-only operations IF you avoid expensive rewrites — e.g. don't set a NOT NULL default on a huge table without thinking.
SQL
Raw
-- Add a column with a default (instant in PostgreSQL 11+ for non-volatile defaults)
ALTER TABLE users ADD COLUMN avatar_url TEXT;
ALTER TABLE users ADD COLUMN signup_source TEXT NOT NULL DEFAULT 'web';

-- Drop a column
ALTER TABLE users DROP COLUMN deprecated_field;

-- Rename a column / table
ALTER TABLE users RENAME COLUMN signup_source TO source;
ALTER TABLE users RENAME TO accounts;

-- Change a column type (PostgreSQL — may rewrite the table; check your DB)
ALTER TABLE users ALTER COLUMN age TYPE BIGINT;
ALTER TABLE users ALTER COLUMN email TYPE TEXT USING email::TEXT;

-- Add / drop NOT NULL — beware of existing nulls when adding
ALTER TABLE users ALTER COLUMN email SET NOT NULL;
ALTER TABLE users ALTER COLUMN avatar_url DROP NOT NULL;

-- Add / drop constraints
ALTER TABLE orders ADD CONSTRAINT chk_amount_positive CHECK (amount > 0);
ALTER TABLE orders DROP CONSTRAINT chk_amount_positive;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.