Mathematical functions (ROUND, CEIL, FLOOR, ABS) in PostgreSQL - Time & Space Complexity
We want to understand how the time it takes to run mathematical functions changes as we use them on more data.
How does the work grow when applying functions like ROUND, CEIL, FLOOR, or ABS to many numbers?
Analyze the time complexity of the following code snippet.
SELECT
ROUND(price, 2) AS rounded_price,
CEILING(discount) AS ceil_discount,
FLOOR(tax) AS floor_tax,
ABS(balance) AS absolute_balance
FROM sales_data;
This code applies four mathematical functions to each row in the sales_data table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying each mathematical function to every row in the table.
- How many times: Once per row, repeated for all rows in sales_data.
Each row requires a fixed amount of work to compute these functions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 40 (4 functions x 10 rows) |
| 100 | 400 (4 functions x 100 rows) |
| 1000 | 4000 (4 functions x 1000 rows) |
Pattern observation: The total work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to run these functions grows in a straight line as the number of rows increases.
[X] Wrong: "Mathematical functions like ROUND or ABS take longer as the numbers get bigger."
[OK] Correct: These functions do a fixed amount of work per number regardless of its size, so the time depends only on how many numbers you process, not their values.
Understanding how simple functions scale with data size helps you explain query performance clearly and confidently.
"What if we applied these functions inside a nested query that runs multiple times? How would the time complexity change?"