ALTER, DROP & TRUNCATE
ALTER TABLE – change an existing table
Columns
- Add:
ALTER TABLE t ADD COLUMN phone TEXT; - Add with default:
ADD COLUMN is_verified BOOLEAN NOT NULL DEFAULT false(existing rows get the default) - Drop:
DROP COLUMN phone;⚠️ data is lost - Rename:
RENAME COLUMN phone TO mobile; - Change type:
ALTER COLUMN amount TYPE NUMERIC(12,2);- Convert with
USING:ALTER COLUMN code TYPE INT USING code::int
- Convert with
- Defaults:
ALTER COLUMN status SET DEFAULT 'new';/DROP DEFAULT - Nullability:
ALTER COLUMN city SET NOT NULL;(fails if NULLs exist) /DROP NOT NULL
Constraints
ADD CONSTRAINT name CHECK (...),ADD CONSTRAINT name UNIQUE (...)DROP CONSTRAINT name;
Table
ALTER TABLE old_name RENAME TO new_name;
Removing data and tables
| Command | What it removes | WHERE? | Speed | Undo inside a transaction? |
|---|---|---|---|---|
DELETE FROM t | rows | ✅ | slower (row by row) | ✅ |
TRUNCATE t | all rows | ❌ | very fast | ✅ in PostgreSQL |
DROP TABLE t | the whole table + data | ❌ | fast | ✅ in PostgreSQL |
TRUNCATE t RESTART IDENTITY– also resets the auto-increment counterTRUNCATE/DROPfail if other tables reference this one; addCASCADE(careful — it affects those tables too!)DROP TABLE IF EXISTS t;– no error if it's missing
Safety tips for production
- Test schema changes on a copy first, and back up before destructive changes
- Wrap changes in
BEGIN … COMMITso you canROLLBACK - Keep changes in migration files in Git (Unit 14)
- On big tables, some ALTERs lock the table or rewrite it — schedule them carefully
Example
CREATE TABLE subscriptions (
id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name TEXT,
price TEXT -- oops: wrong type
);
INSERT INTO subscriptions (name, price) VALUES ('Netflix', '1499'), ('Spotify', '299');
-- Fix the type, converting existing values
ALTER TABLE subscriptions ALTER COLUMN price TYPE NUMERIC(10,2) USING price::numeric;
-- Add columns (existing rows get the default)
ALTER TABLE subscriptions ADD COLUMN billing_day INT NOT NULL DEFAULT 1;
ALTER TABLE subscriptions ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;
-- Rename and require values
ALTER TABLE subscriptions RENAME COLUMN name TO service;
ALTER TABLE subscriptions ALTER COLUMN service SET NOT NULL;
-- Add a named constraint
ALTER TABLE subscriptions ADD CONSTRAINT valid_billing_day
CHECK (billing_day BETWEEN 1 AND 28);
SELECT * FROM subscriptions;
-- id | service | price | billing_day | is_active
-- 1 | Netflix | 1499.00 | 1 | t
-- 2 | Spotify | 299.00 | 1 | t
-- Safely try a destructive change inside a transaction
BEGIN;
TRUNCATE subscriptions RESTART IDENTITY;
SELECT count(*) FROM subscriptions; -- 0
ROLLBACK; -- changed my mind!
SELECT count(*) FROM subscriptions; -- 2
ALTER TABLE subscriptions RENAME TO user_subscriptions;
DROP TABLE IF EXISTS user_subscriptions;