EN
Node.js - PostgreSQL - delete row where column is null
0
points
In this article, we would like to show you how to delete a row where the column is null in the PostgreSQL database using Node.js.
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: 'postgres',
database: 'database_name',
password: 'password',
port: 5432,
});
const deleteRowsIfNullEmail = async () => {
const query = `DELETE FROM "users" WHERE "email" IS NULL;`;
try {
await client.connect(); // creates connection
await client.query(query); // sends query
} catch (error) {
console.error(error.stack);
} finally {
await client.end(); // closes connection
}
};
deleteRowsIfNullEmail();
Result:
Database preparation
create_tables.sql
file:
CREATE TABLE "users" (
"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", "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', 'andrew123@email.com');