/
Ao
/
MaxReport
Обзор
Документация
Войти
/
Ao
/
MaxReport
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
pgsql/doc/src/sgml/html/btree.html
695 строк
48 KB
AoAnima
first_commit
13 июл 2026, 17:47
13 июл 2026, 17:47
f1a670a
Код
Авторство
О чём код?
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>65.1. B-Tree Indexes</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="indextypes.html" title="Chapter 65. Built-in Index Access Methods" /><link rel="next" href="gist.html" title="65.2. GiST Indexes" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">65.1. B-Tree Indexes</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="indextypes.html" title="Chapter 65. Built-in Index Access Methods">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="indextypes.html" title="Chapter 65. Built-in Index Access Methods">Up</a></td><th width="60%" align="center">Chapter 65. Built-in Index Access Methods</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="gist.html" title="65.2. GiST Indexes">Next</a></td></tr></table><hr /></div><div class="sect1" id="BTREE"><div class="titlepage"><div><div><h2 class="title" style="clear: both">65.1. B-Tree Indexes <a href="#BTREE" class="id_link">#</a></h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="btree.html#BTREE-INTRO">65.1.1. Introduction</a></span></dt><dt><span class="sect2"><a href="btree.html#BTREE-BEHAVIOR">65.1.2. Behavior of B-Tree Operator Classes</a></span></dt><dt><span class="sect2"><a href="btree.html#BTREE-SUPPORT-FUNCS">65.1.3. B-Tree Support Functions</a></span></dt><dt><span class="sect2"><a href="btree.html#BTREE-IMPLEMENTATION">65.1.4. Implementation</a></span></dt></dl></div><a id="id-1.10.17.2.2" class="indexterm"></a><div class="sect2" id="BTREE-INTRO"><div class="titlepage"><div><div><h3 class="title">65.1.1. Introduction <a href="#BTREE-INTRO" class="id_link">#</a></h3></div></div></div><p> <span class="productname">PostgreSQL</span> includes an implementation of the standard <acronym class="acronym">btree</acronym> (multi-way balanced tree) index data structure. Any data type that can be sorted into a well-defined linear order can be indexed by a btree index. The only limitation is that an index entry cannot exceed approximately one-third of a page (after TOAST compression, if applicable). </p><p> Because each btree operator class imposes a sort order on its data type, btree operator classes (or, really, operator families) have come to be used as <span class="productname">PostgreSQL</span>'s general representation and understanding of sorting semantics. Therefore, they've acquired some features that go beyond what would be needed just to support btree indexes, and parts of the system that are quite distant from the btree <acronym class="acronym">AM</acronym> make use of them. </p></div><div class="sect2" id="BTREE-BEHAVIOR"><div class="titlepage"><div><div><h3 class="title">65.1.2. Behavior of B-Tree Operator Classes <a href="#BTREE-BEHAVIOR" class="id_link">#</a></h3></div></div></div><p> As shown in <a class="xref" href="xindex.html#XINDEX-BTREE-STRAT-TABLE" title="Table 36.3. B-Tree Strategies">Table 36.3</a>, a btree operator class must provide five comparison operators, <code class="literal"><</code>, <code class="literal"><=</code>, <code class="literal">=</code>, <code class="literal">>=</code> and <code class="literal">></code>. One might expect that <code class="literal"><></code> should also be part of the operator class, but it is not, because it would almost never be useful to use a <code class="literal"><></code> WHERE clause in an index search. (For some purposes, the planner treats <code class="literal"><></code> as associated with a btree operator class; but it finds that operator via the <code class="literal">=</code> operator's negator link, rather than from <code class="structname">pg_amop</code>.) </p><p> When several data types share near-identical sorting semantics, their operator classes can be grouped into an operator family. Doing so is advantageous because it allows the planner to make deductions about cross-type comparisons. Each operator class within the family should contain the single-type operators (and associated support functions) for its input data type, while cross-type comparison operators and support functions are <span class="quote">“<span class="quote">loose</span>”</span> in the family. It is recommendable that a complete set of cross-type operators be included in the family, thus ensuring that the planner can represent any comparison conditions that it deduces from transitivity. </p><p> There are some basic assumptions that a btree operator family must satisfy: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> An <code class="literal">=</code> operator must be an equivalence relation; that is, for all non-null values <em class="replaceable"><code>A</code></em>, <em class="replaceable"><code>B</code></em>, <em class="replaceable"><code>C</code></em> of the data type: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p> <em class="replaceable"><code>A</code></em> <code class="literal">=</code> <em class="replaceable"><code>A</code></em> is true (<em class="firstterm">reflexive law</em>) </p></li><li class="listitem"><p> if <em class="replaceable"><code>A</code></em> <code class="literal">=</code> <em class="replaceable"><code>B</code></em>, then <em class="replaceable"><code>B</code></em> <code class="literal">=</code> <em class="replaceable"><code>A</code></em> (<em class="firstterm">symmetric law</em>) </p></li><li class="listitem"><p> if <em class="replaceable"><code>A</code></em> <code class="literal">=</code> <em class="replaceable"><code>B</code></em> and <em class="replaceable"><code>B</code></em> <code class="literal">=</code> <em class="replaceable"><code>C</code></em>, then <em class="replaceable"><code>A</code></em> <code class="literal">=</code> <em class="replaceable"><code>C</code></em> (<em class="firstterm">transitive law</em>) </p></li></ul></div><p> </p></li><li class="listitem"><p> A <code class="literal"><</code> operator must be a strong ordering relation; that is, for all non-null values <em class="replaceable"><code>A</code></em>, <em class="replaceable"><code>B</code></em>, <em class="replaceable"><code>C</code></em>: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p> <em class="replaceable"><code>A</code></em> <code class="literal"><</code> <em class="replaceable"><code>A</code></em> is false (<em class="firstterm">irreflexive law</em>) </p></li><li class="listitem"><p> if <em class="replaceable"><code>A</code></em> <code class="literal"><</code> <em class="replaceable"><code>B</code></em> and <em class="replaceable"><code>B</code></em> <code class="literal"><</code> <em class="replaceable"><code>C</code></em>, then <em class="replaceable"><code>A</code></em> <code class="literal"><</code> <em class="replaceable"><code>C</code></em> (<em class="firstterm">transitive law</em>) </p></li></ul></div><p> </p></li><li class="listitem"><p> Furthermore, the ordering is total; that is, for all non-null values <em class="replaceable"><code>A</code></em>, <em class="replaceable"><code>B</code></em>: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: circle; "><li class="listitem"><p> exactly one of <em class="replaceable"><code>A</code></em> <code class="literal"><</code> <em class="replaceable"><code>B</code></em>, <em class="replaceable"><code>A</code></em> <code class="literal">=</code> <em class="replaceable"><code>B</code></em>, and <em class="replaceable"><code>B</code></em> <code class="literal"><</code> <em class="replaceable"><code>A</code></em> is true (<em class="firstterm">trichotomy law</em>) </p></li></ul></div><p> (The trichotomy law justifies the definition of the comparison support function, of course.) </p></li></ul></div><p> The other three operators are defined in terms of <code class="literal">=</code> and <code class="literal"><</code> in the obvious way, and must act consistently with them. </p><p> For an operator family supporting multiple data types, the above laws must hold when <em class="replaceable"><code>A</code></em>, <em class="replaceable"><code>B</code></em>, <em class="replaceable"><code>C</code></em> are taken from any data types in the family. The transitive laws are the trickiest to ensure, as in cross-type situations they represent statements that the behaviors of two or three different operators are consistent. As an example, it would not work to put <code class="type">float8</code> and <code class="type">numeric</code> into the same operator family, at least not with the current semantics that <code class="type">numeric</code> values are converted to <code class="type">float8</code> for comparison to a <code class="type">float8</code>. Because of the limited accuracy of <code class="type">float8</code>, this means there are distinct <code class="type">numeric</code> values that will compare equal to the same <code class="type">float8</code> value, and thus the transitive law would fail. </p><p> Another requirement for a multiple-data-type family is that any implicit or binary-coercion casts that are defined between data types included in the operator family must not change the associated sort ordering. </p><p> It should be fairly clear why a btree index requires these laws to hold within a single data type: without them there is no ordering to arrange the keys with. Also, index searches using a comparison key of a different data type require comparisons to behave sanely across two data types. The extensions to three or more data types within a family are not strictly required by the btree index mechanism itself, but the planner relies on them for optimization purposes. </p></div><div class="sect2" id="BTREE-SUPPORT-FUNCS"><div class="titlepage"><div><div><h3 class="title">65.1.3. B-Tree Support Functions <a href="#BTREE-SUPPORT-FUNCS" class="id_link">#</a></h3></div></div></div><p> As shown in <a class="xref" href="xindex.html#XINDEX-BTREE-SUPPORT-TABLE" title="Table 36.9. B-Tree Support Functions">Table 36.9</a>, btree defines one required and five optional support functions. The six user-defined methods are: </p><div class="variablelist"><dl class="variablelist"><dt><span class="term"><code class="function">order</code></span></dt><dd><p> For each combination of data types that a btree operator family provides comparison operators for, it must provide a comparison support function, registered in <code class="structname">pg_amproc</code> with support function number 1 and <code class="structfield">amproclefttype</code>/<code class="structfield">amprocrighttype</code> equal to the left and right data types for the comparison (i.e., the same data types that the matching operators are registered with in <code class="structname">pg_amop</code>). The comparison function must take two non-null values <em class="replaceable"><code>A</code></em> and <em class="replaceable"><code>B</code></em> and return an <code class="type">int32</code> value that is <code class="literal"><</code> <code class="literal">0</code>, <code class="literal">0</code>, or <code class="literal">></code> <code class="literal">0</code> when <em class="replaceable"><code>A</code></em> <code class="literal"><</code> <em class="replaceable"><code>B</code></em>, <em class="replaceable"><code>A</code></em> <code class="literal">=</code> <em class="replaceable"><code>B</code></em>, or <em class="replaceable"><code>A</code></em> <code class="literal">></code> <em class="replaceable"><code>B</code></em>, respectively. A null result is disallowed: all values of the data type must be comparable. See <code class="filename">src/backend/access/nbtree/nbtcompare.c</code> for examples. </p><p> If the compared values are of a collatable data type, the appropriate collation OID will be passed to the comparison support function, using the standard <code class="function">PG_GET_COLLATION()</code> mechanism. </p></dd><dt><span class="term"><code class="function">sortsupport</code></span></dt><dd><p> Optionally, a btree operator family may provide <em class="firstterm">sort support</em> function(s), registered under support function number 2. These functions allow implementing comparisons for sorting purposes in a more efficient way than naively calling the comparison support function. The APIs involved in this are defined in <code class="filename">src/include/utils/sortsupport.h</code>. </p></dd><dt><span class="term"><code class="function">in_range</code></span></dt><dd><a id="id-1.10.17.2.5.3.3.2.1" class="indexterm"></a><a id="id-1.10.17.2.5.3.3.2.2" class="indexterm"></a><p> Optionally, a btree operator family may provide <em class="firstterm">in_range</em> support function(s), registered under support function number 3. These are not used during btree index operations; rather, they extend the semantics of the operator family so that it can support window clauses containing the <code class="literal">RANGE</code> <em class="replaceable"><code>offset</code></em> <code class="literal">PRECEDING</code> and <code class="literal">RANGE</code> <em class="replaceable"><code>offset</code></em> <code class="literal">FOLLOWING</code> frame bound types (see <a class="xref" href="sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS" title="4.2.8. Window Function Calls">Section 4.2.8</a>). Fundamentally, the extra information provided is how to add or subtract an <em class="replaceable"><code>offset</code></em> value in a way that is compatible with the family's data ordering. </p><p> An <code class="function">in_range</code> function must have the signature </p><pre class="synopsis"> in_range(<em class="replaceable"><code>val</code></em> type1, <em class="replaceable"><code>base</code></em> type1, <em class="replaceable"><code>offset</code></em> type2, <em class="replaceable"><code>sub</code></em> bool, <em class="replaceable"><code>less</code></em> bool) returns bool </pre><p> <em class="replaceable"><code>val</code></em> and <em class="replaceable"><code>base</code></em> must be of the same type, which is one of the types supported by the operator family (i.e., a type for which it provides an ordering). However, <em class="replaceable"><code>offset</code></em> could be of a different type, which might be one otherwise unsupported by the family. An example is that the built-in <code class="literal">time_ops</code> family provides an <code class="function">in_range</code> function that has <em class="replaceable"><code>offset</code></em> of type <code class="type">interval</code>. A family can provide <code class="function">in_range</code> functions for any of its supported types and one or more <em class="replaceable"><code>offset</code></em> types. Each <code class="function">in_range</code> function should be entered in <code class="structname">pg_amproc</code> with <code class="structfield">amproclefttype</code> equal to <code class="type">type1</code> and <code class="structfield">amprocrighttype</code> equal to <code class="type">type2</code>. </p><p> The essential semantics of an <code class="function">in_range</code> function depend on the two Boolean flag parameters. It should add or subtract <em class="replaceable"><code>base</code></em> and <em class="replaceable"><code>offset</code></em>, then compare <em class="replaceable"><code>val</code></em> to the result, as follows: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> if <code class="literal">!</code><em class="replaceable"><code>sub</code></em> and <code class="literal">!</code><em class="replaceable"><code>less</code></em>, return <em class="replaceable"><code>val</code></em> <code class="literal">>=</code> (<em class="replaceable"><code>base</code></em> <code class="literal">+</code> <em class="replaceable"><code>offset</code></em>) </p></li><li class="listitem"><p> if <code class="literal">!</code><em class="replaceable"><code>sub</code></em> and <em class="replaceable"><code>less</code></em>, return <em class="replaceable"><code>val</code></em> <code class="literal"><=</code> (<em class="replaceable"><code>base</code></em> <code class="literal">+</code> <em class="replaceable"><code>offset</code></em>) </p></li><li class="listitem"><p> if <em class="replaceable"><code>sub</code></em> and <code class="literal">!</code><em class="replaceable"><code>less</code></em>, return <em class="replaceable"><code>val</code></em> <code class="literal">>=</code> (<em class="replaceable"><code>base</code></em> <code class="literal">-</code> <em class="replaceable"><code>offset</code></em>) </p></li><li class="listitem"><p> if <em class="replaceable"><code>sub</code></em> and <em class="replaceable"><code>less</code></em>, return <em class="replaceable"><code>val</code></em> <code class="literal"><=</code> (<em class="replaceable"><code>base</code></em> <code class="literal">-</code> <em class="replaceable"><code>offset</code></em>) </p></li></ul></div><p> Before doing so, the function should check the sign of <em class="replaceable"><code>offset</code></em>: if it is less than zero, raise error <code class="literal">ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE</code> (22013) with error text like <span class="quote">“<span class="quote">invalid preceding or following size in window function</span>”</span>. (This is required by the SQL standard, although nonstandard operator families might perhaps choose to ignore this restriction, since there seems to be little semantic necessity for it.) This requirement is delegated to the <code class="function">in_range</code> function so that the core code needn't understand what <span class="quote">“<span class="quote">less than zero</span>”</span> means for a particular data type. </p><p> An additional expectation is that <code class="function">in_range</code> functions should, if practical, avoid throwing an error if <em class="replaceable"><code>base</code></em> <code class="literal">+</code> <em class="replaceable"><code>offset</code></em> or <em class="replaceable"><code>base</code></em> <code class="literal">-</code> <em class="replaceable"><code>offset</code></em> would overflow. The correct comparison result can be determined even if that value would be out of the data type's range. Note that if the data type includes concepts such as <span class="quote">“<span class="quote">infinity</span>”</span> or <span class="quote">“<span class="quote">NaN</span>”</span>, extra care may be needed to ensure that <code class="function">in_range</code>'s results agree with the normal sort order of the operator family. </p><p> The results of the <code class="function">in_range</code> function must be consistent with the sort ordering imposed by the operator family. To be precise, given any fixed values of <em class="replaceable"><code>offset</code></em> and <em class="replaceable"><code>sub</code></em>, then: </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> If <code class="function">in_range</code> with <em class="replaceable"><code>less</code></em> = true is true for some <em class="replaceable"><code>val1</code></em> and <em class="replaceable"><code>base</code></em>, it must be true for every <em class="replaceable"><code>val2</code></em> <code class="literal"><=</code> <em class="replaceable"><code>val1</code></em> with the same <em class="replaceable"><code>base</code></em>. </p></li><li class="listitem"><p> If <code class="function">in_range</code> with <em class="replaceable"><code>less</code></em> = true is false for some <em class="replaceable"><code>val1</code></em> and <em class="replaceable"><code>base</code></em>, it must be false for every <em class="replaceable"><code>val2</code></em> <code class="literal">>=</code> <em class="replaceable"><code>val1</code></em> with the same <em class="replaceable"><code>base</code></em>. </p></li><li class="listitem"><p> If <code class="function">in_range</code> with <em class="replaceable"><code>less</code></em> = true is true for some <em class="replaceable"><code>val</code></em> and <em class="replaceable"><code>base1</code></em>, it must be true for every <em class="replaceable"><code>base2</code></em> <code class="literal">>=</code> <em class="replaceable"><code>base1</code></em> with the same <em class="replaceable"><code>val</code></em>. </p></li><li class="listitem"><p> If <code class="function">in_range</code> with <em class="replaceable"><code>less</code></em> = true is false for some <em class="replaceable"><code>val</code></em> and <em class="replaceable"><code>base1</code></em>, it must be false for every <em class="replaceable"><code>base2</code></em> <code class="literal"><=</code> <em class="replaceable"><code>base1</code></em> with the same <em class="replaceable"><code>val</code></em>. </p></li></ul></div><p> Analogous statements with inverted conditions hold when <em class="replaceable"><code>less</code></em> = false. </p><p> If the type being ordered (<code class="type">type1</code>) is collatable, the appropriate collation OID will be passed to the <code class="function">in_range</code> function, using the standard PG_GET_COLLATION() mechanism. </p><p> <code class="function">in_range</code> functions need not handle NULL inputs, and typically will be marked strict. </p></dd><dt><span class="term"><code class="function">equalimage</code></span></dt><dd><p> Optionally, a btree operator family may provide <code class="function">equalimage</code> (<span class="quote">“<span class="quote">equality implies image equality</span>”</span>) support functions, registered under support function number 4. These functions allow the core code to determine when it is safe to apply the btree deduplication optimization. Currently, <code class="function">equalimage</code> functions are only called when building or rebuilding an index. </p><p> An <code class="function">equalimage</code> function must have the signature </p><pre class="synopsis"> equalimage(<em class="replaceable"><code>opcintype</code></em> <code class="type">oid</code>) returns bool </pre><p> The return value is static information about an operator class and collation. Returning <code class="literal">true</code> indicates that the <code class="function">order</code> function for the operator class is guaranteed to only return <code class="literal">0</code> (<span class="quote">“<span class="quote">arguments are equal</span>”</span>) when its <em class="replaceable"><code>A</code></em> and <em class="replaceable"><code>B</code></em> arguments are also interchangeable without any loss of semantic information. Not registering an <code class="function">equalimage</code> function or returning <code class="literal">false</code> indicates that this condition cannot be assumed to hold. </p><p> The <em class="replaceable"><code>opcintype</code></em> argument is the <code class="literal"><code class="structname">pg_type</code>.oid</code> of the data type that the operator class indexes. This is a convenience that allows reuse of the same underlying <code class="function">equalimage</code> function across operator classes. If <em class="replaceable"><code>opcintype</code></em> is a collatable data type, the appropriate collation OID will be passed to the <code class="function">equalimage</code> function, using the standard <code class="function">PG_GET_COLLATION()</code> mechanism. </p><p> As far as the operator class is concerned, returning <code class="literal">true</code> indicates that deduplication is safe (or safe for the collation whose OID was passed to its <code class="function">equalimage</code> function). However, the core code will only deem deduplication safe for an index when <span class="emphasis"><em>every</em></span> indexed column uses an operator class that registers an <code class="function">equalimage</code> function, and each function actually returns <code class="literal">true</code> when called. </p><p> Image equality is <span class="emphasis"><em>almost</em></span> the same condition as simple bitwise equality. There is one subtle difference: When indexing a varlena data type, the on-disk representation of two image equal datums may not be bitwise equal due to inconsistent application of <acronym class="acronym">TOAST</acronym> compression on input. Formally, when an operator class's <code class="function">equalimage</code> function returns <code class="literal">true</code>, it is safe to assume that the <code class="literal">datum_image_eq()</code> C function will always agree with the operator class's <code class="function">order</code> function (provided that the same collation OID is passed to both the <code class="function">equalimage</code> and <code class="function">order</code> functions). </p><p> The core code is fundamentally unable to deduce anything about the <span class="quote">“<span class="quote">equality implies image equality</span>”</span> status of an operator class within a multiple-data-type family based on details from other operator classes in the same family. Also, it is not sensible for an operator family to register a cross-type <code class="function">equalimage</code> function, and attempting to do so will result in an error. This is because <span class="quote">“<span class="quote">equality implies image equality</span>”</span> status does not just depend on sorting/equality semantics, which are more or less defined at the operator family level. In general, the semantics that one particular data type implements must be considered separately. </p><p> The convention followed by the operator classes included with the core <span class="productname">PostgreSQL</span> distribution is to register a stock, generic <code class="function">equalimage</code> function. Most operator classes register <code class="function">btequalimage()</code>, which indicates that deduplication is safe unconditionally. Operator classes for collatable data types such as <code class="type">text</code> register <code class="function">btvarstrequalimage()</code>, which indicates that deduplication is safe with deterministic collations. Best practice for third-party extensions is to register their own custom function to retain control. </p></dd><dt><span class="term"><code class="function">options</code></span></dt><dd><p> Optionally, a B-tree operator family may provide <code class="function">options</code> (<span class="quote">“<span class="quote">operator class specific options</span>”</span>) support functions, registered under support function number 5. These functions define a set of user-visible parameters that control operator class behavior. </p><p> An <code class="function">options</code> support function must have the signature </p><pre class="synopsis"> options(<em class="replaceable"><code>relopts</code></em> <code class="type">local_relopts *</code>) returns void </pre><p> The function is passed a pointer to a <code class="structname">local_relopts</code> struct, which needs to be filled with a set of operator class specific options. The options can be accessed from other support functions using the <code class="literal">PG_HAS_OPCLASS_OPTIONS()</code> and <code class="literal">PG_GET_OPCLASS_OPTIONS()</code> macros. </p><p> Currently, no B-Tree operator class has an <code class="function">options</code> support function. B-tree doesn't allow flexible representation of keys like GiST, SP-GiST, GIN and BRIN do. So, <code class="function">options</code> probably doesn't have much application in the current B-tree index access method. Nevertheless, this support function was added to B-tree for uniformity, and will probably find uses during further evolution of B-tree in <span class="productname">PostgreSQL</span>. </p></dd><dt><span class="term"><code class="function">skipsupport</code></span></dt><dd><p> Optionally, a btree operator family may provide a <em class="firstterm">skip support</em> function, registered under support function number 6. These functions give the B-tree code a way to iterate through every possible value that can be represented by an operator class's underlying input type, in key space order. This is used by the core code when it applies the skip scan optimization. The APIs involved in this are defined in <code class="filename">src/include/utils/skipsupport.h</code>. </p><p> Operator classes that do not provide a skip support function are still eligible to use skip scan. The core code can still use its fallback strategy, though that might be suboptimal for some discrete types. It usually doesn't make sense (and may not even be feasible) for operator classes on continuous types to provide a skip support function. </p><p> It is not sensible for an operator family to register a cross-type <code class="function">skipsupport</code> function, and attempting to do so will result in an error. This is because determining the next indexable value must happen by incrementing a value copied from an index tuple. The values generated must all be of the same underlying data type (the <span class="quote">“<span class="quote">skipped</span>”</span> index column's opclass input type). </p></dd></dl></div></div><div class="sect2" id="BTREE-IMPLEMENTATION"><div class="titlepage"><div><div><h3 class="title">65.1.4. Implementation <a href="#BTREE-IMPLEMENTATION" class="id_link">#</a></h3></div></div></div><p> This section covers B-Tree index implementation details that may be of use to advanced users. See <code class="filename">src/backend/access/nbtree/README</code> in the source distribution for a much more detailed, internals-focused description of the B-Tree implementation. </p><div class="sect3" id="BTREE-STRUCTURE"><div class="titlepage"><div><div><h4 class="title">65.1.4.1. B-Tree Structure <a href="#BTREE-STRUCTURE" class="id_link">#</a></h4></div></div></div><p> <span class="productname">PostgreSQL</span> B-Tree indexes are multi-level tree structures, where each level of the tree can be used as a doubly-linked list of pages. A single metapage is stored in a fixed position at the start of the first segment file of the index. All other pages are either leaf pages or internal pages. Leaf pages are the pages on the lowest level of the tree. All other levels consist of internal pages. Each leaf page contains tuples that point to table rows. Each internal page contains tuples that point to the next level down in the tree. Typically, over 99% of all pages are leaf pages. Both internal pages and leaf pages use the standard page format described in <a class="xref" href="storage-page-layout.html" title="66.6. Database Page Layout">Section 66.6</a>. </p><p> New leaf pages are added to a B-Tree index when an existing leaf page cannot fit an incoming tuple. A <em class="firstterm">page split</em> operation makes room for items that originally belonged on the overflowing page by moving a portion of the items to a new page. Page splits must also insert a new <em class="firstterm">downlink</em> to the new page in the parent page, which may cause the parent to split in turn. Page splits <span class="quote">“<span class="quote">cascade upwards</span>”</span> in a recursive fashion. When the root page finally cannot fit a new downlink, a <em class="firstterm">root page split</em> operation takes place. This adds a new level to the tree structure by creating a new root page that is one level above the original root page. </p></div><div class="sect3" id="BTREE-DELETION"><div class="titlepage"><div><div><h4 class="title">65.1.4.2. Bottom-up Index Deletion <a href="#BTREE-DELETION" class="id_link">#</a></h4></div></div></div><p> B-Tree indexes are not directly aware that under MVCC, there might be multiple extant versions of the same logical table row; to an index, each tuple is an independent object that needs its own index entry. <span class="quote">“<span class="quote">Version churn</span>”</span> tuples may sometimes accumulate and adversely affect query latency and throughput. This typically occurs with <code class="command">UPDATE</code>-heavy workloads where most individual updates cannot apply the <a class="link" href="storage-hot.html" title="66.7. Heap-Only Tuples (HOT)"><acronym class="acronym">HOT</acronym> optimization.</a> Changing the value of only one column covered by one index during an <code class="command">UPDATE</code> <span class="emphasis"><em>always</em></span> necessitates a new set of index tuples — one for <span class="emphasis"><em>each and every</em></span> index on the table. Note in particular that this includes indexes that were not <span class="quote">“<span class="quote">logically modified</span>”</span> by the <code class="command">UPDATE</code>. All indexes will need a successor physical index tuple that points to the latest version in the table. Each new tuple within each index will generally need to coexist with the original <span class="quote">“<span class="quote">updated</span>”</span> tuple for a short period of time (typically until shortly after the <code class="command">UPDATE</code> transaction commits). </p><p> B-Tree indexes incrementally delete version churn index tuples by performing <em class="firstterm">bottom-up index deletion</em> passes. Each deletion pass is triggered in reaction to an anticipated <span class="quote">“<span class="quote">version churn page split</span>”</span>. This only happens with indexes that are not logically modified by <code class="command">UPDATE</code> statements, where concentrated build up of obsolete versions in particular pages would occur otherwise. A page split will usually be avoided, though it's possible that certain implementation-level heuristics will fail to identify and delete even one garbage index tuple (in which case a page split or deduplication pass resolves the issue of an incoming new tuple not fitting on a leaf page). The worst-case number of versions that any index scan must traverse (for any single logical row) is an important contributor to overall system responsiveness and throughput. A bottom-up index deletion pass targets suspected garbage tuples in a single leaf page based on <span class="emphasis"><em>qualitative</em></span> distinctions involving logical rows and versions. This contrasts with the <span class="quote">“<span class="quote">top-down</span>”</span> index cleanup performed by autovacuum workers, which is triggered when certain <span class="emphasis"><em>quantitative</em></span> table-level thresholds are exceeded (see <a class="xref" href="routine-vacuuming.html#AUTOVACUUM" title="24.1.6. The Autovacuum Daemon">Section 24.1.6</a>). </p><div class="note"><h3 class="title">Note</h3><p> Not all deletion operations that are performed within B-Tree indexes are bottom-up deletion operations. There is a distinct category of index tuple deletion: <em class="firstterm">simple index tuple deletion</em>. This is a deferred maintenance operation that deletes index tuples that are known to be safe to delete (those whose item identifier's <code class="literal">LP_DEAD</code> bit is already set). Like bottom-up index deletion, simple index deletion takes place at the point that a page split is anticipated as a way of avoiding the split. </p><p> Simple deletion is opportunistic in the sense that it can only take place when recent index scans set the <code class="literal">LP_DEAD</code> bits of affected items in passing. Prior to <span class="productname">PostgreSQL</span> 14, the only category of B-Tree deletion was simple deletion. The main differences between it and bottom-up deletion are that only the former is opportunistically driven by the activity of passing index scans, while only the latter specifically targets version churn from <code class="command">UPDATE</code>s that do not logically modify indexed columns. </p></div><p> Bottom-up index deletion performs the vast majority of all garbage index tuple cleanup for particular indexes with certain workloads. This is expected with any B-Tree index that is subject to significant version churn from <code class="command">UPDATE</code>s that rarely or never logically modify the columns that the index covers. The average and worst-case number of versions per logical row can be kept low purely through targeted incremental deletion passes. It's quite possible that the on-disk size of certain indexes will never increase by even one single page/block despite <span class="emphasis"><em>constant</em></span> version churn from <code class="command">UPDATE</code>s. Even then, an exhaustive <span class="quote">“<span class="quote">clean sweep</span>”</span> by a <code class="command">VACUUM</code> operation (typically run in an autovacuum worker process) will eventually be required as a part of <span class="emphasis"><em>collective</em></span> cleanup of the table and each of its indexes. </p><p> Unlike <code class="command">VACUUM</code>, bottom-up index deletion does not provide any strong guarantees about how old the oldest garbage index tuple may be. No index can be permitted to retain <span class="quote">“<span class="quote">floating garbage</span>”</span> index tuples that became dead prior to a conservative cutoff point shared by the table and all of its indexes collectively. This fundamental table-level invariant makes it safe to recycle table <acronym class="acronym">TID</acronym>s. This is how it is possible for distinct logical rows to reuse the same table <acronym class="acronym">TID</acronym> over time (though this can never happen with two logical rows whose lifetimes span the same <code class="command">VACUUM</code> cycle). </p></div><div class="sect3" id="BTREE-DEDUPLICATION"><div class="titlepage"><div><div><h4 class="title">65.1.4.3. Deduplication <a href="#BTREE-DEDUPLICATION" class="id_link">#</a></h4></div></div></div><p> A duplicate is a leaf page tuple (a tuple that points to a table row) where <span class="emphasis"><em>all</em></span> indexed key columns have values that match corresponding column values from at least one other leaf page tuple in the same index. Duplicate tuples are quite common in practice. B-Tree indexes can use a special, space-efficient representation for duplicates when an optional technique is enabled: <em class="firstterm">deduplication</em>. </p><p> Deduplication works by periodically merging groups of duplicate tuples together, forming a single <em class="firstterm">posting list</em> tuple for each group. The column key value(s) only appear once in this representation. This is followed by a sorted array of <acronym class="acronym">TID</acronym>s that point to rows in the table. This significantly reduces the storage size of indexes where each value (or each distinct combination of column values) appears several times on average. The latency of queries can be reduced significantly. Overall query throughput may increase significantly. The overhead of routine index vacuuming may also be reduced significantly. </p><div class="note"><h3 class="title">Note</h3><p> B-Tree deduplication is just as effective with <span class="quote">“<span class="quote">duplicates</span>”</span> that contain a NULL value, even though NULL values are never equal to each other according to the <code class="literal">=</code> member of any B-Tree operator class. As far as any part of the implementation that understands the on-disk B-Tree structure is concerned, NULL is just another value from the domain of indexed values. </p></div><p> The deduplication process occurs lazily, when a new item is inserted that cannot fit on an existing leaf page, though only when index tuple deletion could not free sufficient space for the new item (typically deletion is briefly considered and then skipped over). Unlike GIN posting list tuples, B-Tree posting list tuples do not need to expand every time a new duplicate is inserted; they are merely an alternative physical representation of the original logical contents of the leaf page. This design prioritizes consistent performance with mixed read-write workloads. Most client applications will at least see a moderate performance benefit from using deduplication. Deduplication is enabled by default. </p><p> <code class="command">CREATE INDEX</code> and <code class="command">REINDEX</code> apply deduplication to create posting list tuples, though the strategy they use is slightly different. Each group of duplicate ordinary tuples encountered in the sorted input taken from the table is merged into a posting list tuple <span class="emphasis"><em>before</em></span> being added to the current pending leaf page. Individual posting list tuples are packed with as many <acronym class="acronym">TID</acronym>s as possible. Leaf pages are written out in the usual way, without any separate deduplication pass. This strategy is well-suited to <code class="command">CREATE INDEX</code> and <code class="command">REINDEX</code> because they are once-off batch operations. </p><p> Write-heavy workloads that don't benefit from deduplication due to having few or no duplicate values in indexes will incur a small, fixed performance penalty (unless deduplication is explicitly disabled). The <code class="literal">deduplicate_items</code> storage parameter can be used to disable deduplication within individual indexes. There is never any performance penalty with read-only workloads, since reading posting list tuples is at least as efficient as reading the standard tuple representation. Disabling deduplication isn't usually helpful. </p><p> It is sometimes possible for unique indexes (as well as unique constraints) to use deduplication. This allows leaf pages to temporarily <span class="quote">“<span class="quote">absorb</span>”</span> extra version churn duplicates. Deduplication in unique indexes augments bottom-up index deletion, especially in cases where a long-running transaction holds a snapshot that blocks garbage collection. The goal is to buy time for the bottom-up index deletion strategy to become effective again. Delaying page splits until a single long-running transaction naturally goes away can allow a bottom-up deletion pass to succeed where an earlier deletion pass failed. </p><div class="tip"><h3 class="title">Tip</h3><p> A special heuristic is applied to determine whether a deduplication pass in a unique index should take place. It can often skip straight to splitting a leaf page, avoiding a performance penalty from wasting cycles on unhelpful deduplication passes. If you're concerned about the overhead of deduplication, consider setting <code class="literal">deduplicate_items = off</code> selectively. Leaving deduplication enabled in unique indexes has little downside. </p></div><p> Deduplication cannot be used in all cases due to implementation-level restrictions. Deduplication safety is determined when <code class="command">CREATE INDEX</code> or <code class="command">REINDEX</code> is run. </p><p> Note that deduplication is deemed unsafe and cannot be used in the following cases involving semantically significant differences among equal datums: </p><p> </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> <code class="type">text</code>, <code class="type">varchar</code>, and <code class="type">char</code> cannot use deduplication when a <span class="emphasis"><em>nondeterministic</em></span> collation is used. Case and accent differences must be preserved among equal datums. </p></li><li class="listitem"><p> <code class="type">numeric</code> cannot use deduplication. Numeric display scale must be preserved among equal datums. </p></li><li class="listitem"><p> <code class="type">jsonb</code> cannot use deduplication, since the <code class="type">jsonb</code> B-Tree operator class uses <code class="type">numeric</code> internally. </p></li><li class="listitem"><p> <code class="type">float4</code> and <code class="type">float8</code> cannot use deduplication. These types have distinct representations for <code class="literal">-0</code> and <code class="literal">0</code>, which are nevertheless considered equal. This difference must be preserved. </p></li></ul></div><p> </p><p> There is one further implementation-level restriction that may be lifted in a future version of <span class="productname">PostgreSQL</span>: </p><p> </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> Container types (such as composite types, arrays, or range types) cannot use deduplication. </p></li></ul></div><p> </p><p> There is one further implementation-level restriction that applies regardless of the operator class or collation used: </p><p> </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p> <code class="literal">INCLUDE</code> indexes can never use deduplication. </p></li></ul></div><p> </p></div></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="indextypes.html" title="Chapter 65. Built-in Index Access Methods">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="indextypes.html" title="Chapter 65. Built-in Index Access Methods">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="gist.html" title="65.2. GiST Indexes">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter 65. Built-in Index Access Methods </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.4 Documentation">Home</a></td><td width="40%" align="right" valign="top"> 65.2. GiST Indexes</td></tr></table></div></body></html>