EN
Node.js - PostgreSQL Insert data from one table to another
0
points
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.
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:
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";