Languages
[Edit]
EN

Node.js - PostgreSQL Create a new table from the result set of a query

0 points
Created by:
Meredith-Soto
325

In this article, we would like to show you how to create a new table from the result set of a query using CREATE TABLE AS statement in the Postgres database from Node.js level.

Data used in the example - HeidiSQL
Data used in the example - 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 newTableFromQuery = async () => {
	const query = `    
            CREATE TABLE "users_without_email" AS 
                SELECT *    
                FROM "users"
                WHERE "email" IS NULL;
    `;
    await client.connect();  // creates connection
    try {
        await client.query(query);  // sends query
    } finally {
        await client.end();  // closes connection
    }
};

newTableFromQuery()
    .then(() => console.table('New table created!'))
    .catch(error => console.error(error.stack));

Result: 

Postgres - Table "users_without_email" created from the query - HeidiSQL
Table "users_without_email" created from the query - HeidiSQL

Database preparation

create_tables.sql file:

CREATE TABLE "users" (
	"id" SERIAL,
	"name" VARCHAR(50) NOT NULL,
	"surname" VARCHAR(50) NOT NULL,
	"email" VARCHAR(100),
	"department_id" INTEGER,
	"salary" DECIMAL(15,2) NOT NULL,
	PRIMARY KEY ("iusers_without_emaild")
);

insert_data.sql file:

INSERT INTO "users"
	( "name", "surname", "email", "department_id", "salary")
VALUES
	('John', 'Stewart', 'john@email.com', 1, '3512.00'),
	('Chris', 'Brown', 'chris@email.com', 2, '1344.00'),
	('Kate', 'Lewis', NULL, 3, '6574.00'),
	('Ailisa', 'Gomez', 'ailisa@email.com', 2, '6500.00'),
	('Gwendolyn', 'James', NULL, NULL, '4200.00'),
	('Simon', 'Collins', NULL, 4, '3320.00'),
	('Taylor', 'Martin', NULL, NULL, '1500.00'),
	('Andrew', 'Thompson', 'andrew@email.com', NULL, '2100.00');

Native SQL query (used in the above example):

CREATE TABLE "users_without_email1" AS 
    SELECT *    
    FROM "users"
    WHERE "email" IS NULL;

Alternative titles

  1. Node.js - PostgreSQL Define a new table from the results of a query
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