Meritshot Tutorials

  1. Home
  2. »
  3. SQL ALTER TABLE Statement

SQL Tutorial

SQL ALTER TABLE Statement

The ALTER TABLE statement is used to modify an existing table in SQL. You can add, delete, or modify columns, as well as change constraints like primary keys.

Syntax

— Add a new column

ALTER TABLE table_name

ADD column_name datatype;

— Delete an existing column

ALTER TABLE table_name

DROP COLUMN column_name;

— Modify an existing column

ALTER TABLE table_name

MODIFY COLUMN column_name datatype;

— Rename a column

ALTER TABLE table_name

RENAME COLUMN old_name TO new_name;

Example:

1 Adding a New Column

Suppose you want to add an Email column to the Students table:

ALTER TABLE Students

ADD Email VARCHAR(100);

This command adds a new column named Email to the Students table.

2 Deleting a Column

If you no longer need the Grade column in the Students table:

ALTER TABLE Students

DROP COLUMN Grade;

This command removes the Grade column from the Students table.

3 Modifying a Column

Let’s say you want to change the data type of the Salary column in the Employees table from INT to DECIMAL:

ALTER TABLE Employees

MODIFY COLUMN Salary DECIMAL(10, 2);

This command modifies the Salary column to store decimal values instead of integers.

4 Modifying a Column

Let’s say you want to change the data type of the Salary column in the Employees table from INT to DECIMAL:

ALTER TABLE Employees

MODIFY COLUMN Salary DECIMAL(10, 2);

This command modifies the Salary column to store decimal values instead of integers.

Tips to Remember

  1. Backup Data: Always back up your table before making changes.
  2. Check Compatibility: Ensure the new data type is compatible when modifying a column.
  3. Be Careful with DROP: Dropping a column permanently deletes all data in that column.

Frequently Asked Questions

Q1: Can I add multiple columns at once?
A1: Yes, you can add multiple columns in one statement:

ALTER TABLE Students

ADD Email VARCHAR(100),

ADD Address VARCHAR(255);

Q2: What if I try to drop a non-existent column?
A2: SQL will return an error. Use IF EXISTS in some systems to avoid this.

Q3: Can I rename and modify a column simultaneously?
A3: It depends on the SQL dialect, but typically, these actions are done separately.

Q4: How do I verify that changes were made?
A4: Use a DESCRIBE or SHOW COLUMNS command to check the table structure.

Q5: How often can I alter a table?
A5: There’s no limit, but excessive alterations can complicate the table structure.