Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the execution plan of query in postgresql manually?

Is it possible to change the order of the operations of an execution plan manually in postgresql? E.g. if I always want to have the ordering operation before a filtering (although it doesn't make sense in a normal use of postgresql), is it possible to enforce that manually by e.g. changing the internal costs of an operation?

What about if I implement my own function? Is it possible to have such a function always being executed at the very end of the sql statement?

like image 687
navige Avatar asked Dec 26 '22 09:12

navige


1 Answers

Use a subquery or CTE to force certain operations first. Like:

SELECT *
FROM  (
   SELECT *
   FROM   tbl
   LIMIT  10
   ) x
ORDER  BY 1;

You need to understand what you are doing, of course. In the example, I select 10 arbitrary rows and then order them by the first column.
You can use multiple layers of subqueries or multiple CTEs in a row.

Same example as CTE:

WITH x AS (
   SELECT *
   FROM   tbl
   LIMIT  10
   )
SELECT *
FROM   x
ORDER  BY 1;

A subquery is usually faster for simple queries, a CTE offers additional features (like reusing the same CTE in multiple places on different query levels).

like image 142
Erwin Brandstetter Avatar answered Dec 29 '22 11:12

Erwin Brandstetter