H.4. pg_hint_plan — управление планом выполнения с указаниями #
H.4.1. Описание #
pg_hint_plan — модуль, позволяющий управлять планом выполнения с указаниями, записываемыми в комментариях особого вида.
В Postgres Pro Enterprise используется оптимизатор запросов, учитывающий стоимость их выполнения. При этом он использует статистику данных, а не жёсткие правила. Планировщик (оптимизатор) оценивает стоимость всех возможных планов выполнения оператора SQL, и в итоге выбирает для выполнения план с наименьшей стоимостью. Планировщик делает всё возможное, чтобы выбрать лучший план выполнения, но он не идеален, так как не учитывает некоторые свойства данных, например корреляции между столбцами.
Модуль pg_hint_plan позволяет корректировать планы выполнения, применяя так называемые «указания», записываемые в виде простых описаний в SQL-комментариях особого вида.
H.4.2. Обзор #
H.4.2.1. Базовое использование #
Модуль pg_hint_plan считывает фразы-указания в комментариях особого вида, записанных в теле целевого оператора SQL. Эта особая запись начинается с последовательности символов /*+ и заканчивается последовательностью */. Фразы указаний состоят из имени указания и последующих параметров, которые заключаются в скобки и разделяются пробельными символами. Такие указания могут размещаться в нескольких строках для улучшения читаемости.
В следующем примере в качестве метода соединения выбирается соединение по хешу, а pgbench_accounts сканируется последовательным способом.
/*+
HashJoin(a b)
SeqScan(a)
*/
EXPLAIN SELECT *
FROM pgbench_branches b
JOIN pgbench_accounts a ON b.bid = a.bid
ORDER BY a.aid;
QUERY PLAN
---------------------------------------------------------------------------------------
Sort (cost=31465.84..31715.84 rows=100000 width=197)
Sort Key: a.aid
-> Hash Join (cost=1.02..4016.02 rows=100000 width=197)
Hash Cond: (a.bid = b.bid)
-> Seq Scan on pgbench_accounts a (cost=0.00..2640.00 rows=100000 width=97)
-> Hash (cost=1.01..1.01 rows=1 width=100)
-> Seq Scan on pgbench_branches b (cost=0.00..1.01 rows=1 width=100)
(7 rows)H.4.3. Таблица указаний #
В предыдущем разделе говорилось, что указания задаются в комментариях особого вида. Однако это неудобно, когда нет возможности редактировать запросы. В таких случаях указания можно внести в специальную таблицу hint_plan.hints. Эта таблица содержит следующие столбцы:
| Столбец | Описание |
|---|---|
| id | Уникальный номер строки с указанием. Этот столбец заполняется автоматически генератором последовательности. |
| query_id | Уникальный идентификатор запроса, генерируемый обслуживающим процессом при включённом параметре конфигурации compute_query_id. |
| application_name | Значение переменной application_name (имя приложения), выбирающее сеансы, в которых будет действовать указание. В приведённом примере указание будет действовать на сеансы, установленные приложением psql. С пустой строкой будут выбираться сеансы с любым значением application_name. |
| hint | Фраза указания. Это поле должно содержать указания без обрамляющей разметки комментариев. |
Следующий пример показывает, как манипулировать указаниями в таблице.
=# EXPLAIN (VERBOSE, COSTS false) SELECT * FROM t1 WHERE t1.id = 1;
QUERY PLAN
----------------------------------------
Seq Scan on public.t1
Output: id, id2
Filter: (t1.id = 1)
Query Identifier: -7164653396197960701
(4 rows)
=# INSERT INTO hint_plan.hints(query_id, application_name, hints)
VALUES (-7164653396197960701, '', 'SeqScan(t1)');
INSERT 0 1
UPDATE hint_plan.hints
SET hints = 'IndexScan(t1)'
WHERE id = 1;
UPDATE 1
DELETE FROM hint_plan.hints
WHERE id = 1;
DELETE 1Таблица указаний принадлежит пользователю, создавшему расширение, и для неё назначаются права доступа, установленные по умолчанию в момент выполнения команды CREATE EXTENSION. Указания, заданные в таблице, имеют больший приоритет, чем указания в комментариях.
Идентификатор запроса можно узнать с помощью модуля pg_stat_statements или команды EXPLAIN VERBOSE.
H.4.3.1. Типы указаний #
Фразы указаний подразделяются на несколько типов по видам объектов, на которые они могут воздействовать, и их влиянию на планировщик. Списки фраз указаний для каждого типа приведены в Подразделе H.4.9.
H.4.3.1.1. Указания для методов сканирования #
Указания для методов сканирования принудительно устанавливают метод сканирования для заданной таблицы. В качестве имени целевой таблицы обработчик pg_hint_plan может распознать и её псевдоним, если он определён. К таким указаниям относятся, например, SeqScan или IndexScan.
Такие указания работают с обычными таблицами, таблицами с наследованием, нежурналируемыми таблицами, временными таблицами и системными каталогами. Они не применяются к внешним (сторонним) таблицам, табличным функциям, результатам VALUES, CTE, представлениям и вложенным запросам.
/*+
SeqScan(t1)
IndexScan(t2 t2_pkey)
*/
SELECT * FROM table1 t1 JOIN table table2 t2 ON (t1.key = t2.key);H.4.3.1.2. Указания для методов соединения #
Указания для методов соединения принудительно выбирают определённый метод для соединения заданных таблиц.
Эти указания могут работать только с обычными таблицами. Таблицы с наследованием, нежурналируемые и временные таблицы, внешние (сторонние) таблицы, системные каталоги, табличные функции, результаты команд VALUES и CTE могут быть добавлены в список параметров. Однако на представления и подзапросы они не воздействуют.
Указания для методов соединения рекомендуется использовать вместе с указанием для порядка соединения Leading, так как оно гарантирует применение порядка, указанного в запросе.
В запросе с указанием ниже будет применена структура соединения NestLoop(MergeJoin(c b) a):
/*+ Leading(((c b) a)) MergeJoin(c b) NestLoop(a b c) */ EXPLAIN(COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM t1 a, t1 b, t1 c WHERE a.f1 = b.f1 AND b.f1 = c.f1;
QUERY PLAN
---------------------------------------------------------------
Aggregate
-> Nested Loop
-> Merge Join
Merge Cond: (c.f1 = b.f1)
-> Index Only Scan using t1_idx1 on t1 c
-> Materialize
-> Index Only Scan using t1_idx1 on t1 b
-> Memoize
Cache Key: b.f1
Cache Mode: logical
-> Index Only Scan using t1_idx1 on t1 a
Index Cond: (f1 = b.f1)H.4.3.1.3. Указание для порядка соединения #
Указание Leading устанавливает порядок соединения двух и более таблиц. Выбрать порядок можно двумя способами. Первый вариант — установить определённый порядок соединения, но не ограничивать направление на каждом уровне:
/*+
NestLoop(t1 t2)
MergeJoin(t1 t2 t3)
Leading(t1 t2 t3)
*/
SELECT * FROM table1 t1
JOIN table table2 t2 ON (t1.key = t2.key)
JOIN table table3 t3 ON (t2.key = t3.key);Второй вариант — ограничить также и направление соединения. При выборе показанного выше порядка соединения, планировщик может выбрать не то направление (внешняя таблица — внутренняя таблица), которое вам бы хотелось. Чтобы в этом случае задать направление явно, используйте следующий формат:
/*+ Leading ((t1 (t2 t3))) * / SELECT ...
В этом формате скобки, окружающие пару элементов, определяют вложенность, при этом внутри одних скобок первый элемент будет в соединении внешней таблицей, а второй — внутренней.
Обратите внимание на то, что указание Leading (как и методы соединений) не может функционировать с модулем GEQO, если число указанных в запросе таблиц превышает geqo_threshold.
Ниже представлены дополнительные примеры использования указания для порядка соединения:
/*+ Leading(((c b) a)) */ EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM t1 a, t1 b, t1 c WHERE a.f1 = b.f1 AND b.f1 = c.f1;
QUERY PLAN
---------------------------------------------------------------
Aggregate
-> Hash Join
Hash Cond: (b.f1 = a.f1)
-> Nested Loop
-> Index Only Scan using t1_idx1 on t1 c
-> Memoize
Cache Key: c.f1
Cache Mode: logical
-> Index Only Scan using t1_idx1 on t1 b
Index Cond: (f1 = c.f1)
-> Hash
-> Seq Scan on t1 aИ ещё один пример запроса:
/*+ Leading(((d c) (b a))) */ EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM t1 a, t1 b, t1 c, t1 d WHERE a.f1 = b.f1 AND b.f1 = c.f1 AND c.f1 = d.f1;
QUERY PLAN
---------------------------------------------------------------
Aggregate
-> Hash Join
Hash Cond: (c.f1 = a.f1)
-> Nested Loop
-> Index Only Scan using t1_idx1 on t1 d
-> Memoize
Cache Key: d.f1
Cache Mode: logical
-> Index Only Scan using t1_idx1 on t1 c
Index Cond: (f1 = d.f1)
-> Hash
-> Hash Join
Hash Cond: (b.f1 = a.f1)
-> Seq Scan on t1 b
-> Hash
-> Seq Scan on t1 aЗа подробностями обратитесь к Подразделу H.4.9.
H.4.3.1.4. Указания для управления поведением соединения #
Указание «Memoize» позволяет соединению запоминать внутренний результат, а указание «NoMemoize» запрещает это. В приведённом ниже примере указание «NoMemoize» запрещает самому верхнему хеш-соединению запоминать результат таблицы a.
/*+ NoMemoize(a b) */
EXPLAIN SELECT * FROM a, b WHERE a.val = b.val;
QUERY PLAN
--------------------------------------------------------------------
Hash Join (cost=270.00..1412.50 rows=100000 width=16)
Hash Cond: (b.val = a.val)
-> Seq Scan on b (cost=0.00..15.00 rows=1000 width=8)
-> Hash (cost=145.00..145.00 rows=10000 width=8)
-> Seq Scan on a (cost=0.00..145.00 rows=10000 width=8)H.4.3.1.5. Указание для корректировки числа строк #
Указание Rows корректирует неверную оценку количества строк при соединениях, возможно вызванную ограничениями в планировщике. Например:
/*+ Rows(a b #10) */ SELECT... ; Устанавливает число строк результата соединения, равным 10 /*+ Rows(a b +10) */ SELECT... ; Увеличивает число строк на 10 /*+ Rows(a b -10) */ SELECT... ; Вычитает 10 из числа строк /*+ Rows(a b *10) */ SELECT... ; Увеличивает число строк в 10 раз
H.4.3.1.6. Указания для параллельных планов #
Указание Parallel устанавливает конфигурацию параллельного выполнения при сканировании. Третий параметр определяет режим изменений конфигурации. В режиме «soft» pg_hint_plan меняет только max_parallel_workers_per_gather и в остальном оставляет свободу выбора планировщику. В режиме «hard» меняются и другие параметры планировщика, чтобы принудительно установить количество параллельных исполнителей. Это указание может воздействовать на обычные таблицы, родительские таблицы в дереве наследования, нежурналируемые (UNLOGGED) таблицы и системные каталоги. На внешние таблицы, табличные функции, предложения VALUES, CTE, представления и вложенные запросы оно не действует. Обращаться в данном указании к внутренней таблице в представлении можно по имени или псевдонимам этой таблицы. Следующий пример показывает, как в одном запросе можно выбрать разные конфигурации для разных таблиц.
EXPLAIN /*+ Parallel(c1 3 hard) Parallel(c2 5 hard) */
SELECT c2.a FROM c1 JOIN c2 ON (c1.a = c2.a);
QUERY PLAN
-------------------------------------------------------------------------------
Hash Join (cost=2.86..11406.38 rows=101 width=4)
Hash Cond: (c1.a = c2.a)
-> Gather (cost=0.00..7652.13 rows=1000101 width=4)
Workers Planned: 3
-> Parallel Seq Scan on c1 (cost=0.00..7652.13 rows=322613 width=4)
-> Hash (cost=1.59..1.59 rows=101 width=4)
-> Gather (cost=0.00..1.59 rows=101 width=4)
Workers Planned: 5
-> Parallel Seq Scan on c2 (cost=0.00..1.59 rows=59 width=4)
EXPLAIN /*+ Parallel(tl 5 hard) */ SELECT sum(a) FROM tl;
QUERY PLAN
-----------------------------------------------------------------------------------
Finalize Aggregate (cost=693.02..693.03 rows=1 width=8)
-> Gather (cost=693.00..693.01 rows=5 width=8)
Workers Planned: 5
-> Partial Aggregate (cost=693.00..693.01 rows=1 width=8)
-> Parallel Seq Scan on tl (cost=0.00..643.00 rows=20000 width=4)H.4.3.1.7. Указания для хранимых процедур #
Указания можно использовать c хранимыми процедурами. Обратите внимание на то, что указания могут наследоваться.
CREATE OR REPLACE FUNCTION test_1() RETURNS bool AS $$
BEGIN
EXECUTE 'SELECT count(*) FROM t1 WHERE f1 < 2' ;
RETURN true;
END; $$ language plpgsql;
CREATE OR REPLACE FUNCTION test_2() RETURNS void AS $$
BEGIN
EXECUTE 'SELECT /*+ SET(enable_bitmapscan off)*/ test_1()' ;
END;
$$ language plpgsql;
SELECT test_2();
Query Text: SELECT count(*) FROM t1 WHERE f1 < 2
Aggregate (cost=18.00..18.01 rows=1 width=8) (actual time=0.511..0.512 rows=1 loops=1)
-> Seq Scan on t1 (cost=0.00..17.50 rows=200 width=0) (actual time=0.105..0.457 rows=200 loops=1)
Filter: (f1 < 2)
Rows Removed by Filter: 800H.4.3.1.8. Указания для подготовленных операторов #
Расширение pg_hint_plan позволяет использовать указания с подготовленными операторами. Указания следует записывать в операторе PREPARE, в операторе EXECUTE они игнорируются.
Ниже представлены примеры запросов. Первый пример с указанием IndexOnlyScan(t1):
/*+ IndexOnlyScan(t1) */ PREPARE stmt AS SELECT count(*) FROM t1 WHERE f1 < 2;
EXPLAIN EXECUTE stmt;
EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF) EXECUTE stmt;
QUERY PLAN
-------------------------------------------
Aggregate
-> Index Only Scan using t1_idx1 on t1
Index Cond: (f1 < 2)И второй — с указанием BitmapScan(t1):
/*+ BitmapScan(t1) */ EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF) EXECUTE stmt;
QUERY PLAN
-------------------------------------------
Aggregate
-> Index Only Scan using t1_idx1 on t1
Index Cond: (f1 < 2)H.4.3.1.9. Настройка параметров GUC во время планирования #
Указание Set меняет параметры GUC на время планирования. Желаемое влияние на планирование могут оказывать параметры GUC, показанные в Подразделе 19.7.2, если только какое-либо другое указание не конфликтует с заданными параметрами метода планирования. Если для одного параметра GUC задано несколько указаний, в силу вступает последнее. Это указание позволяет поменять и параметры GUC для pg_hint_plan, но результат может не соответствовать ожиданиям.
/*+ Set(random_page_cost 2.0) */ SELECT * FROM table1 t1 WHERE key = 'value'; ...
H.4.3.2. Параметры GUC для настройки pg_hint_plan #
На поведение pg_hint_plan влияют следующие описанные ниже параметры GUC.
Таблица H.7. Параметры GUC
| Имя параметра | Описание | Значение по умолчанию |
|---|---|---|
| pg_hint_plan.enable_hint | Значение True включает pg_hint_plan. | on |
| pg_hint_plan.enable_hint_table | Значение True включает использование указаний из таблицы. | off |
| pg_hint_plan.parse_messages | Задаёт уровень, с которым будут попадать в журнал ошибки разбора указаний. Допустимые значения: error (ошибка), warning (предупреждение), notice (уведомление), info (информация), log (протоколирование), debug (отладка). | info |
| pg_hint_plan.debug_print | Управляет выводом и детализацией отладочной информации. Допустимые значения: off, on, detailed и verbose. | off |
| pg_hint_plan.message_level | Задаёт уровень, с которым будут попадать в журнал отладочные сообщения. Допустимые значения: error, warning, notice, info, log, debug. | log |
| pg_hint_plan.hints_anywhere | Если имеет значение on, pg_hint_plan читает указания, игнорируя синтаксис SQL. Это позволяет размещать указания в любом месте запроса, но имейте в виду, что в этом случае указания могут считываться некорректно. | off |
H.4.4. Установка #
Расширение pg_hint_plan поставляется вместе с Postgres Pro Enterprise в виде отдельного пакета pg-hint-plan-ent-18 (подробные инструкции по установке приведены в Главе 17). После установки Postgres Pro Enterprise активируйте расширение pg_hint_plan:
LOAD 'pg_hint_plan'; LOAD
Вы также можете загрузить его глобально, добавив pg_hint_plan в параметр shared_preload_libraries в файле postgresql.conf.
shared_preload_libraries = 'pg_hint_plan'
Для автоматической загрузки определённых сеансов используйте ALTER USER SET/ALTER DATABASE SET.
По сути, pg_hint_plan не требует выполнения CREATE EXTENSION, но если вы планируете использовать таблицу указаний, создайте расширение и включите параметр enable_hint_table:
CREATE EXTENSION pg_hint_plan; SET pg_hint_plan.enable_hint_table TO on;
H.4.5. Подробное описание указаний #
H.4.5.1. Синтаксис и расположение #
Обработчик pg_hint_plan считывает указания только из первого блочного комментария и немедленно прекращает разбор, обнаруживая недопустимый символ. Допустимыми символами являются буквенные символы, цифры, пробелы, подчёркивания, запятые и скобки. В следующем примере HashJoin(a b) и SeqScan(a) воспринимаются в качестве указаний, а IndexScan(a) и MergeJoin(a b) — нет:
/*+
HashJoin(a b)
SeqScan(a)
*/
/*+ IndexScan(a) */
EXPLAIN SELECT /*+ MergeJoin(a b) */ *
FROM pgbench_branches b
JOIN pgbench_accounts a ON b.bid = a.bid
ORDER BY a.aid;
QUERY PLAN
---------------------------------------------------------------------------------------
Sort (cost=31465.84..31715.84 rows=100000 width=197)
Sort Key: a.aid
-> Hash Join (cost=1.02..4016.02 rows=100000 width=197)
Hash Cond: (a.bid = b.bid)
-> Seq Scan on pgbench_accounts a (cost=0.00..2640.00 rows=100000 width=97)
-> Hash (cost=1.01..1.01 rows=1 width=100)
-> Seq Scan on pgbench_branches b (cost=0.00..1.01 rows=1 width=100)
(7 rows)Однако если для параметра hints_anywhere задано значение on, pg_hint_plan считывает указания из любого места в запросе, поэтому следующие варианты использования указания будут равнозначными:
EXPLAIN /*+ SeqScan(t1)*/
SELECT * FROM table1 t1 WHERE a < 10;
QUERY PLAN
----------------------------------------------------------
Seq Scan on table1 t1 (cost=0.00..17.50 rows=9 width=8)
Filter: (a < 10)
(2 rows)
EXPLAIN
SELECT * FROM table1 t1 WHERE a < 10 AND '/*+SeqScan(t1)*/' <> '';
QUERY PLAN
----------------------------------------------------------
Seq Scan on table1 t1 (cost=0.00..17.50 rows=9 width=8)
Filter: (a < 10)
(2 rows)
EXPLAIN
SELECT * FROM table1 t1 WHERE a < 10 /*+SeqScan(t1)*/;
QUERY PLAN
----------------------------------------------------------
Seq Scan on table1 t1 (cost=0.00..17.50 rows=9 width=8)
Filter: (a < 10)
(2 rows)H.4.5.2. Использование с PL/pgSQL #
pg_hint_plan может работать с запросами в скриптах PL/pgSQL с некоторыми ограничениями.
Указания воздействуют только на следующие типы запросов:
Запросы, возвращающие одну строку (
SELECT,INSERT,UPDATEиDELETE)Запросы, возвращающие множество строк (
RETURN QUERY)Динамические операторы SQL (
EXECUTE)Запрос, открывающий курсор (
OPEN)Цикл по результату запроса (
FOR)
Комментарий с указанием должен добавляться после первого слова запроса, так как комментарии, идущие перед ним, в составе запроса не передаются.
CREATE FUNCTION hints_func(integer) RETURNS integer AS $$
DECLARE
id integer;
cnt integer;
BEGIN
SELECT /*+ NoIndexScan(a) */ aid
INTO id FROM pgbench_accounts a WHERE aid = $1;
SELECT /*+ SeqScan(a) */ count(*)
INTO cnt FROM pgbench_accounts a;
RETURN id + cnt;
END;
$$ LANGUAGE plpgsql;H.4.5.3. Регистр букв в именах объектов #
В отличие от PostgreSQL, pg_hint_plan, разбирая имена объектов в указаниях, сравнивает их с внутренними именами объектов с учётом регистра. Таким образом, имени TBL в указании будет соответствовать только объект "TBL" в базе данных, но не будут соответствовать объекты с именами без кавычек TBL, tbl или Tbl.
H.4.5.4. Экранирование спецсимволов в именах объектов #
Если имя объекта, определённого как параметр указания, включает в себя скобки, кавычки или пробелы, оно должно заключаться в кавычки. При этом действуют те же правила экранирования, что и в PostgreSQL.
H.4.5.5. Различение нескольких вхождений таблицы #
pg_hint_plan может выбирать целевые объекты по псевдонимам, если они заданы. Это позволяет обратиться к одному определённому вхождению таблицы, используемой в запросе неоднократно.
/*+ HashJoin(t1 t1) */
EXPLAIN SELECT * FROM s1.t1
JOIN public.t1 ON (s1.t1.id=public.t1.id);
INFO: hint syntax error at or near "HashJoin(t1 t1)"
DETAIL: Relation name "t1" is ambiguous.
...
/*+ HashJoin(pt st) */
EXPLAIN SELECT * FROM s1.t1 st
JOIN public.t1 pt ON (st.id=pt.id);
QUERY PLAN
---------------------------------------------------------------------
Hash Join (cost=64.00..1112.00 rows=28800 width=8)
Hash Cond: (st.id = pt.id)
-> Seq Scan on t1 st (cost=0.00..34.00 rows=2400 width=4)
-> Hash (cost=34.00..34.00 rows=2400 width=4)
-> Seq Scan on t1 pt (cost=0.00..34.00 rows=2400 width=4)H.4.5.6. Нижележащие таблицы представлений или правил #
Указания не применяются непосредственно к представлениям, но могут воздействовать на выполняемые запросы внутри представления, если имена объектов в указаниях совпадают с именами объектов в развёрнутом запросе представления. К таблицам внутри представления можно обращаться снаружи по назначенным им псевдонимам.
CREATE VIEW v1 AS SELECT * FROM t2;
EXPLAIN /*+ HashJoin(t1 v1) */
SELECT * FROM t1 JOIN v1 ON (c1.a = v1.a);
QUERY PLAN
------------------------------------------------------------------
Hash Join (cost=3.27..18181.67 rows=101 width=8)
Hash Cond: (t1.a = t2.a)
-> Seq Scan on t1 (cost=0.00..14427.01 rows=1000101 width=4)
-> Hash (cost=2.01..2.01 rows=101 width=4)
-> Seq Scan on t2 (cost=0.00..2.01 rows=101 width=4)И ещё один пример:
CREATE VIEW v1 AS SELECT count(*) FROM t1 WHERE f1 < 2;
/*+ IndexOnlyScan(t1) */ EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT * FROM v1;
QUERY PLAN
-------------------------------------------
Aggregate
-> Index Only Scan using t1_idx1 on t1
Index Cond: (f1 < 2)Не выбирайте таблицы с одинаковыми именами в разных представлениях, так как такие таблицы могут неправильно обрабатываться. Чтобы избежать такой ситуации, используйте уникальные псевдонимы, например сочетание наименования представления и наименования таблицы.
/*+ SeqScan(t1) */ EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT * FROM v2;
QUERY PLAN
-------------------------------------
Nested Loop Semi Join
Join Filter: ((count(*)) = t1.f1)
-> Aggregate
-> Seq Scan on t1 t1_1
Filter: (f1 < 2)
-> Seq Scan on t1H.4.5.7. Наследование #
Указания могут быть нацелены только на родителя в дереве наследования, однако при этом они воздействуют на все таблицы дерева. Указания, нацеленные на потомков в этом дереве, не будут действовать.
H.4.5.8. Указания в составных операторах #
Для одного описания составного оператора может задаваться только один комментарий, и записанные в нём указания будут распространяться на все отдельные операторы внутри этого составного оператора.
H.4.5.9. Выражения VALUES #
Все выражения VALUES в предложении FROM имеют внутреннее обозначение *VALUES*, так что к ним можно обращаться, только если в запросе фигурирует только одно выражение VALUES. Два или более выражений VALUES в запросе нельзя различить, посмотрев на EXPLAIN, из-за чего результаты выглядят неоднозначно:
/*+ MergeJoin(*VALUES*_1 *VALUES*) */
EXPLAIN SELECT * FROM (VALUES (1, 1), (2, 2)) v (a, b)
JOIN (VALUES (1, 5), (2, 8), (3, 4)) w (a, c) ON v.a = w.a;
INFO: pg_hint_plan: hint syntax error at or near "MergeJoin(*VALUES*_1 *VALUES*) "
DETAIL: Relation name "*VALUES*" is ambiguous.
QUERY PLAN
-------------------------------------------------------------------------
Hash Join (cost=0.05..0.12 rows=2 width=16)
Hash Cond: ("*VALUES*_1".column1 = "*VALUES*".column1)
-> Values Scan on "*VALUES*_1" (cost=0.00..0.04 rows=3 width=8)
-> Hash (cost=0.03..0.03 rows=2 width=8)
-> Values Scan on "*VALUES*" (cost=0.00..0.03 rows=2 width=8)H.4.5.10. Подзапросы #
В указаниях можно обращаться к подзапросам в следующем контексте по имени ANY_subquery:
IN (SELECT ... {LIMIT | OFFSET ...} ...)
= ANY (SELECT ... {LIMIT | OFFSET ...} ...)
= SOME (SELECT ... {LIMIT | OFFSET ...} ...)С этими конструкциями планировщик внутри даёт имя подзапросу, планируя соединения таблиц с этим подзапросом, так что в указаниях соединений можно обращаться к нему по этому неявному имени. Например:
/*+ HashJoin(a1 ANY_subquery)*/
EXPLAIN SELECT *
FROM pgbench_accounts a1
WHERE aid IN (SELECT bid FROM pgbench_accounts a2 LIMIT 10);
QUERY PLAN
---------------------------------------------------------------------------------------------
Hash Semi Join (cost=0.49..2903.00 rows=1 width=97)
Hash Cond: (a1.aid = a2.bid)
-> Seq Scan on pgbench_accounts a1 (cost=0.00..2640.00 rows=100000 width=97)
-> Hash (cost=0.36..0.36 rows=10 width=4)
-> Limit (cost=0.00..0.26 rows=10 width=4)
-> Seq Scan on pgbench_accounts a2 (cost=0.00..2640.00 rows=100000 width=4)H.4.5.11. Использование указания IndexOnlyScan #
Сканирование индекса может вопреки ожиданиям выполняться с другим индексом, когда индекс, заданный в указании IndexOnlyScan, оказывается неподходящим для сканирования только по индексу.
H.4.5.12. Указание NoIndexScan #
Указание NoIndexScan подразумевает NoIndexOnlyScan.
H.4.5.13. Параллельные указания и UNION #
Предложение UNION может выполняться в параллельном режиме, только когда все нижележащие подзапросы безопасны для распараллеливания. Поэтому, если параллельное выполнение принудительно выбирается для любого из подзапросов, всё предложение UNION будет обрабатываться параллельно, если это возможно. При этом выбор нулевого количества исполнителей в указании Parallel предотвращает выполнение в параллельном режиме.
H.4.5.14. Установка параметров pg_hint_plan в указаниях Set #
Параметры pg_hint_plan влияют на поведение самого модуля, поэтому некоторые параметры работают не так, как можно ожидать:
Указания, изменяющие
enable_hintиenable_hint_table, игнорируются, несмотря на то, что в отладочном выводе они отмечаются как «used hint» (используемое указание).Изменение
debug_printиmessage_levelначинает действовать с середины процедуры обработки запроса.
H.4.5.15. Использование указания DisableIndex #
Указание DisableIndex исключает указанные индексы из рассмотрения во время планирования запросов. Оно имеет приоритет над другими указаниями. Отключённый индекс не используется, даже если он явно запрашивается в указании IndexScan.
/*+DisableIndex(t t_c1) IndexScan(t t_c1) */
EXPLAIN SELECT * FROM t WHERE c1 = 1;
LOG: indexes disabled for DisableIndex(t): t_c1
LOG: available indexes for IndexScan(t):
LOG: pg_hint_plan:
used hint:
DisableIndex(t t_c1)
not used hint:
IndexScan(t t_c1)
duplication hint:
error hint:
QUERY PLAN
-----------------------------------------------------------------
Index Scan using t_pkey on t (cost=0.15..8.17 rows=1 width=12)
Index Cond: (c1 = 1)
(2 rows)H.4.6. Вывод отладочной информации #
Если для параметра pg_hint_plan.debug_print установлено любое значение, отличное от off, расширение выводит отладочную информацию со следующими категориями указаний:
used hint (используемое указание): указания, которые успешно разобраны pg_hint_plan, не имеют синтаксических ошибок и ссылаются на действительные определения объектов. Планировщик пытается применить эти указания для изменения плана выполнения запроса. Однако, если попытка применить определённое указание завершается ошибкой, планировщик игнорирует это указание и выбирает любой выполнимый план. За подробной информацией обратитесь к разделу Указания, принудительно выбирающие невыполнимые планы. Результирующий план можно проверить в выводе команды EXPLAIN.
not used hint (неиспользуемое указание): указания, которые разобраны pg_hint_plan, но ссылаются на недействительные определения объектов или индексы, исключенные из планирования указанием DisableIndex.
duplication hint (дублирующее указание): указания, которые разобраны pg_hint_plan, но являются избыточными или конфликтующими.
error hint (ошибочное указание): указания, которые не могут быть разобраны и применены из-за некорректных имён или любых синтаксических ошибок.
H.4.7. Ошибки #
Обработчик pg_hint_plan останавливает разбор в случае ошибки и применяет указания, уже разобранные к этому моменту. Ниже перечислены типичные ошибки.
H.4.7.1. Синтаксические ошибки #
Любые ошибки в записи или неправильные имена указаний считаются ошибками синтаксиса. Эти ошибки выводятся в журнал сообщений сервера с уровнем, заданным в параметре pg_hint_plan.message_level, если параметр pg_hint_plan.debug_print имеет значение, отличное от off.
H.4.7.2. Некорректные определения объектов #
Указания с некорректными определениями объектов просто игнорируются. Ошибки такого типа отмечаются в журнале сообщений сервера как «not used hint» (неиспользуемое указание).
H.4.7.3. Избыточные или конфликтующие указания #
Когда указания избыточны или одно указание конфликтует с другим, действовать будет последнее указание. Ошибки такого типа отмечаются как «duplication hint» (дублирующее указание) в журнале сообщений сервера при тех же условиях, что и синтаксические ошибки.
H.4.7.4. Вложенные комментарии #
Комментарий с указаниями не может быть рекурсивным. Если pg_hint_plan сталкивается с такой ситуацией, то разбор указания немедленно прекращается и все уже разобранные указания игнорируются.
H.4.8. Функциональные ограничения #
H.4.8.1. Влияние параметров GUC на планирование #
Планировщик не будет рассматривать порядок соединения для предложений FROM, в которых больше чем from_collapse_limit элементов. В таких случаях pg_hint_plan не может повлиять на порядок соединения.
H.4.8.2. Указания, принудительно выбирающие невыполнимые планы #
В случаях, когда принудительно выбранный план выполнить нельзя, планировщик выбирает любые исполнимые планы.
Использовать для FULL OUTER JOIN вложенный цикл.
Использовать индексы, столбцы которых не задействуются в условиях.
Сканирования TID для запросов без условий с
ctid
H.4.8.3. Запросы в ECPG #
ECPG убирает комментарии из запросов, записанных в виде встраиваемого SQL, так что указания с такими запросами передать нельзя. Единственным исключением является команда EXECUTE, которая передаёт данную строку неизменённой. В таком случае могут быть полезны таблицы с указаниями.
H.4.8.4. Идентификаторы запросов #
Когда compute_query_id включён, Postgres Pro генерирует идентификатор запроса, игнорируя комментарии. Таким образом, запросы с разными указаниями, но одинаково написанные, могут получать один и тот же идентификатор.
H.4.9. Поддерживаемые указания #
Ниже перечислены все поддерживаемые указания.
Таблица H.8. Список указаний
| Группа | Формат | Описание |
|---|---|---|
| Метод сканирования | SeqScan(таблица) | Принудительно выбирает последовательное сканирование таблицы. |
TidScan(таблица) | Принудительно выбирает сканирование таблицы по TID. | |
IndexScan(таблица [ индекс...]) | Принудительно выбирает сканирование таблицы по индексу (при добавлении индексов сканирование ограничивается ими). | |
IndexOnlyScan(таблица [ индекс...]) | Принудительно выбирает сканирование таблицы только по индексу (при добавлении индексов сканирование ограничивается ими). Если сканирование только по индексу невозможно, может использоваться обычное сканирование по индексу. | |
BitmapScan(таблица[ индекс...]) | Принудительно выбирает сканирование таблицы по битовой карте (при добавлении индексов сканирование ограничивается ими). | |
IndexScanRegexp(таблица [ регулярное выражение POSIX...]) | Принудительно выбирает сканирование таблицы по индексу. Сканирование ограничивается индексами с именами, соответствующими указанному регулярному выражению POSIX. | |
IndexOnlyScanRegexp(таблица [ регулярное выражение POSIX...]) | Принудительно выбирает сканирование таблицы только по индексу. Сканирование ограничивается индексами с именами, соответствующими указанному регулярному выражению POSIX. | |
BitmapScanRegexp(таблица[ регулярное выражение POSIX...]) | Принудительно выбирает сканирование таблицы по битовой карте. Сканирование ограничивается индексами с именами, соответствующими указанному регулярному выражению POSIX. | |
NoSeqScan(таблица) | Отключает выбор последовательного сканирование таблицы. | |
NoTidScan(таблица) | Отключает выбор сканирования таблицы по TID. | |
NoIndexScan(таблица) | Отключает выбор сканирования по индексу и сканирования только по индексу для заданной таблицы. | |
NoIndexOnlyScan(таблица) | Принудительно отключает выбор сканирования только по индексу для заданной таблицы. | |
NoBitmapScan(таблица) | Отключает выбор сканирования по битовой карте для таблицы. | |
| Отключение индексов | DisableIndex(индекс_таблицы...) | Отключает указанные индексы при планировании запросов, имея приоритет над всеми остальными указаниями. |
| Метод соединения | NestLoop(таблица таблица[ таблица...]) | Принудительно выбирает вложенный цикл для соединений с заданными таблицами. |
HashJoin(таблица таблица[ таблица...]) | Принудительно выбирает соединение по хешу для соединений с заданными таблицами. | |
MergeJoin(таблица таблица[ таблица...]) | Принудительно выбирает соединение слиянием для соединений с заданными таблицами. | |
NoNestLoop(таблица таблица[ таблица...]) | Отключает выбор вложенного цикла для соединений с заданными таблицами. | |
NoHashJoin(таблица таблица[ таблица...]) | Отключает выбор соединения по хешу для соединений с заданными таблицами. | |
NoMergeJoin(таблица таблица[ таблица...]) | Отключает выбор соединения слиянием для соединений с заданными таблицами. | |
| Порядок соединения | Leading(таблица таблица[ таблица...]) | Принудительно выбирает заданный порядок соединения. |
Leading(<соединяемая пара>) | Принудительно выбирает заданный порядок и направления соединения. Соединяемая пара в данном случае — это пара таблица и/или других соединяемых пар, заключённая в скобки, что позволяет образовывать вложенные структуры. | |
| Управление поведением соединения | Memoize(таблица таблица[ таблица...]) | Позволяет самому верхнему соединению среди соединений, включающих указанные таблицы, запоминать внутренний результат. Обратите внимание, что запоминание при этом не будет задействовано принудительно. |
NoMemoize(таблица таблица[ таблица...]) | Запрещает самому верхнему соединению среди соединений, включающих указанные таблицы, запоминать внутренний результат. | |
| Корректировка числа строк | Rows(таблица таблица[ таблица...] корректировка) | Корректирует число строк, получаемых в результате соединения указанных таблиц. Для корректировки можно задать абсолютное значение (#<n>) или использовать сложение (+<n>), вычитание (-<n>) и умножение (*<n>). Здесь <n> — это строка, которую сможет воспринять функция strtod(). |
| Настройка параллельных запросов | Parallel(таблица<число исполнителей> [soft|hard]) | Принудительно включает или отключает параллельную обработку заданной таблицы. Параметр <число исполнителей> в этом указании определяет желаемое количество параллельных исполнителей (значение 0 отключает параллельное выполнение). Если третий параметр равен soft (по умолчанию), меняется только значение параметра сервера max_parallel_workers_per_gather, а в остальном планировщику остаётся свобода выбора. Со значением hard заданное количество исполнителей устанавливается принудительно. |
| GUC | Set(параметр-GUC значение) | Устанавливает значение для параметра GUC на время планирования запроса. |
H.4.10. См. также #
H.4. pg_hint_plan — control an execution plan with hinting phrases #
H.4.1. Description #
pg_hint_plan is a module that allows a user to control an execution plan with hinting phrases mentioned in comments of a special form.
Postgres Pro Enterprise uses a cost-based optimizer, which utilizes data statistics rather than static rules. The planner (optimizer) estimates costs of all possible execution plans for an SQL statement, then the execution plan with the lowest cost is executed. The planner makes every effort to select the best execution plan, but it is not always perfect, since it does not take into account some of the data properties or correlations between columns.
pg_hint_plan makes it possible to tweak execution plans using so-called “hints”, which are simple descriptions added in SQL comments of a special form.
H.4.2. Overview #
H.4.2.1. Basic Usage #
pg_hint_plan reads hinting phrases in comments of a special form given with the target SQL statement. The special comment begins with the character sequence /*+ and ends with */. Hinting phrases consist of a hint name and following parameters enclosed in parentheses and delimited by whitespaces. Each hinting phrase can be delimited by new lines for readability.
In the example below, a hash join is selected as a joining method and pgbench_accounts is scanned by a sequential scan method.
/*+
HashJoin(a b)
SeqScan(a)
*/
EXPLAIN SELECT *
FROM pgbench_branches b
JOIN pgbench_accounts a ON b.bid = a.bid
ORDER BY a.aid;
QUERY PLAN
---------------------------------------------------------------------------------------
Sort (cost=31465.84..31715.84 rows=100000 width=197)
Sort Key: a.aid
-> Hash Join (cost=1.02..4016.02 rows=100000 width=197)
Hash Cond: (a.bid = b.bid)
-> Seq Scan on pgbench_accounts a (cost=0.00..2640.00 rows=100000 width=97)
-> Hash (cost=1.01..1.01 rows=1 width=100)
-> Seq Scan on pgbench_branches b (cost=0.00..1.01 rows=1 width=100)
(7 rows)
H.4.3. Hint Table #
The above section mentions that hints are inserted in a comment of a special form. This is inconvenient if a query cannot be edited. For such cases, hints can be placed in a special table called hint_plan.hints, which looks as follows:
| Column | Description |
|---|---|
| id | A unique number to identify a row for a hint. This column is filled automatically by sequence. |
| query_id | A unique query ID, generated by the backend when the compute_query_id configuration parameter is enabled. |
| application_name | A value of application_name of sessions to apply the hint to. The hint in the example below applies to sessions connected from psql. An empty string means sessions with any application_name. |
| hint | A hint phrase. This must be a series of hints excluding surrounding comment marks. |
The following example shows how to work with the hint table.
=# EXPLAIN (VERBOSE, COSTS false) SELECT * FROM t1 WHERE t1.id = 1;
QUERY PLAN
----------------------------------------
Seq Scan on public.t1
Output: id, id2
Filter: (t1.id = 1)
Query Identifier: -7164653396197960701
(4 rows)
=# INSERT INTO hint_plan.hints(query_id, application_name, hints)
VALUES (-7164653396197960701, '', 'SeqScan(t1)');
INSERT 0 1
UPDATE hint_plan.hints
SET hints = 'IndexScan(t1)'
WHERE id = 1;
UPDATE 1
DELETE FROM hint_plan.hints
WHERE id = 1;
DELETE 1
The hint table is owned by the extension owner and has the same default privileges as at the time of its creation, i.e. during CREATE EXTENSION. Hints in the hint table take priority over the hints specified in comments.
The query ID can be retrieved with pg_stat_statements or with EXPLAIN VERBOSE.
H.4.3.1. Types of Hints #
Hinting phrases are classified into several types depending on the kind of object and how they can affect the planner. For more details, see Section H.4.9.
H.4.3.1.1. Hints for Scan Methods #
Scan method hints enforce a specific scanning method on the target table. pg_hint_plan recognizes the target table by alias names, if any. They are, for example, SeqScan or IndexScan.
Scan hints work with ordinary tables, inheritance tables, UNLOGGED tables, temporary tables, and system catalogs. External (foreign) tables, table functions, VALUES clause, CTEs, views, and subqueries are not affected.
/*+
SeqScan(t1)
IndexScan(t2 t2_pkey)
*/
SELECT * FROM table1 t1 JOIN table table2 t2 ON (t1.key = t2.key);
H.4.3.1.2. Hints for Join Methods #
Join method hints enforce join methods of the joins involving the specified tables.
This can affect joins only on ordinary tables. Inheritance tables, UNLOGGED tables, temporary tables, external (foreign) tables, system catalogs, table functions, VALUES command results, and CTEs are allowed to be in the parameter list. Joins on views and subqueries are not affected.
Join method hints are recommended to be used together with the Leading joining order hint because it guarantees that a joining order specified in the request will be executed.
The hint below prompts the NestLoop(MergeJoin(c b) a) joining structure:
/*+ Leading(((c b) a)) MergeJoin(c b) NestLoop(a b c) */ EXPLAIN(COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM t1 a, t1 b, t1 c WHERE a.f1 = b.f1 AND b.f1 = c.f1;
QUERY PLAN
---------------------------------------------------------------
Aggregate
-> Nested Loop
-> Merge Join
Merge Cond: (c.f1 = b.f1)
-> Index Only Scan using t1_idx1 on t1 c
-> Materialize
-> Index Only Scan using t1_idx1 on t1 b
-> Memoize
Cache Key: b.f1
Cache Mode: logical
-> Index Only Scan using t1_idx1 on t1 a
Index Cond: (f1 = b.f1)
H.4.3.1.3. Hint for Joining Order #
The Leading hint enforces the joining order for two or more tables. There are two ways of enforcing. One is enforcing specific joining order but not restricting direction at each join level:
/*+
NestLoop(t1 t2)
MergeJoin(t1 t2 t3)
Leading(t1 t2 t3)
*/
SELECT * FROM table1 t1
JOIN table table2 t2 ON (t1.key = t2.key)
JOIN table table3 t3 ON (t2.key = t3.key);
Another way also enforces join direction. When the above join order is specified, the join direction chosen by the planner (outer table — inner table) may be different from the expected one. If you want to change the join direction in such a situation, use the following format:
/*+ Leading ((t1 (t2 t3))) * / SELECT ...
In this format, two elements enclosed in parentheses are nested, and within one parenthesis, the first element is the outer table, and the second element is the inner table.
Note that the Leading hint (just like join methods) does not operate together with GEQO if the number of tables specified in the request exceeds geqo_threshold.
Some extra examples of using the hint for joining order:
/*+ Leading(((c b) a)) */ EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM t1 a, t1 b, t1 c WHERE a.f1 = b.f1 AND b.f1 = c.f1;
QUERY PLAN
---------------------------------------------------------------
Aggregate
-> Hash Join
Hash Cond: (b.f1 = a.f1)
-> Nested Loop
-> Index Only Scan using t1_idx1 on t1 c
-> Memoize
Cache Key: c.f1
Cache Mode: logical
-> Index Only Scan using t1_idx1 on t1 b
Index Cond: (f1 = c.f1)
-> Hash
-> Seq Scan on t1 a
And an example below:
/*+ Leading(((d c) (b a))) */ EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM t1 a, t1 b, t1 c, t1 d WHERE a.f1 = b.f1 AND b.f1 = c.f1 AND c.f1 = d.f1;
QUERY PLAN
---------------------------------------------------------------
Aggregate
-> Hash Join
Hash Cond: (c.f1 = a.f1)
-> Nested Loop
-> Index Only Scan using t1_idx1 on t1 d
-> Memoize
Cache Key: d.f1
Cache Mode: logical
-> Index Only Scan using t1_idx1 on t1 c
Index Cond: (f1 = d.f1)
-> Hash
-> Hash Join
Hash Cond: (b.f1 = a.f1)
-> Seq Scan on t1 b
-> Hash
-> Seq Scan on t1 a
For details, see Section H.4.9.
H.4.3.1.4. Hints for Controlling Join Behavior #
The “Memoize” hint allows the join to memoize the inner result, and the “NoMemoize” hint disallows it. In the example below, the “NoMemoize” hint prohibits the topmost hash join from memoizing the result of the table a.
/*+ NoMemoize(a b) */
EXPLAIN SELECT * FROM a, b WHERE a.val = b.val;
QUERY PLAN
--------------------------------------------------------------------
Hash Join (cost=270.00..1412.50 rows=100000 width=16)
Hash Cond: (b.val = a.val)
-> Seq Scan on b (cost=0.00..15.00 rows=1000 width=8)
-> Hash (cost=145.00..145.00 rows=10000 width=8)
-> Seq Scan on a (cost=0.00..145.00 rows=10000 width=8)
H.4.3.1.5. Hint for Row Number Correction #
The Rows hint corrects the row number misestimation of joins that comes from restrictions in the planner. For example:
/*+ Rows(a b #10) */ SELECT... ; Sets rows of join result to 10 /*+ Rows(a b +10) */ SELECT... ; Increments row number by 10 /*+ Rows(a b -10) */ SELECT... ; Subtracts 10 from the row number. /*+ Rows(a b *10) */ SELECT... ; Makes the number 10 times larger.
H.4.3.1.6. Hint for Parallel Plans #
The Parallel hint enforces parallel execution configuration on scans. The third parameter specifies the strength of enforcement. “soft” means that pg_hint_plan only changes max_parallel_workers_per_gather and leaves all others to the planner. “hard” changes other planner parameters so as to forcibly apply the number. This can affect ordinary tables, inheritance parents, UNLOGGED tables, and system catalog. External tables, table functions, VALUES clause, CTEs, views, and subqueries are not affected. Internal tables of a view can be specified by its real name or its alias as the target object. The following example shows that the query is enforced differently on each table.
EXPLAIN /*+ Parallel(c1 3 hard) Parallel(c2 5 hard) */
SELECT c2.a FROM c1 JOIN c2 ON (c1.a = c2.a);
QUERY PLAN
-------------------------------------------------------------------------------
Hash Join (cost=2.86..11406.38 rows=101 width=4)
Hash Cond: (c1.a = c2.a)
-> Gather (cost=0.00..7652.13 rows=1000101 width=4)
Workers Planned: 3
-> Parallel Seq Scan on c1 (cost=0.00..7652.13 rows=322613 width=4)
-> Hash (cost=1.59..1.59 rows=101 width=4)
-> Gather (cost=0.00..1.59 rows=101 width=4)
Workers Planned: 5
-> Parallel Seq Scan on c2 (cost=0.00..1.59 rows=59 width=4)
EXPLAIN /*+ Parallel(tl 5 hard) */ SELECT sum(a) FROM tl;
QUERY PLAN
-----------------------------------------------------------------------------------
Finalize Aggregate (cost=693.02..693.03 rows=1 width=8)
-> Gather (cost=693.00..693.01 rows=5 width=8)
Workers Planned: 5
-> Partial Aggregate (cost=693.00..693.01 rows=1 width=8)
-> Parallel Seq Scan on tl (cost=0.00..643.00 rows=20000 width=4)
H.4.3.1.7. Hints for Stored Procedures #
Hints can be used with stored procedures. Be careful when using hints, since they can be inherited.
CREATE OR REPLACE FUNCTION test_1() RETURNS bool AS $$
BEGIN
EXECUTE 'SELECT count(*) FROM t1 WHERE f1 < 2' ;
RETURN true;
END; $$ language plpgsql;
CREATE OR REPLACE FUNCTION test_2() RETURNS void AS $$
BEGIN
EXECUTE 'SELECT /*+ SET(enable_bitmapscan off)*/ test_1()' ;
END;
$$ language plpgsql;
SELECT test_2();
Query Text: SELECT count(*) FROM t1 WHERE f1 < 2
Aggregate (cost=18.00..18.01 rows=1 width=8) (actual time=0.511..0.512 rows=1 loops=1)
-> Seq Scan on t1 (cost=0.00..17.50 rows=200 width=0) (actual time=0.105..0.457 rows=200 loops=1)
Filter: (f1 < 2)
Rows Removed by Filter: 800
H.4.3.1.8. Hints for Prepared Statements #
The pg_hint_plan extension allows using hints with prepared statements. Hints should be specified in the PREPARE statement and are ignored in the EXECUTE statement.
Below are a couple of sample queries. With the IndexOnlyScan(t1) hint:
/*+ IndexOnlyScan(t1) */ PREPARE stmt AS SELECT count(*) FROM t1 WHERE f1 < 2;
EXPLAIN EXECUTE stmt;
EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF) EXECUTE stmt;
QUERY PLAN
-------------------------------------------
Aggregate
-> Index Only Scan using t1_idx1 on t1
Index Cond: (f1 < 2)
And with the BitmapScan(t1) hint:
/*+ BitmapScan(t1) */ EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF) EXECUTE stmt;
QUERY PLAN
-------------------------------------------
Aggregate
-> Index Only Scan using t1_idx1 on t1
Index Cond: (f1 < 2)
H.4.3.1.9. Setting GUC Parameters During Planning #
The Set hint changes GUC parameters during planning. The GUC parameter shown in Section 19.7.2 can have the expected effects on planning unless any other hint conflicts with the planner method configuration parameters. When multiple hints change the same GUC, the last hint takes effect. GUC parameters for pg_hint_plan are also settable by this hint, but it may not work as you expect.
/*+ Set(random_page_cost 2.0) */ SELECT * FROM table1 t1 WHERE key = 'value'; ...
H.4.3.2. GUC Parameters for pg_hint_plan #
GUC parameters described below affect the behavior of pg_hint_plan.
Table H.7. GUC Parameters
| Parameter Name | Description | Default Value |
|---|---|---|
| pg_hint_plan.enable_hint | True enables pg_hint_plan. | on |
| pg_hint_plan.enable_hint_table | True enables hinting by table. | off |
| pg_hint_plan.parse_messages | Specifies the log level of hint parse error. Valid values are error, warning, notice, info, log, debug. | info |
| pg_hint_plan.debug_print | Controls debug print and verbosity. Valid values are off, on, detailed, and verbose. | off |
| pg_hint_plan.message_level | Specifies message level of debug print. Valid values are error, warning, notice, info, log, debug. | log |
| pg_hint_plan.hints_anywhere | If it is on, pg_hint_plan reads hints ignoring SQL syntax. This allows placing hints anywhere in the query but may cause false reads. | off |
H.4.4. Installation #
The pg_hint_plan extension is provided with Postgres Pro Enterprise as a separate pre-built package pg-hint-plan-ent-18 (for the detailed installation instructions, see Chapter 17). Once you have Postgres Pro Enterprise installed, activate pg_hint_plan:
LOAD 'pg_hint_plan'; LOAD
You can also load it globally by adding pg_hint_plan to the shared_preload_libraries parameter in the postgresql.conf file.
shared_preload_libraries = 'pg_hint_plan'
For automatic loading for specific sessions, use ALTER USER SET/ALTER DATABASE SET.
pg_hint_plan does not require CREATE EXTENSION, but if you plan to use the hint table, create the extension and enable the enable_hint_table parameter:
CREATE EXTENSION pg_hint_plan; SET pg_hint_plan.enable_hint_table TO on;
H.4.5. Details in Hinting #
H.4.5.1. Syntax and Placement #
pg_hint_plan reads hints only from the first block comment and immediately stops parsing of any characters except alphabetical characters, digits, spaces, underscores, commas, and parentheses. In the following example HashJoin(a b) and SeqScan(a) are parsed as hints, but IndexScan(a) and MergeJoin(a b) are not:
/*+
HashJoin(a b)
SeqScan(a)
*/
/*+ IndexScan(a) */
EXPLAIN SELECT /*+ MergeJoin(a b) */ *
FROM pgbench_branches b
JOIN pgbench_accounts a ON b.bid = a.bid
ORDER BY a.aid;
QUERY PLAN
---------------------------------------------------------------------------------------
Sort (cost=31465.84..31715.84 rows=100000 width=197)
Sort Key: a.aid
-> Hash Join (cost=1.02..4016.02 rows=100000 width=197)
Hash Cond: (a.bid = b.bid)
-> Seq Scan on pgbench_accounts a (cost=0.00..2640.00 rows=100000 width=97)
-> Hash (cost=1.01..1.01 rows=1 width=100)
-> Seq Scan on pgbench_branches b (cost=0.00..1.01 rows=1 width=100)
(7 rows)
However, when the hints_anywhere parameter is on, pg_hint_plan reads hints from anywhere in the query so the following hint uses would be equivalent:
EXPLAIN /*+ SeqScan(t1)*/
SELECT * FROM table1 t1 WHERE a < 10;
QUERY PLAN
----------------------------------------------------------
Seq Scan on table1 t1 (cost=0.00..17.50 rows=9 width=8)
Filter: (a < 10)
(2 rows)
EXPLAIN
SELECT * FROM table1 t1 WHERE a < 10 AND '/*+SeqScan(t1)*/' <> '';
QUERY PLAN
----------------------------------------------------------
Seq Scan on table1 t1 (cost=0.00..17.50 rows=9 width=8)
Filter: (a < 10)
(2 rows)
EXPLAIN
SELECT * FROM table1 t1 WHERE a < 10 /*+SeqScan(t1)*/;
QUERY PLAN
----------------------------------------------------------
Seq Scan on table1 t1 (cost=0.00..17.50 rows=9 width=8)
Filter: (a < 10)
(2 rows)
H.4.5.2. Using with PL/pgSQL #
pg_hint_plan works for queries in PL/pgSQL scripts with some restrictions.
Hints affect only the following kinds of queries:
Queries that return one row (
SELECT,INSERT,UPDATE, andDELETE)Queries that return multiple rows (
RETURN QUERY)Dynamic SQL statements (
EXECUTE)Cursor open (
OPEN)Loop over result of a query (
FOR)
A hint comment should be placed after the first word in a query as in the example below, since preceding comments are not sent as a part of the query.
CREATE FUNCTION hints_func(integer) RETURNS integer AS $$
DECLARE
id integer;
cnt integer;
BEGIN
SELECT /*+ NoIndexScan(a) */ aid
INTO id FROM pgbench_accounts a WHERE aid = $1;
SELECT /*+ SeqScan(a) */ count(*)
INTO cnt FROM pgbench_accounts a;
RETURN id + cnt;
END;
$$ LANGUAGE plpgsql;
H.4.5.3. Letter Case in Object Names #
Unlike the way PostgreSQL handles object names, pg_hint_plan compares bare object names in hints against the database internal object names in a case-sensitive manner. Therefore, an object name TBL in a hint matches only "TBL" in database and does not match any unquoted names like TBL, tbl, or Tbl.
H.4.5.4. Escaping Special Characters in Object Names #
The objects defined as the hint parameter should be enclosed in double quotes if they include parentheses, double quotes, and whitespaces. The escaping rules are the same as in PostgreSQL.
H.4.5.5. Distinction Between Multiple Occurrences of a Table #
pg_hint_plan identifies the target object by using aliases if they exist. This behavior is useful to point at a specific occurrence among multiple occurrences of one table.
/*+ HashJoin(t1 t1) */
EXPLAIN SELECT * FROM s1.t1
JOIN public.t1 ON (s1.t1.id=public.t1.id);
INFO: hint syntax error at or near "HashJoin(t1 t1)"
DETAIL: Relation name "t1" is ambiguous.
...
/*+ HashJoin(pt st) */
EXPLAIN SELECT * FROM s1.t1 st
JOIN public.t1 pt ON (st.id=pt.id);
QUERY PLAN
---------------------------------------------------------------------
Hash Join (cost=64.00..1112.00 rows=28800 width=8)
Hash Cond: (st.id = pt.id)
-> Seq Scan on t1 st (cost=0.00..34.00 rows=2400 width=4)
-> Hash (cost=34.00..34.00 rows=2400 width=4)
-> Seq Scan on t1 pt (cost=0.00..34.00 rows=2400 width=4)
H.4.5.6. Underlying Tables of Views or Rules #
Hints are not applicable on views themselves, but they can affect the queries within the view if the object names match the object names in the expanded query on the view. Assigning aliases to the tables in the view enables them to be manipulated from outside of the view.
CREATE VIEW v1 AS SELECT * FROM t2;
EXPLAIN /*+ HashJoin(t1 v1) */
SELECT * FROM t1 JOIN v1 ON (c1.a = v1.a);
QUERY PLAN
------------------------------------------------------------------
Hash Join (cost=3.27..18181.67 rows=101 width=8)
Hash Cond: (t1.a = t2.a)
-> Seq Scan on t1 (cost=0.00..14427.01 rows=1000101 width=4)
-> Hash (cost=2.01..2.01 rows=101 width=4)
-> Seq Scan on t2 (cost=0.00..2.01 rows=101 width=4)
And one more example:
CREATE VIEW v1 AS SELECT count(*) FROM t1 WHERE f1 < 2;
/*+ IndexOnlyScan(t1) */ EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT * FROM v1;
QUERY PLAN
-------------------------------------------
Aggregate
-> Index Only Scan using t1_idx1 on t1
Index Cond: (f1 < 2)
Be careful not to select tables with identical names in different views because these tables may become affected. To avoid this, try using unique aliases, for example, a combination of a view name and a table name:
/*+ SeqScan(t1) */ EXPLAIN (COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT * FROM v2;
QUERY PLAN
-------------------------------------
Nested Loop Semi Join
Join Filter: ((count(*)) = t1.f1)
-> Aggregate
-> Seq Scan on t1 t1_1
Filter: (f1 < 2)
-> Seq Scan on t1
H.4.5.7. Inheritance #
Hints can point only at the parent of an inheritance tree, yet they affect all the tables in the inheritance tree. Hints pointing directly at children will not take effect.
H.4.5.8. Hinting in Multistatements #
One multistatement can have exactly one hint comment and this hint affects all individual statements in the multistatement.
H.4.5.9. VALUES Expressions #
VALUES expressions in the FROM clause are named as *VALUES* internally, so they are hintable if it is the only VALUES expression in a query. Two or more VALUES expressions in a query cannot be distinguished by looking at EXPLAIN, which makes the results ambiguous:
/*+ MergeJoin(*VALUES*_1 *VALUES*) */
EXPLAIN SELECT * FROM (VALUES (1, 1), (2, 2)) v (a, b)
JOIN (VALUES (1, 5), (2, 8), (3, 4)) w (a, c) ON v.a = w.a;
INFO: pg_hint_plan: hint syntax error at or near "MergeJoin(*VALUES*_1 *VALUES*) "
DETAIL: Relation name "*VALUES*" is ambiguous.
QUERY PLAN
-------------------------------------------------------------------------
Hash Join (cost=0.05..0.12 rows=2 width=16)
Hash Cond: ("*VALUES*_1".column1 = "*VALUES*".column1)
-> Values Scan on "*VALUES*_1" (cost=0.00..0.04 rows=3 width=8)
-> Hash (cost=0.03..0.03 rows=2 width=8)
-> Values Scan on "*VALUES*" (cost=0.00..0.03 rows=2 width=8)
H.4.5.10. Subqueries #
Subqueries in the following context can be hinted using the ANY_subquery name:
IN (SELECT ... {LIMIT | OFFSET ...} ...)
= ANY (SELECT ... {LIMIT | OFFSET ...} ...)
= SOME (SELECT ... {LIMIT | OFFSET ...} ...)
For these syntaxes, the planner internally assigns a name to the subquery when planning joins on tables including it, so join hints are applicable on such joins using the implicit name. For example:
/*+ HashJoin(a1 ANY_subquery)*/
EXPLAIN SELECT *
FROM pgbench_accounts a1
WHERE aid IN (SELECT bid FROM pgbench_accounts a2 LIMIT 10);
QUERY PLAN
---------------------------------------------------------------------------------------------
Hash Semi Join (cost=0.49..2903.00 rows=1 width=97)
Hash Cond: (a1.aid = a2.bid)
-> Seq Scan on pgbench_accounts a1 (cost=0.00..2640.00 rows=100000 width=97)
-> Hash (cost=0.36..0.36 rows=10 width=4)
-> Limit (cost=0.00..0.26 rows=10 width=4)
-> Seq Scan on pgbench_accounts a2 (cost=0.00..2640.00 rows=100000 width=4)
H.4.5.11. Using the IndexOnlyScan Hint #
The index scan may be unexpectedly performed on another index when the index specified in the IndexOnlyScan hint cannot perform the index-only scan.
H.4.5.12. The NoIndexScan Hint #
The NoIndexScan hint implies NoIndexOnlyScan.
H.4.5.13. Parallel Hints and UNION #
A UNION can run in parallel only when all underlying subqueries are parallel-safe. Therefore, enforcing parallel on any of the subqueries allows a parallel-executable UNION to run in parallel. Meanwhile, the Parallel hint with zero workers prevents a scan from being executed in parallel.
H.4.5.14. Setting pg_hint_plan Parameters by Set Hints #
pg_hint_plan parameters influence the behavior of the module, so some parameters do not work as expected:
Hints to change
enable_hint,enable_hint_tableare ignored even though they are reported as “used hints” in debug logs.Setting
debug_printandmessage_levelstarts working in the middle of the query processing.
H.4.5.15. Using the DisableIndex Hint #
The DisableIndex hint excludes the specified indexes from being considered during query planning. It takes precedence over other hints. A disabled index is not used, even if explicitly requested by IndexScan.
/*+DisableIndex(t t_c1) IndexScan(t t_c1) */
EXPLAIN SELECT * FROM t WHERE c1 = 1;
LOG: indexes disabled for DisableIndex(t): t_c1
LOG: available indexes for IndexScan(t):
LOG: pg_hint_plan:
used hint:
DisableIndex(t t_c1)
not used hint:
IndexScan(t t_c1)
duplication hint:
error hint:
QUERY PLAN
-----------------------------------------------------------------
Index Scan using t_pkey on t (cost=0.15..8.17 rows=1 width=12)
Index Cond: (c1 = 1)
(2 rows)
H.4.6. Debug Print #
If the pg_hint_plan.debug_print parameter is set to any value other than off, the extension prints debug information with the following hint categories:
used hint: Hints that are successfully parsed by pg_hint_plan, have no syntax errors, and reference valid object definitions. The planner tries to apply these hints to change the query execution plan. However, if an attempt to apply a certain hint fails, the planner ignores this hint and selects any executable plan. For more information, refer to Hints Trying to Enforce Non-Executable Plans. You can check the resulting plan in the EXPLAIN command output.
not used hint: Hints that are parsed by pg_hint_plan but reference invalid object definitions or indexes excluded from planning by the DisableIndex hint.
duplication hint: Hints that are parsed by pg_hint_plan but are redundant or conflicting.
error hint: Hints that cannot be parsed and applied due to incorrect names or any syntax errors.
H.4.7. Errors #
pg_hint_plan stops parsing on any error and uses the already parsed hints. Typical errors are listed below.
H.4.7.1. Syntax Errors #
Any syntactical errors or wrong hint names are reported as syntax errors. These errors are reported in the server log with the message level, which is specified by pg_hint_plan.message_level if pg_hint_plan.debug_print is on or above.
H.4.7.2. Incorrect Object Definitions #
Hints with incorrect object definitions are simply ignored. This kind of error is reported as “Not Used Hint” in the server log.
H.4.7.3. Redundant or Conflicting Hints #
The last hint will take effect in case of redundant or conflicting hints. This kind of error is reported as “Duplication Hint” in the server log under the same conditions as syntax errors.
H.4.7.4. Nested Comments #
A hint comment cannot be recursive. If pg_hint_plan finds it, hint parsing is immediately stopped and all the hints already parsed are ignored.
H.4.8. Functional Limitations #
H.4.8.1. Influences of Planner GUC Parameters #
The planner does not try to consider the joining order for the FROM clause entries more than from_collapse_limit. In such cases pg_hint_plan cannot affect the joining order.
H.4.8.2. Hints Trying to Enforce Non-Executable Plans #
The planner selects any executable plan when the enforced plan cannot be executed.
FULL OUTER JOIN to use nested loop.
Use of indexes that do not have columns used in quals.
TID scans for queries without
ctidconditions.
H.4.8.3. Queries in ECPG #
ECPG removes comments from queries written as embedded SQL, so hints cannot be passed to it. The only exception is the EXECUTE command that passes the query string to the server as is. The hint table can be used in this case.
H.4.8.4. Query Identifiers #
When compute_query_id is enabled, Postgres Pro generates a query ID, ignoring comments. Hence, queries with different hints, still written the same way, may compute the same query ID.
H.4.9. Available Hints #
The available hints are listed below.
Table H.8. Hints List
| Group | Format | Description |
|---|---|---|
| Scan method | SeqScan(table) | Forces the sequential scan on a table. |
TidScan(table) | Forces the TID scan on a table. | |
IndexScan(table[ index...]) | Forces the index scan on a table. Restricts to specified indexes, if any. | |
IndexOnlyScan(table[ index...]) | Forces the index-only scan on a table. Restricts to specified indexes, if any. The index scan may be used if the index-only scan is not available. | |
BitmapScan(table[ index...]) | Forces the bitmap scan on a table. Restricts to specified indexes, if any. | |
IndexScanRegexp(table[ POSIX regexp...]) | Forces the index scan on a table. Restricts to indexes that match the specified POSIX regular expression. | |
IndexOnlyScanRegexp(table[ POSIX regexp...]) | Forces the index-only scan on a table. Restricts to indexes that match the specified POSIX regular expression. | |
BitmapScanRegexp(table[ POSIX regexp...]) | Forces the bitmap scan on a table. Restricts to indexes that match the specified POSIX regular expression. | |
NoSeqScan(table) | Forces the deactivation of the sequential scan on a table. | |
NoTidScan(table) | Forces the deactivation of the TID scan on a table. | |
NoIndexScan(table) | Forces the deactivation of the index scan and index-only scan on a table. | |
NoIndexOnlyScan(table) | Forces the deactivation of the index-only scan on a table. | |
NoBitmapScan(table) | Forces the deactivation of the bitmap scan on a table. | |
| Disable indexes | DisableIndex(table_index...) | Disables the specified indexes during query planning, taking precedence over any other hints. |
| Join method | NestLoop(table table[ table...]) | Forces the nested loop for joins with specified tables. |
HashJoin(table table[ table...]) | Forces the hash join for joins with specified tables. | |
MergeJoin(table table[ table...]) | Forces the merge join for joins with specified tables. | |
NoNestLoop(table table[ table...]) | Forces the deactivation of the nested loop for joins with specified tables. | |
NoHashJoin(table table[ table...]) | Forces the deactivation of the hash join for joins with specified tables. | |
NoMergeJoin(table table[ table...]) | Forces the deactivation of the merge join for joins with specified tables. | |
| Join order | Leading(table table[ table...]) | Forces the join order as specified. |
Leading(<join pair>) | Forces the join order and directions as specified. A join pair is a pair of tables and/or other join pairs enclosed in parentheses, which can make a nested structure. | |
| Control join behavior | Memoize(table table[ table...]) | Allows the topmost join of the joins involving the specified tables to memoize the inner result. Note that it does not enforce memoizing. |
NoMemoize(table table[ table...]) | Disallows the topmost join of the joins involving the specified tables to memoize the inner result. | |
| Row number correction | Rows(table table[ table...] correction) | Corrects row number of a result of the joins with the specified tables. The available correction methods are absolute (#<n>), addition (+<n>), subtraction (-<n>) and multiplication (*<n>). <n> should be a string that strtod() can read. |
| Parallel query configuration | Parallel(table <# of workers> [soft|hard]) | Enforces or inhibits parallel execution of the specified table. <# of workers> is the desired number of parallel workers, where zero means inhibiting parallel execution. If the third parameter is soft (default), it only changes max_parallel_workers_per_gather and leaves everything else to the planner. The hard value enforces the specified number of workers. |
| GUC | Set(GUC-parameter value) | Sets the GUC parameter to the value while the planner is running. |