Using the ALTER TABLE statement and the RENAME COLUMN clause, you can rename a column in SQL. Depending on the database management system (DBMS) you are using, the precise syntax for renaming a column may differ slightly.
Each DBMS has its own unique syntax. However, the fundamental idea is still the same.
Here is a systematic example of how to rename a column in SQL using the standard SQL syntax: Let us
assume we have a table named “employees” with the following structure and data:
Original table: “employees”
emp_id | first_name | last_name | department |
1 | John | Doe | HR |
2 | Harry | Smith | IT |
3 | Danielle | Pereira | Finance |
Step 1: Connect to your database:
As soon as you are connected to your database using a SQL client or another program that supports running SQL queries, double-check that you have the appropriate rights to make changes to the table.
Step 2: Check the existing column names:
You can run the following query to confirm the current column names in the employee’s table:
DESCRIBE employees;
-- or --
SHOW COLUMNS FROM employees;
Step 3: Rename the column:
Now suppose you wish to give the department column the new name of dept. The following SQL statement will be used to rename the column:
-- Syntax for MySQL, MariaDB, and similar DBMSs:
ALTER TABLE employees
CHANGE COLUMN department dept VARCHAR(50);
-- Syntax for PostgreSQL:
ALTER TABLE employees
RENAME COLUMN department TO dept;
-- Syntax for SQL Server:
EXEC sp_rename 'employees.department', 'dept', 'COLUMN';
-- Syntax for Oracle:
ALTER TABLE employees
RENAME COLUMN department TO dept;
Note: If you wish to modify the data type of the column while renaming it, replace (VARCHAR(50)) with the proper data type for the column.
Step 4: Verify the changes:
To verify that the column name has been successfully renamed, you can execute the DESCRIBE or SHOW COLUMNS query again:
DESCRIBE employees;
-- or --
SHOW COLUMNS FROM employees;
The output should now show the updated column name:
Updated table: employees
emp_id | first_name | last_name | dept |
1 | John | Doe | HR |
2 | Harry | Smith | IT |
3 | Danielle | Pereira | Finance |
That’s it! The column name has been successfully renamed in the table employees. Remember to use the appropriate syntax for your specific DBMS.