53.31. pg_stats_ext_exprs #

Представление pg_stats_ext_exprs открывает доступ к информации обо всех выражениях, включённых в объекты расширенной статистики, объединяя данные из каталогов pg_statistic_ext и pg_statistic_ext_data. Это представление даёт доступ только к тем строкам pg_statistic_ext и pg_statistic_ext_data, что соответствуют таблицам, владельцем которых является пользователь: таким образом, это представление можно без опасений разрешить читать всем.

Кроме того, представление pg_stats_ext_exprs специально разработано для подачи информации в более понятном виде, чем нижележащие каталоги — ценой того, что его схему приходится расширять всякий раз, когда изменяется структура содержимого pg_statistic_ext.

Таблица 53.31. Столбцы pg_stats_ext_exprs

Тип столбца

Описание

schemaname name (ссылается на pg_namespace.nspname)

Имя схемы, содержащей таблицу

tablename name (ссылается на pg_class.relname)

Имя таблицы, для которой определён объект статистики

statistics_schemaname name (ссылается на pg_namespace.nspname)

Имя схемы, содержащей объект расширенной статистики

statistics_name name (ссылается на pg_statistic_ext.stxname)

Имя объекта расширенной статистики

statistics_owner name (ссылается на pg_authid.rolname)

Владелец объекта расширенной статистики

expr text

Выражение, включённое в объект расширенной статистики

inherited bool (ссылается на pg_statistic_ext_data.stxdinherit)

Если true, в статистике учитываются значения в дочерних таблицах, а не только в указанном отношении

null_frac float4

Доля записей, в которых это выражение содержит NULL

avg_width int4

Средний размер элементов в выражении, в байтах

n_distinct float4

Число больше нуля представляет примерное количество различных значений в выражении. Если это число меньше нуля, его модуль представляет количество различных значений, делённое на количество строк. (Отрицательная форма применяется, когда ANALYZE полагает, что число различных значений, скорее всего, будет расти по мере роста таблицы; положительная, когда в выражении, вероятно, будет фиксированное количество возможных значений.) Например, -1 указывает на выражение с уникальным содержимым, в котором количество различных значений совпадает с количеством строк.

most_common_vals anyarray

Список самых частых значений в выражении. (NULL, если не находятся значения, встречающиеся чаще других.)

most_common_freqs float4[]

Список частот самых частых значений, то есть число их вхождений, делённое на общее количество строк. (NULL, когда most_common_vals — NULL.)

histogram_bounds anyarray

Список значений, разделяющих значения выражения на примерно одинаковые популяции. Значения most_common_vals, если они присутствуют, не рассматриваются при вычислении этой гистограммы. (Это выражение содержит NULL, если для типа данных выражения не определён оператор <, либо если в most_common_vals перечисляется вся популяция.)

correlation float4

Статистическая корреляция между физическим порядком строк и логическим порядком значений выражения. Допустимые значения лежат в диапазоне -1 .. +1. Когда значение около -1 или +1, сканирование индекса по выражению будет считаться дешевле, чем когда это значение около нуля, как результат уменьшения случайного доступа к диску. (Это выражение содержит NULL, если для типа данных выражения не определён оператор <.)

most_common_elems anyarray

Список элементов, отличных от NULL, наиболее часто присутствующих в значениях выражения. (NULL для скалярных типов.)

most_common_elem_freqs float4[]

Список частот самых частых элементов, то есть доля строк, содержащих минимум один экземпляр данного значения. За частотами по элементам следуют два или три дополнительных значения: минимум и максимум предшествующих частот по элементам и дополнительно частота элементов NULL. (Принимает значение NULL, когда most_common_elems — NULL.)

elem_count_histogram float4[]

Гистограмма количеств различных и отличных от NULL элементов в значениях этого выражения, за которой следует среднее количество элементов, отличных от NULL. (Принимает значение NULL для скалярных типов.)


Максимальным числом записей в полях-массивах можно управлять на уровне столбцов, используя команду ALTER TABLE SET STATISTICS, или глобально, задав параметр времени выполнения default_statistics_target.

53.31. pg_stats_ext_exprs #

The view pg_stats_ext_exprs provides access to information about all expressions included in extended statistics objects, combining information stored in the pg_statistic_ext and pg_statistic_ext_data catalogs. This view allows access only to rows of pg_statistic_ext and pg_statistic_ext_data that correspond to tables the user owns, and therefore it is safe to allow public read access to this view.

pg_stats_ext_exprs is also designed to present the information in a more readable format than the underlying catalogs — at the cost that its schema must be extended whenever the structure of statistics in pg_statistic_ext changes.

Table 53.31. pg_stats_ext_exprs Columns

Column Type

Description

schemaname name (references pg_namespace.nspname)

Name of schema containing table

tablename name (references pg_class.relname)

Name of table the statistics object is defined on

statistics_schemaname name (references pg_namespace.nspname)

Name of schema containing extended statistics object

statistics_name name (references pg_statistic_ext.stxname)

Name of extended statistics object

statistics_owner name (references pg_authid.rolname)

Owner of the extended statistics object

expr text

Expression included in the extended statistics object

inherited bool (references pg_statistic_ext_data.stxdinherit)

If true, the stats include values from child tables, not just the values in the specified relation

null_frac float4

Fraction of expression entries that are null

avg_width int4

Average width in bytes of expression's entries

n_distinct float4

If greater than zero, the estimated number of distinct values in the expression. If less than zero, the negative of the number of distinct values divided by the number of rows. (The negated form is used when ANALYZE believes that the number of distinct values is likely to increase as the table grows; the positive form is used when the expression seems to have a fixed number of possible values.) For example, -1 indicates a unique expression in which the number of distinct values is the same as the number of rows.

most_common_vals anyarray

A list of the most common values in the expression. (Null if no values seem to be more common than any others.)

most_common_freqs float4[]

A list of the frequencies of the most common values, i.e., number of occurrences of each divided by total number of rows. (Null when most_common_vals is.)

histogram_bounds anyarray

A list of values that divide the expression's values into groups of approximately equal population. The values in most_common_vals, if present, are omitted from this histogram calculation. (This expression is null if the expression data type does not have a < operator or if the most_common_vals list accounts for the entire population.)

correlation float4

Statistical correlation between physical row ordering and logical ordering of the expression values. This ranges from -1 to +1. When the value is near -1 or +1, an index scan on the expression will be estimated to be cheaper than when it is near zero, due to reduction of random access to the disk. (This expression is null if the expression's data type does not have a < operator.)

most_common_elems anyarray

A list of non-null element values most often appearing within values of the expression. (Null for scalar types.)

most_common_elem_freqs float4[]

A list of the frequencies of the most common element values, i.e., the fraction of rows containing at least one instance of the given value. Two or three additional values follow the per-element frequencies; these are the minimum and maximum of the preceding per-element frequencies, and optionally the frequency of null elements. (Null when most_common_elems is.)

elem_count_histogram float4[]

A histogram of the counts of distinct non-null element values within the values of the expression, followed by the average number of distinct non-null elements. (Null for scalar types.)


The maximum number of entries in the array fields can be controlled on a column-by-column basis using the ALTER TABLE SET STATISTICS command, or globally by setting the default_statistics_target run-time parameter.

FAQ