Languages
[Edit]
EN

Node.js - PostgreSQL RENAME COLUMN (ALTER TABLE)

6 points
Created by:
Dirask Admin - Marvin
1850

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"

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