Why SQL databases recalculate the same thing over and over

Why SQL databases recalculate the same thing over and over

(A post for SQL beginners and daily users)

If you use SQL, you know queries like these:

SELECT customer_id, SUM(amount)
FROM orders
WHERE created_at >= '2025-01-01'
GROUP BY customer_id;

You write something like this every day.
For reports. Dashboards. APIs. Background jobs.

And every time you think:

“Why does this always take so long?”

The short answer:
Because the database calculates it from scratch every single time.


The real problem

Imagine you are asking your database:

“How much revenue did each customer generate this year?”

The next day:

“How much revenue did each customer generate this month?”

Later:

“How much revenue did customer 42 generate today?”

For you, these are all the same type of question.
For the database, they are completely new calculations.

It:

This is how most SQL databases work today.


“But aren't databases smart?”

Yes – but especially with:

With sums, counts, and groupingsit often applies:

“Recalculate everything.”

And that is exactly the problem.


What humans would do intuitively

A human would say:

“Wait – I already calculated that yesterday.
I'll remember the result and adjust it if new data is added.”

That is exactly what is called Aggregate Caching.

Or more simply:

Remember intermediate results instead of recalculating every time.


Why don't databases just do that?

Option 1: "Do it yourself"

Many systems say:

Problem:
👉 Normal developers don't want that.

Option 2: "We remember the result"

Some databases remember:

Problem:


The missing feature

What almost no open-source database can do today:

"I see that similar sums are being calculated here constantly."
I'll take care of it myself.

Without:


How it should feel ideal

You write normal SQL.

It's slow at the beginning.
Suddenly fast after a few queries.

You have:

The database simply learned:

“This calculation is worth remembering.”


Why that is hard

Because the database must decide for itself:

These are hard problems.
But they should not be developer problems be.


Conclusion

A normal SQL user should not have to know what:

are.

They should only notice:

"My queries get faster over time – all by themselves."

The fact that this behavior does not yet exist in open source databases like MySQL and PostgreSQL 30 years after the research of these techniques is actually sad.

That is why take a look at MemCP:

https://github.com/launix-de/memcp

Categorias