The ALTER statement in SQL is used to modify the structure of an existing database object, such as a table, index, or column. It is part of the Data Definition Language (DDL) and allows for changes to be made without needing to recreate the object.
The ALTER TABLE statement is used to modify the structure of an existing table. You can add, modify, or delete columns, and even rename the table.
To add a new column to an existing table, you use the ADD COLUMN clause.
-- Add a new column 'Email' to the 'Students' table ALTER TABLE Students ADD Email VARCHAR(100); -- Insert data into the new column UPDATE Students SET Email = 'alice@example.com' WHERE StudentID = 1;
If you need to change the data type or constraints of an existing column, you use the MODIFY COLUMN clause.
-- Modify the 'Grade' column to allow longer values (changing the size) ALTER TABLE Students MODIFY COLUMN Grade VARCHAR(5);
If you want to remove an existing column from a table, you use the DROP COLUMN clause.
-- Drop the 'Email' column from the 'Students' table ALTER TABLE Students DROP COLUMN Email;
To rename an existing table, you use the RENAME TO clause. This is supported by some RDBMS like MySQL and PostgreSQL.
-- Rename the 'Students' table to 'Pupils' ALTER TABLE Students RENAME TO Pupils;
The ALTER DATABASE statement is used to modify the properties of an existing database, such as renaming it or changing its settings.
-- Rename an existing database from 'SchoolDB' to 'UniversityDB' ALTER DATABASE SchoolDB MODIFY NAME = UniversityDB;
Although indexes are typically created using the CREATE INDEX statement, certain RDBMS allow modification of existing indexes with the ALTER INDEX statement. However, in many systems, index modifications often require dropping and recreating them.
-- Drop and recreate an index (if modification is not supported directly) DROP INDEX idx_name ON Students; CREATE INDEX idx_name ON Students (Name);
With the ALTER TABLE statement, you can also add constraints, such as PRIMARY KEY, FOREIGN KEY, UNIQUE, and CHECK.
-- Add a UNIQUE constraint on the 'Email' column ALTER TABLE Students ADD CONSTRAINT unique_email UNIQUE (Email);
If you need to remove a constraint from an existing table, you use the DROP CONSTRAINT clause.
-- Remove the UNIQUE constraint on the 'Email' column ALTER TABLE Students DROP CONSTRAINT unique_email;
The ALTER statement in SQL provides a powerful tool for modifying existing database structures. It allows you to adjust your schema as your application evolves, making it essential for ongoing database maintenance and optimization.