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.
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));
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"