Languages
[Edit]
EN

Node.js - PostgreSQL DROP TABLE IF EXISTS

0 points
Created by:
Jun-L
873

In this article, we would like to show you how to delete a table if it exists 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 deleteTable = async () => {
    try {
        await client.connect();                     // gets connection
        await client.query('DROP TABLE IF EXISTS "users"');  // sends queries
        return true;
    } catch (error) {
        console.error(error.stack);
        return false;
    } finally {
        await client.end();                         // closes connection
    }
};

deleteTable().then((result) => {
    if (result) {
        console.log('Table deleted');
    }
});
Postgres - DROP TABLE IF EXISTS result in HeidiSQL (before)
Postgres - DROP TABLE IF EXISTS result in HeidiSQL (before)
Postgres - DROP TABLE IF EXISTS result in HeidiSQL (after)
Postgres - DROP TABLE IF EXISTS result in HeidiSQL (after)

Database preparation

create_tables.sql file:

CREATE TABLE "users" (
	"id" SERIAL,
	"name" VARCHAR(100) NOT NULL,
	"role" VARCHAR(15) NOT NULL,
	PRIMARY KEY ("id")
);

Alternative titles

  1. Node.js - PostgreSQL DROP TABLE IF EXISTS with async/await
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

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