ALTER TABLE Statement in SQL
SQL ALTER TABLE tutorial with examples for beginners
The ALTER TABLE statement in SQL is used to modify the structure of an existing table. It allows you to add, remove, or change columns, as well as manage constraints like PRIMARY KEY, FOREIGN KEY, UNIQUE, and DEFAULT.
This SQL tutorial will help you understand:
What ALTER TABLE does
Different ALTER TABLE operations
Add, modify, and drop columns
Add and remove constraints
Rename tables and columns
Real-world examples
Best practices
The ALTER TABLE command updates a table’s schema without deleting existing data.
You can use ALTER TABLE to:
Add a new column
Modify a column
Delete a column
Rename a column or table
Add/remove constraints
Change data types
ALTER TABLE table_name
operation;
ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE users
ADD age INT;
ALTER TABLE users
ADD (phone VARCHAR(20), status VARCHAR(20));
ALTER TABLE users
MODIFY age SMALLINT;
MySQL:
ALTER TABLE users
CHANGE COLUMN name full_name VARCHAR(150);
PostgreSQL:
ALTER TABLE users
RENAME COLUMN name TO full_name;
ALTER TABLE users
DROP COLUMN age;
⚠ Warning: Dropped columns cannot be recovered without backup.
ALTER TABLE customers
ADD PRIMARY KEY (customer_id);
ALTER TABLE orders
ADD CONSTRAINT fk_user
FOREIGN KEY (user_id) REFERENCES users(id);
MySQL:
ALTER TABLE orders
DROP FOREIGN KEY fk_user;
ALTER TABLE users
ADD CONSTRAINT unique_email UNIQUE(email);
MySQL:
ALTER TABLE users
DROP INDEX unique_email;
ALTER TABLE employees
MODIFY name VARCHAR(150) NOT NULL;
ALTER TABLE accounts
ALTER status SET DEFAULT 'active';
MySQL alternative:
ALTER TABLE accounts
MODIFY status VARCHAR(20) DEFAULT 'active';
ALTER TABLE users
RENAME TO customers;
ALTER TABLE users
ADD last_login DATETIME;
ALTER TABLE employees
MODIFY salary DECIMAL(10,2);
ALTER TABLE orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id) REFERENCES customers(id);
ALTER TABLE products
DROP COLUMN old_price;
✔ Backup tables before structural changes
✔ Use constraints carefully to maintain data integrity
✔ Avoid dropping columns unless necessary
✔ Test ALTER commands on a development database first
✔ Keep table naming consistent
✔ Add indexes for improved query performance
In this SQL ALTER TABLE tutorial, you learned:
How to add, modify, and drop columns
How to manage constraints (PRIMARY KEY, UNIQUE, FOREIGN KEY)
How to rename tables and columns
Real-world ALTER TABLE examples
ALTER TABLE is essential for maintaining and evolving database structure without losing data.