Method 1: Using the ALTER TABLE Statement
Syntax:
ALTER TABLE table_name CHANGE COLUMN old_column_name new_column_name data_type;
Example:
Suppose we have a table called employees with the following structure:
Original Table – employees:
emp_id | emp_first_name | emp_last_name | emp_salary |
---|---|---|---|
1 | John | Doe | 50000 |
2 | Jane | Smith | 60000 |
We want to rename the emp_first_name and emp_last_name columns to first_name and last_name, respectively, and change the data type of emp_salary to DECIMAL(10, 2).
SQL Query:
ALTER TABLE employees
CHANGE COLUMN emp_first_name TO first_name VARCHAR(255),
CHANGE COLUMN emp_last_name TO last_name VARCHAR(255),
CHANGE COLUMN emp_salary TO emp_salary DECIMAL(10, 2);
Modified Table – employees:
emp_id | first_name | last_name | emp_salary |
---|---|---|---|
1 | John | Doe | 50000.00 |
2 | Jane | Smith | 60000.00 |
HackerRank SQL Questions with Answers :
- HackerRank: Query a Triangle’s Type Based on its side lengths. (Types of Trianlge)
- HackerRank SQL – The PADS Solution with Explanation (MySQL, MS SQL Server)
- Weather Observation Station 20 – HackerRank SQL Solution
- Hackerrank – Draw The triangle 1 (SQL Solution with Explanation)
Method 2: Using the RENAME COLUMN Statement (PostgreSQL, MySQL)
Syntax:
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
Example:
Consider the same table employees as in the previous example, but this time, we’ll use PostgreSQL to rename the emp_first_name and emp_last_name columns to first_name and last_name, respectively.
SQL Query:
ALTER TABLE employees
RENAME COLUMN emp_first_name TO first_name,
RENAME COLUMN emp_last_name TO last_name;
Modified Table – employees:
emp_id | first_name | last_name | emp_salary |
---|---|---|---|
1 | John | Doe | 50000.00 |
2 | Jane | Smith | 60000.00 |
These examples demonstrate two different methods to change multiple column names in SQL, using the ALTER TABLE statement and the RENAME COLUMN statement in PostgreSQL, MySQL respectively.