Decimal and floating-point types in MySQL - Time & Space Complexity
When working with decimal and floating-point types in MySQL, it is important to understand how operations on these types scale as data grows.
We want to know how the time to process these numbers changes when we handle more rows or bigger numbers.
Analyze the time complexity of the following SQL query using decimal and floating-point columns.
SELECT AVG(price) AS avg_price
FROM products
WHERE price > 100.00;
This query calculates the average price of products where the price is greater than 100.00, using decimal or floating-point values.
Look for repeated steps in the query execution.
- Primary operation: Scanning each row in the products table to check the price condition and include it in the average calculation.
- How many times: Once for every row in the table.
As the number of rows increases, the database must check more prices and add more values to the average.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks and additions |
| 100 | 100 checks and additions |
| 1000 | 1000 checks and additions |
Pattern observation: The work grows directly with the number of rows; doubling rows doubles the work.
Time Complexity: O(n)
This means the time to compute the average grows in a straight line as the number of rows increases.
[X] Wrong: "Calculations on decimal or floating-point types take longer time per row, so the overall time grows faster than the number of rows."
[OK] Correct: Each calculation takes a small, fixed amount of time, so the total time still grows linearly with the number of rows, not faster.
Understanding how numeric data types affect query time helps you explain performance clearly and shows you know how databases handle data at scale.
What if we added an index on the price column? How would the time complexity change?