Skip to content
Katabench
Try free

Existence Without Loading

Easy About 10 min Free, no account needed

Answer a yes/no existence question by asking the database, not by loading the rows to count them.

The brief

Implement HasOrders(db, region): return true if any device in the given region has recorded at least one measurement, and false otherwise.

It is a yes/no question, but the starter answers it by pulling every matching measurement back to the application and checking whether the list is non-empty. On the hidden dataset of hundreds of thousands of measurements that transfers far more data than the single bit of information you actually need, and it times out.

Ask the database the existence question directly, so it can stop as soon as it finds the first matching row and hand back only the answer.

This puzzle runs against a real, throwaway PostgreSQL database created just for your submission and destroyed afterwards.

Starter code

C#
using System.Linq;
using CodeRunner.PuzzleSchemas;

public class Solution
{
    // Answers the existence question by loading every matching measurement and checking the count. Correct,
    // but it transfers the whole result set just to learn whether it is empty.
    public bool HasOrders(IotDbContext db, string region)
    {
        var measurements = db.Measurements.Where(o => o.Device.Region == region).ToList();
        return measurements.Count > 0;
    }
}

How it is graded

Your LINQ or SQL runs against real PostgreSQL. You see the SQL your code generates on the sample tests, so you learn when the database did the wrong work.

EF Core practice →

Related guides

What it practices

Semi-joins and anti-joins
Ask existence questions with EXISTS, NOT EXISTS or Any instead of loading or counting rows.
Server-side filtering
Filter, count and sort in the database instead of in application memory.

Related katas