Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
PostgreSQL - ADD COLUMN
Next article icon

PostgreSQL – RENAME COLUMN

Last Updated : 17 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Renaming columns in PostgreSQL is a common task for developers and database administrators. When aligning with naming conventions, fixing typos, or restructuring database schemas. Using the PostgreSQL ALTER TABLE RENAME COLUMN statement, we can efficiently rename one or more columns without losing data.

In this article, we will explain the syntax, examples, and important considerations to help us rename columns efficiently while ensuring our database operates smoothly.

What is PostgreSQL RENAME COLUMN?

The PostgreSQL ALTER TABLE RENAME COLUMN clause allows us to rename a column in an existing table. We can rename single or multiple columns in different tables to improve readability and consistency in database design. PostgreSQL ensures that this operation is transactional and if anything goes wrong, changes are rolled back to keep the database consistent.

Syntax:

ALTER TABLE table_name 
RENAME COLUMN column_name TO new_column_name;

key terms

  • Specify the Table: The table contains the column we want to rename.
  • Column Name: The name of the column we want to rename.
  • New Column Name: The new name for the column.

Examples of Using PostgreSQL RENAME COLUMN Clause

Let’s take some practical examples to demonstrate how to rename columns, handle foreign key constraints, and work with indexed columns. These examples will guide us through real-world scenarios where renaming columns becomes necessary for better schema organization and readability.

Example 1: Renaming a Single Column in PostgreSQL

Let’s create a customers table and rename the ’email’ column to ‘contact_email‘. This example demonstrates a basic column rename operation, showing how to make schema changes while preserving data and structure.

Step 1: Create Table

CREATE TABLE customers (
id serial PRIMARY KEY,
name VARCHAR NOT NULL,
phone VARCHAR NOT NULL,
email VARCHAR,
group_id INT,
);

Step 2: Insert Data

INSERT INTO customers (name, phone, email, group_id) 
VALUES
('John Doe', '1234567890', '[email protected]', 101),
('Jane Smith', '0987654321', '[email protected]', 102);

Step 3: Verify Data Before Renaming

SELECT * FROM customers;

Output Before Renaming:

id name phone email group_id
1 John Doe 1234567890 [email protected] 101
2 Jane Smith 0987654321 [email protected] 102

Step4: Rename Column

ALTER TABLE customers 
RENAME COLUMN email TO contact_email;

Step 5: Verify Data After Renaming

SELECT * FROM customers;

Output

id name phone contact_email group_id
1 John Doe 1234567890 [email protected] 101
2 Jane Smith 0987654321 [email protected] 102

Explanation:

In this example, the email column was successfully renamed to contact_email. The data in the table remains unchanged, and we can now see the new column name in the output while the existing data, such as email addresses, is preserved.

Example 2: Renaming Multiple Columns

If we need to rename multiple columns in PostgreSQL, we must execute multiple ALTER TABLE statements. These statements rename two columns ‘name’ and ‘phone’ of the ‘customers’ table to ‘customer_name’ and ‘contact_phone’ respectively.

Step 1: Rename Columns

ALTER TABLE customers 
RENAME COLUMN name TO customer_name;

ALTER TABLE customers
RENAME COLUMN phone TO contact_phone;

Step 2: Verify Changes

SELECT * FROM customers;

Output

id customer_name contact_phone contact_email group_id
1 John Doe 1234567890 [email protected] 101
2 Jane Smith 0987654321 [email protected] 102

Explanation:

In this example, we renamed two columns, name to customer_name and phone to contact_phone using separate ALTER TABLE statements. After verifying the changes, the output reflects the updated column names while keeping the data intact.

Example 3: Renaming Columns with Foreign Keys

In this example, we will create an orders table that references the customers table through a foreign key on the customer_id column. After renaming the customer_id column, we will re-establish the foreign key relationship.

Step 1: Create the orders Table

CREATE TABLE orders (
order_id serial PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES customers (id)
);

Step 2: Insert Data into the orders Table

INSERT INTO orders (customer_id, order_date)
VALUES
(1, '2024-01-15'),
(2, '2024-02-20');

Step 3: Drop the Foreign Key Constraint

ALTER TABLE orders  
DROP CONSTRAINT orders_customer_id_fkey;

Step 4: Rename Column

ALTER TABLE orders  
RENAME COLUMN customer_id TO new_customer_id;

Step 5: Add Foreign Key Constraint Again

ALTER TABLE orders  
ADD CONSTRAINT orders_new_customer_id_fkey
FOREIGN KEY (new_customer_id) REFERENCES customers (id);

