Path extraction with #> and #>> in PostgreSQL - Time & Space Complexity
We want to understand how the time to extract data from JSON grows as the JSON gets bigger.
Specifically, how does using #> and #>> operators affect performance when accessing nested data?
Analyze the time complexity of the following PostgreSQL JSON path extraction queries.
SELECT data #> '{a,b,c}' AS value1 FROM json_table;
SELECT data #>> '{a,b,c}' AS value2 FROM json_table;
These queries extract nested values from a JSON column using path operators.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing the JSON structure along the given path keys.
- How many times: Once per row, and once per key in the path (each key leads to next nested level).
The time grows with the length of the path and the size of the JSON at each level.
| Input Size (path length n) | Approx. Operations |
|---|---|
| 3 | 3 steps to reach nested value |
| 5 | 5 steps to reach nested value |
| 10 | 10 steps to reach nested value |
Pattern observation: The number of steps grows linearly with the path length.
Time Complexity: O(n)
This means the time to extract a value grows linearly with the number of keys in the path.
[X] Wrong: "Extracting a nested JSON value is always constant time regardless of path length."
[OK] Correct: Each key in the path requires looking inside the JSON at that level, so longer paths take more steps.
Understanding how JSON path extraction scales helps you write efficient queries and explain performance trade-offs clearly.
What if the JSON data is deeply nested but the path length is short? How would the time complexity change?