PostgreSQL: how can queries possibly be “immutable” / functional

postgresql

I've read that PostgreSQL can have "functional" indexes. For that you need the immutable keyword.

Seen that PostgreSQL is a CRUD DB I don't understand at all how it can possibly work in a functional way.

If there's an update or a delete to the DB, how can a past query guarantee that the result of the same query is always going to be the same?

Best Answer

I think you are getting confused with functional programming languages.

Anyway, a functional index is used to speed up access to data where queries that are accessing the data are using database functions.

By way of example, a query such as select blah from foo where sqrt(blah)=4 would have to perform the sqrt() operation for each value of blah. You could optimise this by pre-calculating all values of sqrt(blah) in a functional index: create index foo_func on foo (sqrt(blah));

This is where immutability comes in. A function is immutable if and only if the same input will always give the same output. Functional indexes can only use immutable functions. This guarantees that any queries for a given value and related functional index value will always return the same result.