TypeORM: Selecting Rows with Null Values

Updated: May 2, 2022 By: A Goodman Post a comment

This succinct article is for people working with TypeORM who want to select records containing Null values. We’ll examine two examples. The first one uses the find() method, and the second uses Query Builder.

Here’s the sample entity named User that will appear in both examples:

// User entity
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column({ nullable: true })
    address: string;
}

Using find() method

This code snippet finds all users whose addresses are null:

import { IsNull } from "typeorm";
import { User } from './entities/User'
import { dataSource } from './my-data-source'

const getUsers = async () => {
    const userRepository = dataSource.getRepository(User);
    const results = await userRepository.find({
        where: {
            address: IsNull()
        }
    })
}

Using Query Builder

This code finds all users whose addresses are null with query builder:

import {dataSource } from "./my-data-source";
import { User } from './entities/User'

const getUsers = async () => {
    const userRepository = dataSource.getRepository(User);
    const users = await userRepository
        .createQueryBuilder('user')
        .where('user.address IS NULL')
        .getMany();

    // Do something with users
}

Conclusion

We’ve walked through a couple of examples about finding rows where a column is null. If you’d like to explore more new and exciting stuff about TypeORM and the backend development world, take a look at the following articles:

You can also check out our database topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles