Constant folding

However, there are many more optimizations in PostgreSQL that take place behind the scenes and that contribute to overall good performance. One of these features is called constant folding. The idea is to turn expressions into constants, as shown in the following example:

test=# explain SELECT * FROM a WHERE aid = 3 + 1;
QUERY PLAN
----------------------------------------------------------------
Index Only Scan using idx_a on a
(cost=0.57..4.58 rows=1 width=4)
Index Cond: (aid = 4)
(2 rows)

As you can see, PostgreSQL will try to look for 4. As aid is indexed, PostgreSQL will go for an index scan. Note that our table has just one column, so PostgreSQL even figured out that all the data it needs can be found in the index.

What happens if the expression is on the left-hand side?

test=# explain SELECT * FROM a WHERE aid - 1 = 3;
QUERY PLAN
------------------------------------------------------------
Seq Scan on a (cost=0.00..1942478.48 rows=500000 width=4)
Filter: ((aid - 1) = 3)
(2 rows)

In this case, the index lookup code will fail and PostgreSQL has to go for a sequential scan. Keep in mind that this is a single-core plan. If the size of the table is large or if your PostgreSQL configuration is different, you might see a multi-core plan. For the sake of simplicity, this chapter only contains single-core plans to make reading easier.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset