问题
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?
回答1:
There are more ways - some was showed here, but there are second way, if you would to move function call on end of processing, then just set COST to some higher value. Default for custom functions is 100, but you can set higher value.
CREATE OR REPLACE FUNCTION public.test()
RETURNS integer
LANGUAGE plpgsql
IMMUTABLE COST 1000 -- very expensive function
AS $function$
declare i int;
declare j int;
begin
i := 1;
while i < 10000 loop
j := 1;
while j < 1000 loop
j := j + 1;
end loop;
i := i + 1;
end loop;
return i;
end;
$function$
回答2:
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).
回答3:
About the best you can do without CTEs (which others have explained) is to turn off certain types of operations. This is generally considered dangerous and a method of last resort since it usually points to bugs either in your database (i.e. lacking indexes, not vacuuming enough, too low analyse sampling) or in PostgreSQL code.
But if you want to try it, look up "enable_seqscan" and other settings, see e.g. PostgreSQL documentation.
来源:https://stackoverflow.com/questions/14982120/change-the-execution-plan-of-query-in-postgresql-manually