Languages
[Edit]
EN

Node.js - PostgreSQL - find rows where column is empty string (blank)

0 points
Created by:
Dirask Admin - MR
1340

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.

Node.js - PostgreSQL - find row where column is empty string (blank)
Data used in the example - HeidiSQL

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: 'my_username',
    database: 'my_database',
    password: 'my_password',
    port: 5432,
});

const findRows = async (text) => {
	const query = `
            SELECT * 
            FROM "users" 
            WHERE "email" = $1;
    `;
    await client.connect();  // creates connection
    try {
        const { rows } =  await client.query(query, [text]);  // sends query
        return rows;
    } finally {
        await client.end();  // closes connection
    }
};

findRows('')  // empty string 
    .then(result => console.table(result))
    .catch(error => console.error(error.stack));

Result: 

┌─────────┬────┬─────────────┬───────────┬───────┐
│ (index) │ id │    name     │  surname  │ email │
├─────────┼────┼─────────────┼───────────┼───────┤
│    0    │ 2  │   'Chris'   │  'Brown'  │  ''   │
│    1    │ 3  │   'Kate'    │  'Lewis'  │  ''   │
│    2    │ 5  │ 'Gwendolyn' │  'James'  │  ''   │
│    3    │ 6  │   'Simon'   │ 'Collins' │  ''   │
│    4    │ 7  │  'Taylor'   │ 'Martin'  │  ''   │
└─────────┴────┴─────────────┴───────────┴───────┘

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');

Native SQL query (used in the above example):

SELECT * 
FROM "users" 
WHERE "email" = $1;
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