EN
Node.js - PostgreSQL Create table if not exists
0 points
In this article, we would like to show you how to create a table only if it doesn't exist in Node.js.
xxxxxxxxxx
1
const { Client } = require('pg');
2
3
const client = new Client({
4
host: '127.0.0.1',
5
user: 'postgres',
6
database: 'database_name',
7
password: 'password',
8
port: 5432,
9
});
10
11
const execute = async (query) => {
12
try {
13
await client.connect(); // gets connection
14
await client.query(query); // sends queries
15
return true;
16
} catch (error) {
17
console.error(error.stack);
18
return false;
19
} finally {
20
await client.end(); // closes connection
21
}
22
};
23
24
const text = `
25
CREATE TABLE IF NOT EXISTS "users" (
26
"id" SERIAL,
27
"name" VARCHAR(100) NOT NULL,
28
"role" VARCHAR(15) NOT NULL,
29
PRIMARY KEY ("id")
30
);`;
31
32
execute(text).then(result => {
33
if (result) {
34
console.log('Table created');
35
}
36
});
Database:

Native SQL query (used in the above example):
xxxxxxxxxx
1
CREATE TABLE IF NOT EXISTS"users" (
2
"id" SERIAL,
3
"name" VARCHAR(100) NOT NULL,
4
"role" VARCHAR(15) NOT NULL,
5
PRIMARY KEY ("id")
6
);
Note:
To create a multi-line string, create a
template literal
usingbackticks
``
.