How Do I Change Multiple Column Names in SQL?

SQL, short for Structured Query Language, is a powerful tool for managing data in databases. If you’re new to SQL, you might wonder: “How do I rename multiple columns at once?” or “Can I modify several columns in SQL?” These questions are common for beginners. In this blog post, we’ll take you through the process of renaming all columns in SQL and help you understand how to efficiently manage your database’s structure.
 

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_idemp_first_nameemp_last_nameemp_salary
1JohnDoe50000
2JaneSmith60000

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_idfirst_namelast_nameemp_salary
1JohnDoe50000.00
2JaneSmith60000.00

HackerRank SQL Questions with Answers :

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_idfirst_namelast_nameemp_salary
1JohnDoe50000.00
2JaneSmith60000.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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top