Filter Before You Fetch
Easy About 8 min Free, no account needed
Filter measurements on the database, not after loading the whole table.
The brief
Return the Ids (ascending) of all measurements whose Value is at least
threshold. The starter loads the entire measurements table into memory and filters
in C#; push the Where to the database so only the matching rows come back.
The hidden test runs against tens of thousands of measurements under a tight time limit, materializing the whole table will not finish.
Starter code
using System.Collections.Generic;
using System.Linq;
using CodeRunner.PuzzleSchemas;
public class Solution
{
// Loads every measurement, then filters in memory.
public List<int> BigOrders(IotDbContext db, decimal threshold)
{
return db.Measurements
.ToList()
.Where(o => o.Value >= threshold)
.OrderBy(o => o.Id)
.Select(o => o.Id)
.ToList();
}
}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
- Server-side filtering
- Filter, count and sort in the database instead of in application memory.
Related katas
- Existence Without Loading Easy Free Answer a yes/no existence question by asking the database, not by loading the rows to count them.
- Dishes per Cuisine Easy Pro Count how many dishes sit in each cuisine with one grouped query.
- Latest Messages in a Channel Easy Pro One composite index can serve a filter and a sort at once: no separate sort step.
- Invoices by Number Easy Pro Support pastes in nine invoice numbers. Finding them reads sixty thousand rows today, and two hundred thousand next year.