EN
Node.js - PostgreSQL RENAME COLUMN (ALTER TABLE)
6 points
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.

Note: at the end of this article you can find database preparation SQL queries.
xxxxxxxxxx
1
const { Client } = require('pg');
2
3
const client = new Client({
4
host: '127.0.0.1',
5
user: 'my_username',
6
database: 'my_database',
7
password: 'my_password',
8
port: 5432,
9
});
10
11
const renameColumn = async () => {
12
const query = `
13
ALTER TABLE "users"
14
RENAME COLUMN "salary" TO "earnings";
15
`;
16
await client.connect(); // creates connection
17
try {
18
await client.query(query); // sends query
19
} finally {
20
await client.end(); // closes connection
21
}
22
};
23
24
renameColumn()
25
.then(() => console.log('Column renamed!'))
26
.catch(error => console.error(error.stack));


create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL,
3
"name" VARCHAR(50) NOT NULL,
4
"surname" VARCHAR(50) NOT NULL,
5
"department_id" INTEGER,
6
"salary" DECIMAL(15,2) NOT NULL,
7
PRIMARY KEY ("id")
8
);
Native SQL query (used in the above example):
xxxxxxxxxx
1
ALTER TABLE "users"
2
RENAME COLUMN "salary" TO "earnings"