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
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.
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
- Has a Plate Been Seen Easy Pro Ask the database for existence so it stops at the first indexed hit instead of reading every row.
- Accounts With Clean Books Medium Pro Combine a nonempty guard with universal quantification, so every order must reconcile without loading the account graph.
- Count Active Devices Medium Pro Collapse a per-device existence probe into one server-side count under a memory cap.
- Is a Username Taken Medium Pro A signup availability check that reads every account to answer one yes/no question.