EN
Node.js - PostgreSQL - find rows where column is empty string (blank)
0 points
In this article, we would like to show you how to find 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.
xxxxxxxxxx
1
const { Client } = require('pg');
2
3
const client = new Client({
4
host: '127.0.0.1',
5
user: 'my_username',
6
database: 'my_database',
7
password: 'my_password',
8
port: 5432,
9
});
10
11
const findRows = async (text) => {
12
const query = `
13
SELECT *
14
FROM "users"
15
WHERE "email" = $1;
16
`;
17
await client.connect(); // creates connection
18
try {
19
const { rows } = await client.query(query, [text]); // sends query
20
return rows;
21
} finally {
22
await client.end(); // closes connection
23
}
24
};
25
26
findRows('') // empty string
27
.then(result => console.table(result))
28
.catch(error => console.error(error.stack));
Result:
xxxxxxxxxx
1
┌─────────┬────┬─────────────┬───────────┬───────┐
2
│ (index) │ id │ name │ surname │ email │
3
├─────────┼────┼─────────────┼───────────┼───────┤
4
│ 0 │ 2 │ 'Chris' │ 'Brown' │ '' │
5
│ 1 │ 3 │ 'Kate' │ 'Lewis' │ '' │
6
│ 2 │ 5 │ 'Gwendolyn' │ 'James' │ '' │
7
│ 3 │ 6 │ 'Simon' │ 'Collins' │ '' │
8
│ 4 │ 7 │ 'Taylor' │ 'Martin' │ '' │
9
└─────────┴────┴─────────────┴───────────┴───────┘
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL,
3
"name" VARCHAR(50) NOT NULL,
4
"surname" VARCHAR(50) NOT NULL,
5
"email" VARCHAR(50),
6
PRIMARY KEY ("id")
7
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "users"
2
( "name", "surname", "email")
3
VALUES
4
('John', 'Stewart', 'john@email.com'),
5
('Chris', 'Brown', ''),
6
('Kate', 'Lewis',''),
7
('Ailisa', 'Gomez', 'ailisa@email.com'),
8
('Gwendolyn', 'James', ''),
9
('Simon', 'Collins', ''),
10
('Taylor', 'Martin',''),
11
('Andrew', 'Thompson', 'andrew123@email.com');
Native SQL query (used in the above example):
xxxxxxxxxx
1
SELECT *
2
FROM "users"
3
WHERE "email" = $1;