The ALTER command is a DDL command that can be used to change the structure of existing tables in the database by adding, modifying, renaming, or removing columns and constraints. Using the ALTER command, you can add columns, rename columns, delete columns, or change the data type of columns.
ALTER Command: Syntax
- Adding a Column:
ADD is used to insert new columns into an existing table. When we need to add more information, we don’t have to recreate the entire database; instead, ADD comes to our rescue.
ALTER TABLE table_name ADD column_name1 data_type, column_name2 data_type, ...
Consider the student_details table( where Roll int, Name varchar(10)), which will be used to execute all the preceding commands.
Query to add another column “Marks” in the student_details table.
ALTER Table student_details ADD Marks INT;
Note: The values in column “Marks” are left blank because we added the column to the table and not inserted the values in it.
- Modifying data type of column:
The ALTER command in SQL can be used to modify the existing columns of a table, and it is possible to modify multiple columns at once.
ALTER TABLE table_name MODIFY column_name column_type;
Query to modify the Name column datatype from varchar(10) to varchar(25).
ALTER Table student_details MODIFY COLUMN Name varchar(25);
- Rename a Column:
We can use the ALTER command to rename an existing column in a database table.
ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name;
Query to rename the Roll column to Enrollment.
ALTER TABLE student_details RENAME COLUMN Roll TO Enrollment;
- Drop a Column:
To remove a column from an existing database table, use the ALTER TABLE command.
ALTER TABLE table_name DROP COLUMN column_name;
Query to drop column Marks.
ALTER TABLE student_details DROP COLUMN Marks;
Note: also read about SQL Data Types
Please follow me to read my latest post on programming and technology if you like my post.
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Reply