A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgres-rename-column.php below:

Website Navigation


PostgreSQL Rename Column: Syntax and Practical Example Guide

PostgreSQL Rename Column: Syntax and Practical Example GuideLast update on December 31 2024 05:34:26 (UTC/GMT +8 hours)

How to Rename a Column in PostgreSQL

Renaming a column in a PostgreSQL database is a straightforward process that allows developers to adjust table schemas without affecting existing data. This operation can be performed using the ALTER TABLE command with the RENAME COLUMN clause.

This guide provides the syntax, an example, and detailed explanation of how to rename a column in PostgreSQL.

Syntax:

ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name;

Example

Let’s rename a column named username to user_name in a table called users.

Code:


-- Alter the table 'users' to rename the column 'username' to 'user_name'
ALTER TABLE users RENAME COLUMN username TO user_name;

Explanation:

Practical Example

Initial Table Setup

Create a users table with a column named username:

Code:

-- Create the 'users' table with an initial 'username' column
CREATE TABLE users (
    id SERIAL PRIMARY KEY,       -- Primary key for the table
    username VARCHAR(50) NOT NULL, -- Username column
    email VARCHAR(100) NOT NULL   -- Email column
);

Inserting Data

Code:

-- Insert sample data into the 'users' table
INSERT INTO users (username, email) VALUES
('jana_isabel', '[email protected]'),
('david_isabel', '[email protected]');

Renaming the Column

Code:

-- Rename the column 'username' to 'user_name'
ALTER TABLE users RENAME COLUMN username TO user_name;

Verifying the Change

Code:

-- Check the table structure to confirm the column name change
\d users

The result shows the column name username is now user_name.

Explanation

Best Practices

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4