PostgreSQL: Force on Planner to use Sequential Scan or Index Scan

Every day If you are doing performance optimization related stuff, sometime you also confuse on the decision of the Query Planner because It might be choose a wrong plan.

The SQL Server and MySQL provide features like: Index force or Index hint for SQL query, but PostgreSQL does not provide such feature because Once you set Index hint on the query, in future data is increasing and your Index hint might be not working accordingly.

Database Theory: Table Scan vs Index Scan vs Index Seek

In the PostgreSQL, Query Planner takes the decision base on the updated statistics and choose the Table Scan or Index Scan.

For smaller table, sequential scan is always faster compare to Index scanning. But sometimes what I have found is: due to invalid parameter PostgreSQL skips the indexes and start the table scanning which leads to poor performance.

In this situation, we should disable the Sequential Scan option so that Query Planner force to use available Indexes and execute the Query.

In PostgreSQL, We cannot enable / disable Index Scan or Table Scan at individual query level.

PostgreSQL provides two main parameters for Index Scan or Table Scan:
By default, this both parameters are ON, but as per the your requirement you can change the value.
You can find these parameters in postgresql.conf file.

enable_seqscan
enable_indexscan

You should never make the force on Query Planner because Forcing is a very bad idea. It might be useful to check if it will be faster, but production code should never use such tricks.

Anvesh Patel

Leave a Reply

1 Comment on "PostgreSQL: Force on Planner to use Sequential Scan or Index Scan"

Notify of
avatar
Sort by:   newest | oldest | most voted
Anand
Guest

can the Parallel Seq scan be used in sub-query.
I can see it only in normal queries.

wpDiscuz