Where clause filtering in C Sharp (C#) - Time & Space Complexity
When we use a WHERE clause to filter data, we want to know how long it takes as the data grows.
We ask: How does filtering time change when there are more rows to check?
Analyze the time complexity of the following code snippet.
// Simulate filtering rows with a WHERE clause
List<int> FilterData(List<int> data, int threshold) {
var result = new List<int>();
foreach (var item in data) {
if (item > threshold) {
result.Add(item);
}
}
return result;
}
This code checks each item in a list and keeps only those greater than a threshold.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list once.
- How many times: Exactly once for every item in the input list.
As the list gets bigger, the code checks more items one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of checks grows directly with the number of items.
Time Complexity: O(n)
This means the time to filter grows in a straight line as the data size grows.
[X] Wrong: "Filtering with a WHERE clause is instant no matter how big the data is."
[OK] Correct: The code must check each item to decide if it matches, so more data means more work.
Understanding how filtering scales helps you explain how queries behave with growing data, a useful skill in many jobs.
"What if the data was already sorted and we stopped checking after the first item that failed the condition? How would the time complexity change?"