EN
Node.js - PostgreSQL - delete row where column is empty string (blank)
0
points
In this article, we would like to show you how to delete a row where the column is an empty string 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 deleteRows = async (text) => {
const query = `DELETE FROM "users" WHERE "email" = $1;`;
try {
await client.connect(); // creates connection
await client.query(query, [text]); // sends query
} catch (error) {
console.error(error.stack);
} finally {
await client.end(); // closes connection
}
};
deleteRows(''); // delete row where column is empty string ''
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', ''),
('Kate', 'Lewis',''),
('Ailisa', 'Gomez', 'ailisa@email.com'),
('Gwendolyn', 'James', ''),
('Simon', 'Collins', ''),
('Taylor', 'Martin',''),
('Andrew', 'Thompson', 'andrew123@email.com');