Languages
[Edit]
EN

Node.js - PostgreSQL RENAME COLUMN (ALTER TABLE)

6 points
Created by:
Dirask Admin - MR
1340

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