Languages
[Edit]
EN

Node.js - PostgreSQL Insert data from one table to another

0 points
Created by:
Mariam-Barron
811

In this article, we would like to show you how to insert data from one table to another in the Postgres database from Node.js level.

Node.js - PostgreSQL Insert data from one table to another
target table - "users" - HeidiSQL
Node.js - PostgreSQL Insert data from one table to another
source table - "members" - 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 moveFromMembersToUsers = async () => {
	const query = `    
            INSERT INTO "users" ("name", "email", "country")
            SELECT "name", "email", ''
            FROM "members";
    `;
    await client.connect();  // creates connection
    try {
        await client.query(query);  // sends query
    } finally {
        await client.end();  // closes connection
    }
};

moveFromMembersToUsers()
    .then(() => console.log('Rows moved!'))
    .catch(error => console.error(error.stack));

Result: 

users table after query execution - HeidiSQL

Database preparation

create_tables.sql file:

CREATE TABLE "users" (
	"id" SERIAL,
	"name" VARCHAR(100),
	"email" VARCHAR(100),
	"country" VARCHAR(15),
	PRIMARY KEY ("id")
);

CREATE TABLE "members" (
	"id" SERIAL,
	"name" VARCHAR(50) NOT NULL,
	"surname" VARCHAR(50) NOT NULL,
	"email" VARCHAR(50),
	PRIMARY KEY ("id")
);

insert_data.sql file:

INSERT INTO "users"
    ("name", "email", "country")
VALUES
    ('Tom', 'tom@email.com', 'Poland'),
    ('Chris', 'chris@email.com', 'Spain'),
    ('Jack', 'jack@email.com', 'Spain'),
    ('Kim', 'kim@email.com', 'Vietnam'),
    ('Marco', 'marco@email.com', 'Italy'),
    ('Kate', 'kate@email.com', 'Spain'),
    ('Nam', 'nam@email.com', 'Vietnam');

INSERT INTO "members"
	( "name", "surname", "email")
VALUES
	('John', 'Stewart', 'john@email.com'),
	('Chris', 'Brown', NULL),
	('Kate', 'Lewis', NULL),
	('Ailisa', 'Gomez', 'ailisa@email.com'),
	('Gwendolyn', 'James', NULL),
	('Simon', 'Collins', NULL),
	('Taylor', 'Martin', NULL),
	('Andrew', 'Thompson', 'andrew@email.com');

Native SQL query (used in the above example):

INSERT INTO "users" ("name", "email", "country")
SELECT "name", "email", ''
FROM "members";
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - PostgreSQL - Problems

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