ALTER Statement

The ALTER statement is used to modify the structure of an existing table by adding, removing, or changing columns or constraints. It provides flexibility for managing and updating database schema.

Examples of Using ALTER

Scenario 1: Adding a New Column

You can add a new column to an existing table.

ALTER TABLE FreedomFighters
ADD Hometown VARCHAR(50);

Output:

Column Hometown added successfully.

Scenario 2: Adding a Column as the First Column

To add a new column at the beginning of the table, some SQL dialects support this syntax.

ALTER TABLE FreedomFighters
ADD Nationality VARCHAR(50) FIRST;

Output:

Column Nationality added as the first column successfully.

Scenario 3: Adding a Column After a Specific Column

You can specify the position of the new column.

ALTER TABLE FreedomFighters
ADD Nationality VARCHAR(50) AFTER Name;

Output:

Column Nationality added after Name column successfully.

Scenario 4: Modifying a Column

To change the data type or properties of an existing column.

ALTER TABLE FreedomFighters
MODIFY COLUMN Contribution VARCHAR(255);

Output:

Column Contribution modified successfully.

Scenario 5: Dropping a Column

To remove a column from the table.

ALTER TABLE FreedomFighters
DROP COLUMN Hometown;

Output:

Column Hometown dropped successfully.

Scenario 6: Renaming a Column

To change the name of a column (supported in some SQL dialects).

ALTER TABLE FreedomFighters
RENAME COLUMN Contribution TO Achievements;

Output:

Column Contribution renamed to Achievements successfully.

Do's and Don'ts

Do's

  • Use ALTER carefully, especially when modifying data types or adding constraints.
  • Take a backup of the table before performing major alterations.
  • Communicate schema changes to your development team to avoid issues.
  • Test the table structure changes thoroughly in a development environment before applying them in production.

Don'ts

  • Don't remove columns unless you are sure they are not needed, as it may result in data loss.
  • Don't make structural changes during peak usage times to prevent performance degradation.
  • Don't forget to test the impact of your changes on existing queries and applications.
  • Don't modify columns without understanding the implications for the data stored within them.