Numeric and decimal precision in PostgreSQL - Time & Space Complexity
When working with numbers in a database, the precision of numeric and decimal types affects how calculations are done.
We want to understand how the time to process these numbers changes as their size or precision grows.
Analyze the time complexity of the following SQL snippet that sums decimal numbers with precision.
SELECT SUM(price)
FROM products
WHERE price > 0;
This query adds up all positive prices stored as numeric or decimal values.
Look for repeated actions that affect time.
- Primary operation: Adding each price value one by one.
- How many times: Once for every row with a positive price.
As the number of rows increases, the total additions increase too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to sum prices grows in a straight line as the number of prices increases.
[X] Wrong: "Adding numbers with more decimal places takes longer time per addition."
[OK] Correct: While precision affects storage, the addition operation time is mostly affected by how many numbers are added, not their decimal length.
Understanding how numeric precision impacts query time helps you explain performance in real projects where money or measurements matter.
"What if we changed the query to multiply prices instead of summing? How would the time complexity change?"