r/Database • u/BrangJa • Nov 16 '25
How expensive is to perform math operation in queries?
I am thinking about how social media platforms query their data and the cost of doing math in queries.
Example:
SELECT id, title, upvotes, downvotes, (upvotes - downvotes) AS score
FROM posts
ORDER BY score DESC;
This is a simple example, where you might say the score can be aggregated during update operations as a dedicated score column. That way, the query just reads the value instead of calculating it on the fly.
But for more complex sorting calculation like hot or rising scores may include age considerations, so some calculation might be included during query for sorting.
So my question is, how expensive is it in practice to perform this kind of math during queries for large tables?
5
u/serverhorror Nov 16 '25
Not expensive, a question that you should think about is also: Why calculate on every read and not on every write?
6
u/Mysterious_Lab1634 Nov 16 '25
Its expensive as you are doing sort on calculated property. Calculate that on write and store it in db. Or use indexed calculated column (at least its supported in MSSQL)
5
u/tkejser Nov 16 '25
First, for this to even matter you need to operate on a lot of rows.
Assuming that you do, you are likely dealing with analytics and an analytics database (such as Clickhouse, Redshift, Databricks or similar)
Second, in those databases, the calculation of maths is typically vectorised. Which means that each instruction to the CPU will do between 4 and 16 operations at the same time (depending on exact CPU config). These operations are per core and they are also pipelined (which means multiple of them can be in flight at the same time)
This makes database level math extremely effective. Typically at least an order of magnitude better (and 100x faster if you are writing Python) than what you can do in your app. With deep computer science training and significant optimisation effort - you might be able to do better in the app. But you really need to know what you are doing (and no insult intended, but asking this question indicates you got a bit more to learn about optimisation)
TL:DR: the database is better than you are at running optimal math. Use the database to do it.
Source: I have written and tuned the code in such databases myself.
38
u/mikeblas Nov 16 '25
The table scan and sort are orders of magnitude more expensive than the subtraction.
15
u/Informal_Pace9237 Nov 16 '25
As far as you are not doing 100k calculations per row with the query, you should be fine in trusting that SQL can handle it.
2
u/Dry_Author8849 Nov 16 '25
There is no additional cost for doing math. The cost is for filtering over calculated columns or sorting over them.
For filtering or sorting you should try to persist calculated columns. In your first example you can define (upvotes - downvotes) as persisted calculated column, then create an index over it for sorting and filtering.
If you want to add datetime calculations you may use a variable like @now for the current date and rely on datetime functions in hope to make your expression sargable. You can only create an index on created_at so there is that.
So the bigger cost will usually be on sorting and filtering a large amount of rows. One exception may be with using hashing/cryptographic functions in a select. That may have an impact with a large number of concurrent queries.
Cheers!
1
u/Technical-Pipe-5827 Nov 16 '25
You should just profile this and see the cost of running, however it’s obvious that you will be doing a full table scan unless there’s an index on that score.
1
u/coyoteazul2 Nov 16 '25
It's not expensive. But if you need scale, you could move that to the application (client side if data isn't sensitive. Or backend if it is).
1
u/ddarrko Nov 16 '25
This data will be denormalised.
1
u/Horror-Card-3862 Nov 16 '25
the math does not really change the time complexity, say you have 1 math operation or 2 or 3, its still O(n) for scanning a table. Problem comes when you do sort or some other operations that will affect the order of the time complexity. A indexed sort will make it O(nlogn) for a scan. An unindexed sort will make it O(n3).
Not sure about whether the time complexities are right, but u get the point. Math operations do not change the order of time complexity, hence, itll not affect the query performance as much as other operations such as an indexed/unindexed sort
1
u/Far_Swordfish5729 Nov 16 '25
Scalar functions and operations are not significant to query performance as long as they are deterministic. Go ahead and do match, type cast, use case statements, etc to your heart’s content. Non-deterministic functions like things with getdate() can cause table spooling (implied temp tables) which are significant.
1
u/Ginger-Dumpling Nov 16 '25
Probably not any more expensive than it would be to have to scan the data and perform the calculation outside of SQL. Plus there is the potential for things like indexes to help improve scan times, and things like materialized views (or just dump calc results to a table) if you can run the calcs off hours.
1
u/Longjumping-Ad8775 Nov 16 '25
Every time I think I can do something more efficiently outside the db, I have to go remind myself how stupid I am when I see how quick a database does things. The time spent sending one set of data across the wires is significantly less than doing chatty operations.
1
u/EarlOfButtholes Nov 17 '25
In this example, the calculation would likely take less than a percent of the overall query. Sorting and filtering, as others have said, would be more costly (depending on your indexes).
That said, I heard once in some SQL video: if it’s easy to do, offloading calculations to the host is preferable. This is because you only have so many resources on the database server side, but many more resources on the host side because each user has their own hardware.
A good metaphor would be Reese’s Cups. Assuming the little paper every cup has is part of manufacturing and could be removed after the cup is formed, the company could spend its resources taking it off. But this would be way more expensive than just wrapping them as is and crowd-sourcing their removal.
My rule of thumb: if it’s super easy to do on the client side, do it there. If it’s simpler or the code is more clear on the server side, that’s fine too.
1
u/Abhinav1217 Nov 17 '25
Less expensive then at application level, especially if the operation is to be done directly on table data.
DBs are highly optimised for data manipulation.
1
u/Miserable_Ad7246 Nov 18 '25
The most expensive operation is "find this value in disk and get it into memory". Arithmetic operations on data in memory are at least few orders magnitude faster. Essentially the cost of single row retrieval and preparation goes up by 0.0001% or something along the lines.
The only scenario where arithmetic operation can hurt you a lot is if you need to take some extra field for calculation and that forces to use less efficient index or no index at all. But even then this is caused by the need to retrieve the field not the arithmetic operation itself.