Explain Codes LogoExplain Codes Logo

How can I have IS NULL condition in TypeORM find options?

javascript
typeorm
find-options
null-checks
Anton ShumikhinbyAnton Shumikhin·Nov 24, 2024
TLDR

Use IsNull in TypeORM to filter records with NULL values:

import { IsNull } from 'typeorm'; const result = await repository.find({ where: { columnName: IsNull() } });

This code will fetch rows where columnName is NULL. Make sure to replace columnName with your actual field name.

Handle NOT NULL like a boss

Now, let's keep it simple, when reverse care is needed i.e., you want to exclude any NULL records, use combination of Not with IsNull:

import { Not, IsNull } from 'typeorm'; // Because we're contrary like that, we want columns that are NOT NULL. const nonNullResults = await repository.find({ where: { columnName: Not(IsNull()) } });

Voila! You've just got records where columnName is definitely not taking a null-day off!

Flexing QueryBuilder muscles

For more complex queries, come on board with QueryBuilder. Using QueryBuilder for NULL checks is pretty straightforward:

const queryBuilderResult = await repository .createQueryBuilder("user") .where("user.columnName IS NULL") // Yeah, we're talking to you NULL value! .getMany();

And for the exact opposite, just be rebellious with a NOT in the right place:

const queryBuilderNonNullResult = await repository .createQueryBuilder("user") .where("user.columnName IS NOT NULL") // NULL, *NOT* today! .getMany();

Keep QueryBuilder for the heavyweight rounds, don't burn it out with lighter weights!

Going deeper with IS NULL checks

It's time for some coaching. SQL's manner of handling null comparison is... messy! This fella doesn't play by rules. If you try direct null comparisons in SQL, you'll hit a brick wall:

SELECT * FROM users WHERE name = NULL; // Spoilers: it won't work!

Never fear, IsNull() comes to rescue. This champ eases your job and establishes the IS NULL condition in the type-safe way, serving as TypeORM's FindOperatorType:

import { FindOperatorType } from 'typeorm'; // Subtle secret spread: "isNull" as a FindOperatorType. Shhhh!

Secure your coding seatbelts! No more bumpy rides with incorrect SQL syntax.

Yes, there can be a void!

In programming, dealing with null is like trying to hear a dog whistle. Especially when we're dabbling in logical operations.

Utilizing IsNull and Not(IsNull()) correctly in TypeORM lets you gently maneuver these empty values in your data design and queries. Your app runs, your logic shines - a win-win!