Languages
[Edit]
EN

Node.js - PostgreSQL RENAME COLUMN (ALTER TABLE)

6 points
Created by:
Majid-Hajibaba
972

In this article, we would like to show you how to rename single column located inside existing table in the Postgres database from Node.js level. In the example we use ALTER TABLE statement.

Node.js - PostgreSQL ALTER TABLE - RENAME COLUMN
Table used in the example - HeidiSQL

Note: at the end of this article you can find database preparation SQL queries.

const { Client } = require('pg');

const client = new Client({
    host: '127.0.0.1',
    user: 'my_username',
    database: 'my_database',
    password: 'my_password',
    port: 5432,
});

const renameColumn = async () => {
	const query = `
            ALTER TABLE "users"
            RENAME COLUMN "salary" TO "earnings";
    `;
    await client.connect();        // creates connection
    try {
        await client.query(query); // sends query
    } finally {
        await client.end();        // closes connection
    }
};

renameColumn()
    .then(() => console.log('Column renamed!'))
    .catch(error => console.error(error.stack));
Postgres - ALTER TABLE result in HeidiSQL (before)
Postgres - ALTER TABLE results in HeidiSQL (before)
Postgres - ALTER TABLE result in HeidiSQL (after)
Postgres - ALTER TABLE results in HeidiSQL (after)

Database preparation

create_tables.sql file:

CREATE TABLE "users" (
	"id" SERIAL,
	"name" VARCHAR(50) NOT NULL,
	"surname" VARCHAR(50) NOT NULL,
	"department_id" INTEGER,
    "salary" DECIMAL(15,2) NOT NULL,
	PRIMARY KEY ("id")
);

Native SQL query (used in the above example):

ALTER TABLE "users"
RENAME COLUMN "salary" TO "earnings"

Alternative titles

  1. Node.js - PostgreSQL - How to rename existing column
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - PostgreSQL

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join