0%
PostgreSQL Deep Dive: MVCC, Vacuum, Plans, and Replication
Architecture and Storage
MVCC and Vacuum
Indexes and Query Planning
JSONB and Full Text Search
Postgres stores JSON in two types: json, which keeps the original text, and jsonb, which parses it into a binary structure. jsonb is what almost every application should use, because it supports indexing, fast key lookup and a rich set of operators. This section explains how jsonb is stored, what the main operators and functions do, how jsonb values are updated and where storing data as JSON fits next to ordinary columns.
json versus jsonb
The json type stores the input text exactly, including whitespace, key order and duplicate keys, and reparses it on every access. jsonb parses the input once on write into a binary format with sorted, deduplicated keys, keeping only the last value for duplicates and discarding whitespace. Writing jsonb costs slightly more, but reading, querying and indexing are much faster. json is only useful when the exact original text must be preserved, such as for signature verification of a payload.
The binary layout
A jsonb value is a tree of containers. Each object or array stores a header with the count of entries, followed by an array of entry headers holding the type and the offset or length of each value, then the keys and values themselves. Object keys are stored sorted by length and then bytes, so a key lookup can use binary search instead of scanning the whole object. Nested objects and arrays are stored inline as sub containers.
Access operators
The arrow operator returns a field or array element as jsonb, and the double arrow returns it as text. The path operators, hash arrow and hash double arrow, take an array of keys to reach nested values. data arrow address arrow city returns jsonb; data double arrow name returns text suitable for comparison with strings. Mixing them up is a common bug: comparing a jsonb result with a text literal requires a cast or the text form.
Containment and existence
The containment operator, at greater than, tests whether one jsonb value contains another: data contains the object with status active is true when that key and value appear at the top level of data, and containment works recursively for nested objects and arrays. The existence operators, question mark, question mark bar and question mark ampersand, test whether a key or any or all of several keys exist. These operators are the ones GIN indexes accelerate, so queries written with them can be fast on large tables.
jsonpath
Since version 12, Postgres supports SQL/JSON path expressions through the jsonb_path_query family of functions and the at question mark and at at operators. A path such as dollar dot items star question mark at dot price greater than 100 selects items with a price above 100. jsonpath is expressive for nested filtering, and the at at and at question mark operators can use GIN indexes with jsonb_path_ops in some cases.
Building and transforming
Functions such as jsonb_build_object, jsonb_build_array and jsonb_agg build jsonb from rows, which is common for API responses assembled in SQL. jsonb_each, jsonb_array_elements and jsonb_to_recordset expand jsonb into rows, letting SQL join and aggregate over embedded arrays. jsonb_set, jsonb_insert and the minus operator modify values, and the concatenation operator merges objects, with keys from the right side winning.
Updates rewrite the whole value
jsonb values are immutable on disk: changing one key with jsonb_set produces a new value, and the row gets a new version containing the entire new document. For a 50 KB document, updating one counter writes 50 KB of new data plus WAL, and if the document is TOASTed, the whole TOAST value is rewritten. Documents that are updated frequently in small pieces are expensive as jsonb and are better modeled with separate columns or rows for the hot parts.
TOAST and large documents
Documents larger than about 2 KB are compressed and, if still large, moved out of line into the TOAST table. Reading any field of a TOASTed document requires fetching and decompressing the whole value, so selecting a single key from millions of large documents can be much slower than reading a plain column. Since version 14, lz4 compression, set with default_toast_compression or per column, decompresses faster than the default pglz and helps workloads that read large jsonb values often.
Statistics and the planner
The planner has statistics for whole columns, not for keys inside jsonb, so a predicate such as data double arrow status equals active is estimated with default selectivities, often badly. Expression statistics, created with CREATE STATISTICS on an expression since version 14, or an expression index, which gathers statistics on its expression, give the planner real distributions for frequently filtered keys. Without them, plans for jsonb filters may choose the wrong join or scan strategy.
When jsonb fits
jsonb fits data whose shape varies by row, such as event payloads, integration settings, user preferences and attributes that differ by product category, and data that is mostly stored and returned as a whole. It fits less well for fields that every row has, that are filtered and joined often, that need constraints or foreign keys, or that are updated frequently. A common design keeps core fields as typed columns and puts the long tail of optional attributes in a jsonb column.
Constraints on jsonb
CHECK constraints can enforce structure inside jsonb, such as requiring a key, its type with jsonb_typeof, or a value range. More complex schemas can be validated with extensions or in the application, but simple checks in the database catch the most common errors. Generated columns can extract a field into a typed column, which can then have its own constraints, indexes and statistics while the document remains the source of truth.
Equality and comparison
jsonb values can be compared with equals, which compares structure and values, ignoring key order since keys are stored sorted. Ordering operators exist too, with a defined but rarely meaningful order across types. Numbers in jsonb are stored as numeric, so 1 and 1.0 compare equal, while the string 1 does not equal the number 1. Mismatched types in documents written by different clients are a frequent cause of filters that silently miss rows.
Null versus missing
jsonb has its own null, distinct from SQL NULL. data arrow key returns SQL NULL when the key is missing and the jsonb value null when the key is present with a null value. Containment of the object with key null value matches only documents where the key exists and is null. Code that treats missing and null keys the same must check both, for example with the existence operator and a comparison to the jsonb null.
Subscripting
Since version 14, jsonb supports subscripting with square brackets, so data with key address and key city in brackets reads a nested value, and UPDATE can assign to a subscript to set a nested key. Subscripting returns jsonb and reads more naturally than chains of arrows. Assignments still rewrite the whole document, since the storage model is unchanged, so the cost considerations for updates apply equally.
Aggregating into jsonb
jsonb_agg and jsonb_object_agg build arrays and objects from grouped rows, letting a single query return nested results, such as an order with its line items as an array. This avoids N plus one queries from the application and lets the database do the assembly close to the data. Large aggregated results can use a lot of memory, so limiting nested arrays and paginating parents keeps responses bounded.
Casting and validation on write
Casting text to jsonb validates the syntax and fails on invalid JSON, so the database never stores malformed documents. Since version 16, the IS JSON predicate tests whether text is valid JSON, and can check for an object, array or scalar, without raising an error, which is useful for validating input in CHECK constraints on text columns or in data cleaning queries before casting.
jsonb parses once and stores sorted keys for fast lookups. Use the arrow operators for access and containment for indexable filters. Every update rewrites the whole document, large documents are TOASTed and read whole, and the planner lacks key statistics unless you add expression statistics or indexes.