Step 6: Verify Data

SELECT * FROM orders;

Output After Renaming:

order_id new_customer_id order_date
1 1 2024-01-15
2 2 2024-02-20

Explanation:

In this example, the column customer_id in the orders table was renamed to new_customer_id. After renaming, we re-established the foreign key relationship between the orders and customers tables. The data remains intact, and the foreign key reference is properly updated to reflect the new column name.

Important Points About RENAME COLUMN in PostgreSQL

  • PostgreSQL treats unquoted identifiers as lowercase. If the column names are mixed case or contain special characters, use double quotes.|
  • Renaming a column does not automatically update references to that column in views, triggers, functions, or application code.
  • The RENAME COLUMN operation is transactional. If something goes wrong, the database will roll back to its previous state.
  • Renaming a column does not affect the names of associated constraints or indexes.

Conclusion

Knowing how to rename a column in PostgreSQL ensures better organization and consistency in our database. Using the PostgreSQL ALTER TABLE RENAME COLUMN statement, we can easily rename both single and multiple columns. If a column is indexed, the index reference will automatically update.

However, keep in mind that renaming columns affects dependent objects like views, triggers, and foreign keys, which need to be updated manually. By following best practices such as transactional updates and stakeholder notifications, we can ensure a smooth renaming process without affecting database performance.



Next Article
PostgreSQL - ADD COLUMN

R

RajuKumar19
Improve
Article Tags :
  • Databases
  • PostgreSQL
  • postgreSQL-managing-table

Similar Reads

  • PostgreSQL - ADD COLUMN
    In PostgreSQL, the ADD COLUMN statement is a powerful command used to modify an existing database table by adding one or more new columns. This feature is important for adapting table structures to meet evolving data requirements, and it plays a key role in database management and optimization. In t
    5 min read
  • PostgreSQL - REPLACE() Function
    PostgreSQL REPLACE() function is a powerful tool for efficient string manipulation within our database. By utilizing the REPLACE() syntax in PostgreSQL, we can easily replace specific substrings within a string and enabling us to clean, format and modify data effectively. In this article, We will le
    4 min read
  • PostgreSQL - DROP COLUMN
    In PostgreSQL, there are instances where you might need to remove unnecessary or obsolete columns from your database tables. The DROP COLUMN clause in the ALTER TABLE statement allows you to do this with ease. When you drop a column from a table, PostgreSQL automatically removes any associated index
    2 min read
  • PostgreSQL - Rename Table
    Renaming a table in PostgreSQL is a common task that can be quickly done using the RENAME clause in combination with the ALTER TABLE statement. This article will walk you through the process of renaming an existing table in PostgreSQL, explaining the syntax, and providing a detailed example. SyntaxA
    2 min read
  • PostgreSQL - Change Column Type
    Changing the column type in PostgreSQL is good for adapting to increase the data needs. Using the ALTER TABLE statement, we can modify the structure of existing tables easily. The PostgreSQL ALTER COLUMN syntax allows us to change a columns data type while maintaining data integrity and performance.
    5 min read
  • PostgreSQL - Rename Database
    Renaming a PostgreSQL database is a simple yet essential task for developers and database administrators. Whether we're migrating data, restructuring our database, or just managing our server efficiently, the ability to rename a PostgreSQL database can streamline our workflow. In this article, we wi
    4 min read
  • PostgreSQL - TRIM Function
    The TRIM() function in PostgreSQL is an essential tool for removing unwanted characters from strings. Whether we're working with user inputs, formatting text, or performing data cleansing operations, TRIM() is an invaluable function for managing string data. This article will provide an in-depth loo
    4 min read
  • PostgreSQL REVERSE() Function
    The REVERSE() function in PostgreSQL is a simple yet powerful tool used to reverse the order of characters in a given string. It takes one input which is a string and returns the characters in reverse order. This function is helpful when you need to transform data, run tests or validate information.
    4 min read
  • PostgreSQL - Psql commands
    PostgreSQL, or Postgres, is an object-relational database management system that utilizes the SQL language. PSQL is a powerful interactive terminal for working with the PostgreSQL database. It enables users to execute queries efficiently and manage databases effectively. Here, we highlight some of t
    2 min read
  • PostgreSQL String Functions
    PostgreSQL is a powerful, open-source relational database management system that offers a rich set of functions and operators for working with string data. String manipulation is an essential task in many applications, and PostgreSQL provides a variety of built-in functions to make working with text
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences