Languages

Node.js - Postgres - how to change column datatype?

0 points
Asked by:
a_horse
208

Hey, how can I change the data type in the "salary" column from DECIMAL to VARCHAR in this table:

Postgres - ALTER TABLE result in HeidiSQL (before)

1 answer
0 points
Answered by:
a_horse
208

I found a solution:

we must use ALTER TABLE statement as follows:

ALTER TABLE table_name
ALTER COLUMN column_name TYPE new_data_type;

in this case, it will be:

ALTER TABLE "users"
ALTER COLUMN "salary" TYPE VARCHAR

Practical example in Node.js:

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

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

const changeColumnType = async () => {
	const query = `ALTER TABLE "users"
                   ALTER COLUMN "salary" TYPE VARCHAR;`;
    try {
        await client.connect();    // gets connection
        await client.query(query); // sends query
    } catch (error) {
        console.error(error.stack);
    } finally {
        await client.end();        // closes connection
    }
};

changeColumnType(); 

For better understanding, I also made an article:

0 comments Add comment
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