Designing for H igh
local graph
Chapter 7 — Designing for H igh
Section titled “Chapter 7 — Designing for H igh”Designing for High Transaction Volumes and Writing Efficient Transactional Code
Section titled “Designing for High Transaction Volumes and Writing Efficient Transactional Code”Databases are at the heart of modern enterprise applications. Speed, accuracy, and efficiency of transactions are critical as user counts, data volumes, and application usage increase. Choosing the correct data type that supports all necessary operations without adding unnecessary overhead is the first step. A sub-optimal data type generates unnecessary I/O and requires custom coding, instead of using the power of PostgreSQL.
Once we have picked the correct data type, we need to select the appropriate indexes and design effective and efficient queries. The choice of index is influenced by the data type and the type of operation that is executed in the query. Choosing the wrong index, which does not support the needs of the query or leverage the power of the data type, creates unnecessary I/O, uses more memory, and requires longer development and test cycles.
The rich and extensible set of data types, the operations they support, and how they are indexed is a cornerstone of PostgreSQL’s success.
Unlike simpler databases that use a one-size-fits-all approach (for example, using a TEXT type for all character data), PostgreSQL offers a wide range of types, each designed for specific kinds of data. Choosing the right type is not just about correctness; it is a vital decision that affects the following:
- Performance: The correct data type minimizes the storage footprint, which reduces I/O and speeds up queries, because more rows fit per data page and more relevant pages fit in memory caches.
- Data i ntegrity: Proper typing enforces validity at the database level. For example, an
INTEGERcolumn will reject alphabetic characters, and aDATEcolumn will prevent the entry of non-date data. - Functionality: Specific types enable specialized operations. For example, when using the
TIMESTAMPtype, the developer has access to a rich set of operators to compare dates, extract date components, handle time zones, or work with intervals.
This chapter covers the following topics:
- The main PostgreSQL data types and their key uses
- How to choose the right data type for your needs
- How indexes work with data types for faster access
- The main types of indexes and when to use them
- Tips for writing efficient queries using data types and indexes
- Common mistakes to avoid in schema, index, and query design
Technical requirements
Section titled “Technical requirements”All examples in the chapter are available in the GitHub repo under psql_scripts / sample_scripts / chapter_7.sql.
PostgreSQL data types
Section titled “PostgreSQL data types”Data comes in many forms and shapes. Data types are used to characterize data – for example, defining that a data element is a 25-character-long string, and the operations that can be executed on that string – for example, appending to the string, searching within it, or replacing a substring. Choosing the correct data type is essential, as the data types define what the application can expect, what the developer needs to consider, and how the application will perform.
When developers choose a data type, we recommend that they follow a golden rule:
Choose the most specific type that accurately represents your domain, provides the right operators, and can comfortably hold your expected data range.
For example, don’t choose INTEGER to store Boolean true/false data, as INTEGER (4 bytes) uses four times as much space as BOOLEAN (1 byte). Making the right choice minimizes I/O and provides developers with powerful tools that reduce the need to write a lot of code.
To help the developer pick the correct data type, we divide PostgreSQL’s data types into several categories:
| Category | Purpose |
|---|---|
| Boolean | Store true/false data. |
| Numeric | Manage data about numbers, such as integers, floating-point numbers, and decimals. |
| Binary | Store raw data – for example, images or PDF documents. |
| Character t ypes | Store text and character data. |
| Date and time | Manage dates, times, and timestamps. |
| NoSQL | Handle JSON, JSONB, and key-value-pair data. |
| Arrays | Manage collections of elements of the same basic data type. |
| Ranges | Define ranges over certain basic data types, such as time or integers. |
| Custom types | Provide enumerations, domain-specific data types, and composite types. |
| UUID | Create universally unique identifiers that are especially useful in distributed systems. |
| Vector data | Provide the foundation for AI processing in PostgreSQL (via third-party extension) |
| Time series | Support high-volume append-only data that needs to be aggregated and analyzed over time (via third-party extension). |
Table 7.1: Categories of data types provided in PostgreSQL
Some of these data types need to be activated using the CREATE EXTENSION command. Some extensions are included as contrib modules in the standard PostgreSQL distribution; for example, the HSTORE extension provides the key-value-pair data type and is part of the standard PostgreSQL distribution. Others, such as the vector data type, are part of third-party extensions and need to be installed separately.
There are specialty types that we will not discuss here, as we haven’t seen significant developer adoption: bit string, text search, XML, OID, ISN, and ISN. However, for specialized applications in those domains, they can be instrumental. For example, the ISN data type deals with ISBNs and EAN codes. PostgreSQL’s native network address type deals with IPV4, IPV6, CIDR, and MAC addresses, and should be used instead of strings, as the built-in types offer strong operator support. When built-in types are insufficient, PostgreSQL’s extensibility allows teams to define custom data types with their own operators and indexes to support highly specialized domains. The PostgreSQL documentation (see https://www.postgresql.org/docs/current/datatype.html) is the best resource to learn more about these specialty types.
PostgreSQL also supports basic geometric types, such as points, lines, boxes, and circles. We will not discuss those here either, as developers interested in geographic information might be better off installing the PostGIS extension and consulting specialized PostGIS reference documentation (see https://postgis.net/documentation/).
The following sections will describe each data type category with a specific focus on guidance for the developer: what it is, when to use it, and what the pros and cons are.
Boolean data
Section titled “Boolean data”Boolean data is the simplest and most obvious data type. It only allows for two values: true and false. It should always be used if those are the only possible values. Like all SQL types, a boolean column can also be NULL, which represents an unknown or missing value and participates in SQL’s three-valued logic. Although it may be tempting to use integers for TRUE and FALSE, this approach is not advisable, as integers require four times the storage space (4 bytes instead of 1).
Numeric data
Section titled “Numeric data”PostgreSQL provides several data types for specific numeric data:
- Integer supports whole numbers and comes in three variations:
SMALLINT(2 bytes),INTEGER(4 bytes), andBIGINT(8 bytes). - Arbitrary precision (declared as
NUMERICorDECIMAL) is used to handle user-specified precision, such asNUMERIC(5,2), which allows for at most 5 total digits of precision with 2 digits after the decimal point (scale). In that case, the value ranges from -999.99 to 999.99. The storage requirement varies with the precision. - Floating - point numbers are either declared as
REAL(6 decimal digits of precision using 4 bytes for storage) orDOUBLEPRECISION(15 decimal digits of precision using 8 bytes of storage).
The SMALLSERIAL, SERIAL, and BIGSERIAL types were used for autoincrementing integers, especially in primary keys, but have been superseded by GENERATED BY DEFAULT AS IDENTITY, which complies with the SQL standard. In most cases, GENERATED ALWAYS AS IDENTITY is preferred to enforce identity generation and reduce the risk of sequence desynchronization, while GENERATED BY DEFAULT AS IDENTITY is useful when explicit values must occasionally be provided (for example, during migrations).
PostgreSQL also provides the MONEY data type, which should not be used because its decimal precision depends on the local server setting lc_monetary. Restoring data that uses the MONEY data type to a different server can be problematic. We recommend using the NUMERIC type instead. Depending on the use case, choose the appropriate precision and scale. For example, NUMERIC (8,2) will be sufficient for retail applications where the most expensive product costs less than 999,999.99. Financial institutions will require greater precision and scale.
Data Type | Range | Storage | Pro | Con |
|---|---|---|---|---|
| +/- 32,768 | 2 bytes | Fast computation Small storage | No fractions Automatic rounding |
| +/- 2,147 M | 4 bytes | ||
| +/- 9.223 1E18 | 8 bytes | ||
| Max. 131072 digits bef. decimal point; max 16383 digits aft. decimal point | Variable | No rounding errors | More storage Slower calculations |
| -3.40282347 × 1E38 to 3.40282347 × 1E38 | 4 bytes | Imprecise w. rounding errors | Fast calculations Less storage than |
| 1E-307 to 1E+308 | 8 bytes |
Table 7.2: Decision criteria for numeric data types
Based on the details laid out in *Table 7.*2, we recommend the following approach to picking the best data type for numeric data:
- Calculations on numeric or decimal types are slower than those on integers or floating-point numbers.
- Floating-point numbers can exhibit rounding errors; arbitrary precision numbers do not. If your application needs exact storage and calculations, it’s best to use
NUMERICorDECIMAL. - If no fractional parts are required, use an
INTEGERdata type, and choose the smallest type that comfortably fits your use case.
Binary data
Section titled “Binary data”PostgreSQL offers the BYTEA data type (BYTEA stands for binary array) for storing binary strings or byte sequences. BYTEA can store strings up to 1 GB in size, but it is generally not recommended to manage large amounts of binary data directly in Postgres. Instead, we recommend storing binary data, such as images or other large binary objects, as files and saving the file paths in the database.
Character data
Section titled “Character data”PostgreSQL offers character types with fixed length (CHARACTER), variable length with a limit (VARCHAR), and unlimited length up to 1 GB (TEXT). All string and text operators, such as || (concatenation), CONCAT(``), RTRIM / LTRIM, SUBSTRING, and others, work with all character types.
With regard to performance, the PostgreSQL documentation states the following:
While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact, character(n) is usually the slowest of the three because of its additional storage costs. In most situations, text or character varying should be used instead.
In general, developers will choose between VARCHAR(N) and TEXT. In most cases, TEXT is preferred. If the maximum length of the character string is a business rule that must be enforced, then use VARCHAR(N). UI-driven limits are typically better handled through input validation before the data reaches the database.
Date and time
Section titled “Date and time”PostgreSQL supports the full range of SQL types for time and date (see *Table 7.*3). When using TIME or TIMESTAMP with a time zone (TIMESTAMPTZ), the server explicitly converts the data to UTC during storage and reconverts it to the local session time zone at retrieval, and if the input does not include an explicit time zone, it is interpreted using the session time zone. Timestamps, times, and intervals can be defined with a precision of up to six fractional digits (6 is the default).
During input, date and time literals need to be enclosed in single quotes (e.g., ' 2025-01-01 ').
| Name | Storage | Description | Range | High Value | Resolution |
|---|---|---|---|---|---|
| TIMESTAMP | 8 bytes | both date and time (no time zone) | 4713 BC - 294276 AD | 294276 AD | 1 microsecond |
| TIMESTAMP WITH TIME ZONE (alias: TIMESTAMPTZ) | 8 bytes | both date and time, with time zone | 4713 BC - 294276 AD | 294276 AD | 1 microsecond |
| DATE | 4 bytes | date (no time of day) | 4713 BC - 5874897 AD | 5874897 AD | 1 day |
| TIME | 8 bytes | time of day (no date) | 00:00:00 - 24:00:00 | 24:00:00 | 1 microsecond |
| TIME WITH TIME ZONE (alias: TIMETZ) | 12 bytes | time of day (no date), with time zone | 00:00:00+1559 - 24:00:00-1559 | 24:00:00-1559 | 1 microsecond |
| INTERVAL | 16 bytes | time interval | +/- 178000000 years | 178000000 years | 1 microsecond |
Table 7.3: PostgreSQL date and time types
INTERVAL provides a convenient way to add or subtract intervals of time. Here’s an example:
select NOW() + INTERVAL '1' YEAR;select NOW() + INTERVAL '2' DAY;The following is guidance for developers:
timestamptzandtimetzare convenient PostgreSQL aliases for times and timestamps withtime zone. They are generally used instead of the more verbosetime/timestamp withtimezone.- PostgreSQL supports 195 different time zone abbreviations. Use the
pg_timezone_abbrevsview to get a listing of the recognized time zones with their offset from UTC. Timestamptzuses the server’s time zone when the input does not include an explicit time zone.- Time or time stamps with or without time zones use the same amount of storage, and there is no difference in computational overhead.
- Using time zones is generally recommended if a backup could ever be applied to a server in a different time zone.
PostgreSQL started supporting NoSQL data types in version 8.4 with key-value pairs (KVP s). It added JavaScript Object Notation (JSON) in 9.2, and JSONB (the binary version) was added in 9.4. Today, JSONB is generally considered the preferred NoSQL data type in PostgreSQL, as it has the richest set of operators, the best indexing options, and, in most circumstances, provides better performance. However, JSON and JSONB are not equivalent: JSON preserves the original input text, while JSONB stores a parsed binary form. As a result, JSON can be cheaper to write (less processing on insert/update), while JSONB is typically better for read-heavy workloads and querying.
JSON is a powerful data format because of its flexibility and extensive operator support. Consider the following example of a JSON document that illustrates the tremendous flexibility of the JSONB data type.
{"firstName": "John", "lastName": "Smith", -- Character type "isAlive": true, -- Boolean type "age": 25, -- Numeric type "height_cm": 167.6, -- Numeric type "address": { -- Nested JSONB object "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "phoneNumbers": [ -- JSONB array { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" } ]}'JSON syntax
Section titled “JSON syntax”JSON uses a simple notation of < key >``: ``< value >, where the key is a string, and the value can be one of four primitive types (see *Table 7.*4), a nested JSON object, or an array.
| JSON Primitive Type | PostgreSQL Type | Notes |
|---|---|---|
| String | Text | \u0000 is disallowed, as are Unicode escapes representing characters not available in the database encoding |
| Number | Numeric | NaN and infinity values are disallowed |
| Boolean | Boolean | Only lowercase true and false spellings are accepted |
| Null | (none) | SQL NULL is a different concept |
Table 7.4: Mapping JSON primitive types to PostgreSQL basic types (from PostgreSQL documentation)
As shown in the preceding example, the JSONB primitive types can also be used to create more complex nested JSON objects using arrays and JSON itself.
JSON null cannot be cast to SQL NULL, and vice versa.
JSON operators
Section titled “JSON operators”Understanding the JSON operators is key, as JSON is much, much more than just a nested string. It has powerful operators for creating documents, accessing their content, the JSON Path language, the JSON Query language, and JSON_TABLE. We will provide simple examples to illustrate the breadth of JSON operators to create, read, update, and delete data in JSON documents. For a complete listing, please refer to the PostgreSQL documentation.
Creating and accessing JSON documents
Section titled “Creating and accessing JSON documents”The JSONB_BUILD_OBJECT function is extremely powerful and can build JSON objects from variadic parameters, arrays, and records. This example shows how we can combine data from the brand and country tables into one JSON object:
CREATE TABLE brand_country_json (id, brand_info) AS(SELECT id, JSONB_BUILD_OBJECT( 'brand id', id, 'label', label, 'description', description, 'country', JSONB_BUILD_OBJECT( 'iso code', alpha3_code, 'name', name) ) FROM brand b JOIN country_of_origin coo on b.id = coo.brand_id);This results in a simple table with a JSON column.
id | jsonb_pretty----+------------------------------------------------- 9 | { + | "label": "H&M", + | "country": { + | "name": "Sweden", + | "iso code": "SWE" + | }, + | "brand id": 9, + | "description": "Affordable fashion for all"+ | }The - > and - > > operators were the initial operators introduced in PostgreSQL 9.2 to access data in JSON documents. - > extracts the JSON object field with the given key and - > > retrieves the string value.
SELECT brand_info->'label' AS label_json FROM brand_country_json WHERE id=9;label_json------------ "H&M"SELECT brand_info->>'label' AS label_text FROM brand_country_json WHERE id=9;label_text------------ H&Mselect brand_info->'country' country_json FROM brand_country_json WHERE id=9;country_json--------------------------------------- {"name": "Sweden", "iso code": "SWE"}json_path_query is a more powerful and elegant way to navigate complex JSON documents.
SELECT jsonb_path_query (brand_info, '$.label') AS label, jsonb_path_query (brand_info, '$.country.name') AS country_nameFROM brand_country_json WHERE id=9;SQL/JSON path expressions specify items to be retrieved from a JSON value. The path can include the path to the JSON element, such as country.name. Other options include the position in an array and searching through arrays that are included in the JSONB document.
The following query, applied to our initial, complex example, searches the array of phone numbers for the one where the type is " home ".
SELECT JSONB_PATH_QUERY (info, '$.lastName') AS name, JSONB_PATH_QUERY(info, '$.phoneNumbers[*][0] ? (@.type == "home")')->'number' AS home_nbr FROM jsonb_example;Updating JSON documents
Section titled “Updating JSON documents”JSONB_SET is a powerful function to change existing values or add new entries. It has four parameters:
target: The original JSON document to be modified.path: An array of text elements that specifies the path to the key where you want to insert or update the data.new_valueis the new JSONB value to be set at the specified path.create_missing: An optional parameter indicating whether to create missing keys if they do not exist. It defaults to true, meaning that the function will create a new key if needed.
This command will add a new phone number entry to our complex JSON example:
SELECT JSONB_SET ( info, -- the target JSONB column '{phoneNumbers,2}', -- the path to the new entry '{"type":"mobile", "number": "617 306 6059"}', -- the changed data true -- create missing path elements if needed ) FROM jsonb_example WHERE id=1;Whereas this command updates the existing phone number:
SELECT JSONB_SET( info, '{phoneNumbers,1,number}', '"617 306 6059"')FROM jsonb_example WHERE id=1;Deleting JSON documents
Section titled “Deleting JSON documents”The #- operator can be used to delete keys and their values. The first example deletes the state key and its value; the second example deletes the second entry in the array of phone numbers.
SELECT info #- '{address, state}' FROM jsonb_example WHERE id=1;SELECT info #- '{phoneNumbers,1}' FROM jsonb_example WHERE id=1;JSON_TABLE
Section titled “JSON_TABLE”JSON_TABLE was added to PostgreSQL in version 17, letting developers convert JSON data into a standard PostgreSQL table.
The following statement converts the JSONB data from the customer table into columnar data:
SELECT id, first_name, pn.* FROM customer, JSON_TABLE( phone_numbers, '$' COLUMNS ( mobile TEXT PATH '$.mobile', home TEXT PATH '$.home') ) AS pn;Indexing JSON documents
Section titled “Indexing JSON documents”While B-tree indexes are the most popular indexes in PostgreSQL and are suitable for many use cases, they focus on equality comparison of column values, and we hardly ever compare two JSON documents for equality in a WHERE clause.
But B-tree indexes can help filter JSON documents based on specific key values. In that case, we create an expression index for those keys. For example, if we want to quickly find customers by their mobile phone number, we create an expression index for that field.
CREATE INDEX idx_customers_mobile ON customer ((phone_numbers->>'mobile'));When we don’t plan to search by a specific field, we recommend using the GIN index. It decomposes the JSON document and indexes the keys and the values. This makes the GIN index the primary choice for JSON-based queries that match on keys and containment. We will explain the use of the GIN index in more detail in the following section focused on PostgreSQL indexes.
Performance consideration
Section titled “Performance consideration”JSONB is flexible and powerful, but it has a performance drawback when handling frequent updates. Updating even one field in a JSONB document rewrites the entire object, generating a lot of WAL (Write Ahead Log records – PostgreSQL durability log) and potentially slowing down the database.
To prevent this, create separate columns for fields that are updated often, and avoid referencing those fields within the JSONB object. This hybrid approach—using relational columns for high-volume write fields and reserving JSONB for complex, less frequently changed data—finds the right balance between performance and flexibility.
NoSQL or tables: How to decide?
Section titled “NoSQL or tables: How to decide?”It may seem tempting to use JSON to store almost any kind of data; after all, JSON can be indexed and queried just like tabular data, and it is part of the same transactional model. Why not just use arrays of JSON objects to store the rows of data?
The following design decisions guide the developer in making that choice:
- JSON documents tend to be organized hierarchically, encoding the preferred access path. If the business requirements change, the hierarchical encoding can become problematic.
- When a part of a JSON object is updated, then the whole JSON document is committed as part of the updated row. This can cause significant I/O and WAL, and if the JSON document is heavily indexed, a lot of indexing information must be updated, too.
- PostgreSQL benchmarks have shown that selects, inserts, and deletes of JSON documents are very fast; updates tend to be slower.
We recommend using the JSONB data type instead of columns in the following situations:
- Personalization data that includes multiple phone numbers or multiple addresses. Using JSON makes it easy for some users to have one phone number, and others to have three or four.
- Raw data from third-party systems that has been normalized and abstracted for use in a relational environment. For example, temperature sensor data, where different sensor types may send different datasets, but the relational model currently only uses the timestamp and the temperature. Keeping the raw data in the JSON document allows the developer to access more information later.
- Log information can easily be stored as JSON and queried as and when needed.
Arrays
Section titled “Arrays”PostgreSQL defines array types of any built-in or user-defined base type, enumeration type, composite type, range type, or domain. Arrays can be used in variable declaration in functions or procedures, or as data types for columns in tables.
Arrays can be multi-dimensional, but they cannot mix different data types. If you need to combine multiple data types into a single array, we recommend creating an array based on a composite type.
Arrays are easy to define, as shown in *Table 7.*5. They are often used to hold multiple items that are related, such as a list of phone numbers.
| Definition | Explanation |
|---|---|
| INTEGER[] | One-dimensional array of integers. |
| INTEGER[3] | One-dimensional array of three integers. Important: PostgreSQL does not enforce the length definition. |
| TEXT[][] | Two-dimensional array of text values. |
Table 7.5: Sample array definitions
Working with arrays in PostgreSQL is straightforward. Here is a simple illustration for creating, reading, updating, and deleting from arrays of military phonetic alphabets.
-- example with text arraysCREATE TABLE array_spelling ( country TEXT PRIMARY KEY, spelling TEXT[]);
-- array with spelling alphabets for US, DE, FRINSERT INTO array_spelling (country, spelling) VALUES ('US', '{Alpha,Bravo,Charlie,Delta,Echo,Foxtrot}'), ('DE', '{Anton,Berta,Cäsar,Dora,Emil,Friedrich}'), ('FR', '{Anatole,Berthe,Célestin,Désiré,Eugène,François}');
-- view the dataSELECT * FROM array_spelling;
-- replace Foxtrot with FoxtrottUPDATE array_spellingSET spelling = ARRAY_REPLACE(spelling, 'Foxtrot', 'Foxtrott')WHERE country = 'US';
-- add Golf to the end of the arrayUPDATE array_spellingSET spelling = ARRAY_APPEND(spelling, 'Golf')WHERE country = 'US';
-- remove Golf from the arrayUPDATE array_spellingSET spelling = ARRAY_REMOVE(spelling, 'Golf')WHERE country = 'US';Arrays or tables: How to decide?
Section titled “Arrays or tables: How to decide?”It can be tempting to use arrays instead of tables, especially when replacing small tables. However, arrays should be used only to store small collections of data that are not referenced elsewhere, or to keep mid-sized data collections in memory during complex calculations. Replacing tables with arrays also means giving up relational properties—such as joins, referential integrity, and integrity constraints—that tables provide. Arrays have significant limitations:
- The data in an array must all be of the same type, even when the array has multiple dimensions.
- Searches in arrays may require sequential scans unless an appropriate index is used. PostgreSQL can index array elements using GIN indexes, but without such an index or when queries depend on element position/order, searches often degrade to sequential checks.
- The whole array represents one column in the database record. Any change of any value in the array means that the entire row must be committed.
- Using arrays extensively can easily break the First Normal Form and lead to significant data duplication and other normalization anomalies (You can read more about this in Chapter 5*,* Transactions, ACID Compliance, and Data Normalization.
Ranges
Section titled “Ranges”Range data types were introduced in PostgreSQL 9.2 and have rapidly become a powerful tool that simplifies data modeling and reduces the lines of code in many situations.
PostgreSQL offers range types for integers, numeric, timestamps with and without time zones, and date ranges. They make it easy to define range boundaries: ( and ) indicate that the boundary is excluded, whereas [ and ] indicate that the boundary is included. Infinite ranges simply omit the lower or upper boundary or use special values such as -infinity and infinity (and the +infinity synonym) to express unbounded ends explicitly.
Range types offer a wide range of specialized operators for identifying containment, overlap, right-of, left-of, adjacency, and so on. B-tree indexes are useful to compare different ranges for equality, but Generalized Search Tree (GiST) indexes should be used to support most range type-specific operators.
Chapter 5*,* Transactions, ACID Compliance, and Data Normalization shows how range data types can be used to model complex concepts, such as date ranges for prices, in a single statement. The btree_gist extension, a PostgreSQL contrib module, allows us to create a one-statement constraint that checks for overlapping date ranges!
This code snippet illustrates the use of the DATERANGE data type and the @ > (contains) operator:
CREATE TABLE product.product_variant_price (... validity DATERANGE NOT NULL,... -- Ensures that there are no overlapping price validity periods for the same product and geography. EXCLUDE USING GIST (product_variant_id WITH =, validity WITH &&));
-- both upper and lower boundaries are included in the rangeINSERT INTO product_variant_price (product_variant__id, price, validity, current)VALUES (109, 100.00, '[2025-07-01,2025-07-02]', false);-- use the @> operator to check if the value is contained in the rangeSELECT * FROM product_variant_price WHERE validity @> '2025-07-18'::date AND product_variant_id = 109;Range data types are compelling and easy to use. Developers should be familiar with them and take them into account.
Custom types
Section titled “Custom types”PostgreSQL provides many built-in data types, and a developer may wonder why we need – or want – more of them? The simple reason is that type definitions centralize the description and management of new building blocks, which reduces code and complexity throughout the application. PostgreSQL provides domains, composite types, and enumeration types.
Custom types cannot be used in the row-filtering expression for logical replication.
Domains
Section titled “Domains”Domains are built on base types, such as NUMERIC, and add additional constraints, for example, by defining that all prices must be greater than zero and should be limited to two fractional digits and an overall precision of 8.
CREATE DOMAIN price AS NUMERIC(8,2) CHECK (VALUE >= 0);
CREATE TABLE custom_type_example ( id SERIAL PRIMARY KEY, product_name TEXT, product_price price);
INSERT INTO custom_type_example (product_name, product_price) VALUES ('Product 1', 19.99), ('Product 2', 29.99);
INSERT INTO custom_type_example (product_name, product_price) VALUES ('Product 3', -5.00); -- this will fail due to the CHECK constraint
SELECT * FROM custom_type_example;When to use domains
Section titled “When to use domains”Domains are an underused capability that simplifies database definitions and reduces code by centralizing specifications.
The DDL is much more elegant when you use custom-domain definitions in table, view, or function definitions, instead of repeating the constraint and precision specification everywhere.
Definitions, constraints, and specifications are managed centrally. When the business decides to change the spec, the developer makes the change in a single place.
Caution: DROP DOMAIN ... CASCADE will also drop dependent objects (such as columns defined with that domain), so teams should treat domains as shared contracts and manage changes deliberately.
Composite types
Section titled “Composite types”Composite types are similar to tables in that they allow the assembly of several different data elements into one data element that can then easily be returned from functions. For example, one could define a composite type called custom_product that has name, description, and cost. The c ost could leverage the PRICE domain we described previously.
Data elements of a custom type can be created in two ways: using ROW to construct the element or as a quoted list.
CREATE TYPE custom_product AS ( name VARCHAR(2), description TEXT, cost PRICE); -- uses the custom domain defined above
CREATE TABLE composite_type_example ( id SERIAL PRIMARY KEY, product_info custom_product );
INSERT INTO composite_type_example (product_info) VALUES (ROW('P1', 'Product 1 description', 19.99)), (ROW('P2', 'Product 2 description', 29.99));
INSERT INTO composite_type_example (product_info) VALUES ('("P3", "Product 3 description", 32.15)');
INSERT INTO composite_type_example (product_info) VALUES ('("P4", "Product 3 description", -5.00)'); -- this will fail due to the PRICE domain CHECK constraint
SELECT * FROM composite_type_example;While CREATE TYPE appears to work like CREATE TABLE, it does not allow for the creation of check constraints within the type. For that purpose, we leverage custom domains.
One important thing to note: every CREATE TABLE command also creates a composite type of the same name, with the same columns – but without the constraints! This composite type can conveniently be used to return values from functions.
When to use composite types
Section titled “When to use composite types”Though custom types resemble JSON documents, they offer more robust data typing and definition rules. If the structure and rules are known, we recommend using custom types instead of JSON objects.
Enumeration types
Section titled “Enumeration types”Enumeration (a.k.a. ENUM) types are data types that comprise a static, ordered set of values. For example, one could define an enumerated type for the days of the week.
CREATE TYPE week_days AS ENUM ( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
CREATE TABLE enum_example ( id SERIAL PRIMARY KEY, day week_days NOT NULL);
INSERT INTO enum_example (day) VALUES ('Monday'), ('Tuesday'), ('Sunday');
INSERT INTO enum_example (day) VALUES ('FRIDAY'); -- this will fail
SELECT * FROM enum_example WHERE day > 'Friday';Enumerations are ordered by the sequence in which they were defined.
When to use enumeration types
Section titled “When to use enumeration types”Enumerations and foreign keys can both be used to define a set of values for a column. Enumerations have an advantage over foreign keys: queries don’t need to refer to the parent table to get the real value instead of the key.
But use enumerations with caution: changing the values in an enumeration type is a change to the database schema instead of just adding a row to a table, which can require stronger locks and may be difficult to apply on a very busy system.
It is recommended to use enumeration types when you have a small, fixed set of values that is unlikely to change, such as RGB colors (red, green, blue). Otherwise, use tables and foreign keys.
Universally unique IDs
Section titled “Universally unique IDs”Universally Unique Identifiers (UUID s) are a separate data type in PostgreSQL. A UUID is a 128-bit (16-byte) sequence of 32 hexadecimal digits, represented in five groups separated by hyphens – for example, 01995196-02ef-7db9-b11b-b906ee7b4926.
UUIDs are intended to provide unique identifiers that distributed systems can generate without using a shared reference. PostgreSQL supports UUID V4 and V7 (introduced in PostgreSQL V18). V4 and V7 share the same on-disk format but use different generation algorithms.
UUIDV4 uses a completely random approach, but UUIDV7 is time-ordered. That distinction is essential when using UUIDs as primary keys in PostgreSQL. A sequential primary key reduces index fragmentation during inserts and tends to improve retrieval by favoring sequential reads.
*Table 7.*6 describes the five segments of a UUID V7, including the most significant 48 bits, which include the timestamp.
select uuidv7();Here’s the output we get:
uuidv7-------------------------------------- 01995196-02ef-7db9-b11b-b906ee7b492648-bit time stamp | UUID version + 12 random bits | Variant (2 bits) + 2 random bits | 60 random bits | |
|---|---|---|---|---|
|
|
|
|
|
Table 7.6: Anatomy of a UUID V7
When to use UUIDs
Section titled “When to use UUIDs”UUIDs are designed to provide universally unique identifiers in distributed systems, where each component needs to generate unique IDs independently. They are especially useful when data is created in multiple locations and later merged, or when IDs must be generated safely offline without coordinating with a central sequence.
Keep in mind that UUIDs require significantly more storage (16 bytes) than big integers (8 bytes) or regular integers (4 bytes), which causes more I/O and WAL, and requires more memory.
The following short test, shown in *Table 7.*7, illustrates the difference. We are inserting 10,000,000 rows into both tables and then measuring the table size. The test table using UUID-based primary keys needs about 22% more storage. Keep in mind that a 16-byte UUID primary key forces every referencing foreign key to also be 16 bytes, compared to just 8 bytes with BIGINT. In a normalized schema, this overhead multiplies across dozens of tables and, more importantly, across all their associated indexes. The result is fewer index entries per 8 KB data page, higher I/O for queries, and a reduced effectiveness of the shared buffer cache, as larger index pages displace other valuable data. This system-wide, non-linear performance degradation is one of the strongest arguments for preferring BIGINT over UUID in many designs.
CREATE TABLE test_integer ( id INTEGER PRIMARY KEY ); | CREATE TABLE test_UUID ( id UUID PRIMARY KEY DEFAULT uuidV7() ); |
|---|---|
pg_relation_size: 3,624,779,776 bytes | pg_relation_size: 4,428,111,872.00 (+22%) |
Table 7.7: Comparing UUID-based primary keys to integer-based ones
In some distributed systems, a combination of instance-specific prefixes and integers may be sufficient to guarantee uniqueness. This approach will also yield data that may be easier to understand and debug, but it requires manual management of prefixes.
These are general rules of thumb:
- In distributed systems, use UUID when identifiers must be generated independently across multiple writers without coordination (for example, offline creation or later merging of independently created records)
- In single-instance data services, an integer or a big integer usually suffices, unless the expected number of IDs exceeds 9,223 billion
Specialty data types from notable third-party extensions
Section titled “Specialty data types from notable third-party extensions”As PostgreSQL is built on an extensible object-relational architecture, extensions can be used to add data types, operators, and indexes. PostGIS is a well-documented extension for adding geospatial data types and operators. Many books have been published about PostGIS. In this book, which focuses on transactions, analytics, and AI, we will discuss pgvector, the extension to perform AI calculations in PostgreSQL, and mention TimescaleDB, the leading extension to handle append-only timeseries data.
Even though a UUID is 16 bytes and an int is 4 bytes (a 4:1 ratio), the table size won’t be 4 times larger because every row, every page, and the relation itself has some overhead.
Vector data
Section titled “Vector data”Vector data representations are key to combining AI and databases. Vectors are used to store embeddings: the semantic representations of natural language documents, images, and other unstructured information. Nearest neighbor searches use vector distance calculations, such as cosine distance or Euclidean distance, for natural language search, recommendations, sentiment analysis, and generative AI. Chapter 15*,* Database Requirements for Artificial Intelligence Use Cases reviews the AI use case in detail, and Chapter 16*,* Vectors and Indexing for AI with pgvector gives detailed examples of how pgvector can be used to implement AI use cases in PostgreSQL.
Vector data is supported in PostgreSQL through the pgvector extension, which is not part of the standard PostgreSQL distribution and must be installed separately.
While a real AI use case requires high-dimensional vectors (often over 1,000), we will illustrate pgvector with a simple three-dimensional use case (see Figure 7.1).

Figure 7.1: A three-dimensional vector space: the references are red, the target is green
Four points (the red dots) are defined as three-dimensional vectors in our three-dimensional space, and we will use pgvector ‘s L-2 distance calculation to identify the nearest neighbor to our target (the green dot with coordinates 0.8,1.5,0) in ascending order of distance.
CREATE TABLE vector_example ( id bigserial PRIMARY KEY, embedding vector(3));
INSERT INTO vector_example (embedding) VALUES ('[1,1,0]'), ('[1,2,2]'), ('[3,2,3]'), ('[1.5,2,3]');
SELECT embedding <-> '[0.8,1.5,0]' as L2_distance, * FROM vector_example ORDER BY L2_distance;p gvector provides a simple-to-use yet powerful tool for implementing AI operations in PostgreSQL. Chapter 16*,* Vectors and Indexing for AI with pgvector provides a detailed review of how developers can use pgvector to implement semantic search, product recommendations, and the automatic generation of SQL statements directly in PostgreSQL.
Time series data
Section titled “Time series data”Time-series data is a key characteristic of Internet of Things (IoT) applications, where sensors generate large volumes of timestamped data that must be ingested and analyzed quickly. IoT data is typically processed in an append-only manner rather than in an update-focused way.
For example, in an update-focused approach, the database record tracking the temperature of sensor 17 would be updated as soon as sensor 17 reports new data – even if this happens hundreds of times per hour. We might also track prior values or the time of the update.
This approach is problematic because it creates hotspots in the database, generates significant bloat, and makes the analysis of measurement series challenging.
In append-oriented processing, the new record, together with a timestamp, gets appended to the table. There is no updating of any records, which avoids hotspots and bloat. However, the developer is now left dealing with a rapidly growing table and the need to manually write code to handle time buckets, condense data, apply continuous aggregates, and manage partitioning.
TimescaleDB is an open source PostgreSQL extension that addresses this problem by introducing hypertables (automatic time-based partitioning) and continuous aggregates (incrementally refreshed, precomputed rollups for fast analytics).
Choosing the right data types for your use case
Section titled “Choosing the right data types for your use case”The developer is continuously faced with data type decisions. The fundamental golden rule advises selecting a data type that accurately represents the domain, provides the right operators, and can comfortably hold the expected data range.
This golden rule helps decide between integer data types, and limited character strings (CHAR and VARCHAR) or unlimited character data (TEXT). The same is true for range types: reconstructing ranges through multiple columns and range operators through complex queries makes no sense.
Clear rules guide decisions on whether to use UUIDs or integers for primary keys. Unless unique IDs must be created in distributed systems, or the range of the unique identifiers exceeds the capabilities of BIGINT, use an integer type.
The decision to use custom types (domains, composites, and enumerations) can be less obvious. We recommend tying that choice to business rules that are not expected to change. For example, consider defining a custom PRICE data type, that leverages the NUMERIC (8,2) base type with a check constraint making sure that values of type PRICE are greater than zero – if that type matches the business rules!!!
With regard to composite types: unless the developer wants to define specific operators for a composite type, we recommend using tabular structures. They are easier to maintain, IDEs provide better tooling, and many analytics tools focus on tables.
We encourage the use of JSON to provide flexibility. JSON is great for personalization, managing denormalized source data, or storing logs. Do not use JSON to replace normalized tables.
PostgreSQL indexes
Section titled “PostgreSQL indexes”The prior section reviewed the most important PostgreSQL data types, how to use them, and when to choose them. This section discusses PostgreSQL indexes, how they work, and which indexes to choose for which type of workload.
Overview
Section titled “Overview”Database indexes accelerate the retrieval of data from disk and from memory. PostgreSQL stores data in 8k blocks, and it is the index’s role to quickly identify the relevant 8k block(s) that contains the data to be read or modified.
PostgreSQL provides several types of indexes, each with specific strengths and recommended use cases:
- B- t ree (B alanced T ree) is focused on equality and range queries, and it is the only index that can be used to create an ordered output. It is used by default for primary keys and is the default index when no other index type is mentioned.
- Hash indexes use a 32-bit hash; it is very fast, but it can only be used for equality comparisons.
- GIN (Generalized Inverted Index) is used to index data with many keys and values, such as JSON documents or multi-dimensional arrays. GIN indexes handle duplicates very well and make sure that keys are stored only once. GIN indexes are also used in
tsvectortext searches. - BRIN (Block Range Index) creates a tiny index that is used for very large, naturally ordered tables, for append-only tables. The BRIN index identifies ranges of data blocks that can contain the target record.
- GiST (Generalized Search Tree) is an indexing framework designed to index complex data types with minimal programming. Supported data types include geometric types, range types, key-value pairs, integer arrays, and
pg_trgm(text search via trigrams – see Chapter 14, Analyzing Text Documents in PostgreSQL). GiST also supports distances used for nearest neighbor searches. - SP-GIST (Space-Partitioned Generalized Search Tree) is also an indexing framework. It is comparable to GiST, but it allows for decomposing keys into hierarchically organized partitions. It is used for complex spatial queries or hierarchical datasets.
Extensions, such as pgvector, often provide their own indexes. pgvector includes IVFFLAT (Inverted File with Flat Compression) and HNSW (Hierarchical Navigable Small World) as ways to identify potential nearest neighbors.
Indexing strategies
Section titled “Indexing strategies”Some of the indexes previously described can be used in different ways to help the developer achieve even better results. This includes techniques such as the following:
- Expression indexes, where an expression calculates the value to be indexed
- Partial indexes, where only key values are included in the index
- Multi-column indexes create a single index on select combinations of columns that are frequently used in
WHEREclauses - Index-only scans are designed to provide results directly from the index, without consulting the actual table
- Alternate operator classes, where the index is built with a different operator class to support specific operators efficiently (for example, using
text_pattern_opson a B-tree index to optimizeLIKE 'prefix%'searches).
Let’s look at each strategy in more detail.
Expression indexes
Section titled “Expression indexes”While we mostly think about applying indexes directly to columns, it is sometimes better to clean up or normalize the column first. For example, in our dataset, some cities are spelled out in all capitals, and some are capitalized. To search efficiently, we create an expression index on the lowercase spelling of the city column.
N ote: Prefer normalizing data at ingestion when possible. Expression indexes are especially useful when you can’t immediately fix legacy or externally sourced data, or when you intentionally index a derived value (e.g., lower(email), date_ trunc (``'day', ``ts``), or coalesce(``col, ...)).
CREATE INDEX idx_customer_city_lower ON customer (LOWER(city));Partial index
Section titled “Partial index”If the values in an index column are very skewed towards one value or if our queries use only a subset of the data in the conditional clauses, thenit does not make sense to index all the values, as the selectivity of the index would be low, and PostgreSQL would likely revert to a sequential scan. For example, in our customer dataset, Massachusetts accounts for a large share of the data, so it makes sense to create a partial index on the state to reduce the index size and make updates easier without sacrificing performance.
Multi-column indexing
Section titled “Multi-column indexing”Many queries use multiple columns in the WHERE clause, for example:
SELECT * FROM customer where last_name = 'West' and first_name = 'Waldo';When we use the EXPLAIN ANALYZE facility (you can learn more on that in Chapter 8*,* Understanding and Monitoring Transactional Application Performance), we see that PostgreSQL used a sequential scan, the slowest possible method to find data.
EXPLAIN SELECT * FROM customerwhere last_name = 'West' and first_name = 'Waldo';QUERY PLANSeq Scan on customer (cost=0.00..48.21 rows=1 width=116) Filter: (((last_name)::text = 'West'::text) AND ((first_name)::text = 'Waldo'::text))If we add an index on last_name only, then PostgreSQL uses a combination of bitmap and index scan – a slightly faster way.
CREATE INDEX idx_customer_lname ON customer (last_name);EXPLAIN SELECT * FROM customerwhere last_name = 'West' and first_name = 'Waldo';QUERY PLAN Bitmap Heap Scan on customer (cost=1.43..8.88 rows=1 width=116) Recheck Cond: ((last_name)::text = 'West'::text) Filter: ((first_name)::text = 'Waldo'::text) -> Bitmap Index Scan on idx_customer_lname (cost=0.00..1.43 rows=7 width=0) Index Cond: ((last_name)::text = 'West'::text)(5 rows)After we define a multi-column index on last_name and first_name, we see that the query starts using this combined index, which is the most efficient way to find the data.
CREATE INDEX idx_m_customer_lname_lname ON customer (last_name, first_name);EXPLAIN SELECT * FROM customerwhere last_name = 'West' and first_name = 'Waldo';QUERY PLANIndex Scan using idx_m_customer_lname_lname on customer (cost=0.28..2.50 rows=1 width=116) Index Cond: (((last_name)::text = 'West'::text) AND ((first_name)::text = 'Waldo'::text))(2 rows)One of the major improvements in PostgreSQL V18 is called Skip Scan, which lets the planner utilize multi-column B-tree indexes even if the initial columns are not included in the WHERE clause. This often allows us to skip creating dedicated single-column indexes on the second or third columns of a multi-column index, reducing index maintenance and storage space.
Index-only scans (covering indexes)
Section titled “Index-only scans (covering indexes)”Index-only scans can answer queries using only the index, without any heap access (the heap is where PostgreSQL stores table data). This is significantly more efficient than other index mechanisms, which, once the correct record is found, still need to access the heap to provide the requested data.
Index-only scans have two fundamental requirements:
- The index type must support index-only scans. Index-only scans are always supported by B-tree indexes, and by GiST and SP-GiST for some operators.
- The query must reference only columns stored in the index.
To support the latter, one can add a ' passenger ' (covering) column to an index using the INCLUDE clause.
CREATE INDEX idx_customer_lname_w_city ON CUSTOMER(last_name) include (CITY);EXPLAIN SELECT city FROM customer where last_name = 'West';QUERY PLANIndex Only Scan using idx_customer_lname_w_city on customer (cost=0.28..1.50 rows=7 width=15) Index Cond: (last_name = 'West'::text)Without the covering index, the query cost would have been much higher because the data had to be fetched from the heap.
EXPLAIN SELECT city FROM customer where last_name = 'West';QUERY PLANBitmap Heap Scan on customer (cost=1.43..8.86 rows=7 width=15) Recheck Cond: ((last_name)::text = 'West'::text) -> Bitmap Index Scan on idx_customer_lname (cost=0.00..1.43 rows=7 width=0) Index Cond: ((last_name)::text = 'West'::text)(4 rows)Adding an additional column to an index to achieve index-only scans can accelerate query response time, but beware: the index now needs to be updated when either the index key columns or the included (covering) columns change.
Choosing the right indexes for your use case
Section titled “Choosing the right indexes for your use case”The developer may be tempted to index everything and create many multi-column indexes, just in case. However, that could significantly slow down the system.
We recommend the following indexing strategy:
- Primary keys should be used for every table. This automatically creates a B-tree index, which excels at equality comparisons. If you use an artificial (surrogate) primary key, consider also enforcing uniqueness on the natural key with a
UNIQUEconstraint (backed by a unique index). - During development, identify the
WHEREclauses and the columns likely to be queried frequently. Create multi-column indexes for recurrent column patterns. Organize theWHEREclauses and the indexes in descending order of selectivity. - Avoid over-indexing. Index creation and index updates are CPU- and I/O-intensive operations. Every time an indexed column changes, all indexes that it participates in must be updated and recommitted. This is also referred to as the write amplification effect.
- Be cautious. Indexes can become quite large and can consume significant disk space and I/O capacity on their own. Over time, indexes can also become bloated (contain many dead or fragmented pages), which increases I/O, reduces cache efficiency, and slows down scans.
- Avoid indexes on columns with low selectivity; for instance, a gender column in an employee table will typically be ignored by the planner because using the index (which requires loading it from disk and scanning it) does not provide any measurable advantage over a sequential scan.
- If a column appears in a multi-column B-tree index, do not (initially) create a separate index. Actual run time analysis (more about that in Chapter 8*,* Understanding and Monitoring Transactional Application Performance) will help identify additional index needs.
- Understand the data elements and operators in the
WHEREclauses and pick the appropriate indexes:- Equality and order by ->B-tree
- NoSQL, arrays, and text search with tsvector ->GIN
- Geospatial, ranges, custom types, and text search with trigram -> GiST
- Huge sequentially organized tables (10s of GBs+) -> BRIN
- Equality and order by ->B-tree
During the test phase and when the system moves to production, we recommend monitoring the system for frequently occurring queries that do not use an index, and for indexes that are used infrequently or not at all. Chapter 8*,* Understanding and Monitoring Transactional Application Performance will review the tools to monitor indexes.
PostgreSQL will happily allow redundant or unused indexes (as long as they have different names), so it is best practice to periodically review index usage statistics and remove unused indexes. Major planner improvements—such as Skip Scan in PostgreSQL 18—are also a good trigger to re-evaluate your indexing strategy.
Guidelines for writing effective, efficient, and manageable queries
Section titled “Guidelines for writing effective, efficient, and manageable queries”Queries are at the heart of working with any relational database, whether used interactively, through stored procedures (see Chapter 6*,* Functions and Stored Procedures), or through calls generated from an application. This book will not delve into the details of SQL and how to write queries; instead, we refer you to the book Learn SQL (Second Edition) by Luca Ferrari and Enrico Pirozzi. In the remainder of this chapter, we will focus on writing effective, efficient, and manageable queries.
Effective queries return exactly the data that is needed. Queries are considered efficient if they achieve the desired results with a minimum of CPU and I/O. Queries, just like any computer code, need to be manageable and maintainable.
Effective queries ensure that they return only the columns and rows that are needed. A query that returns all columns, even though only two are required, is not effective as it causes unnecessary data traffic between the client and the server. A query that uses ORDER BY to get the best choice, but omits adding a LIMIT, returns many more rows than are needed, and causes excessive I/O and network traffic between the client and the server. This makes it an inefficient query. A query that uses cryptic abbreviations or positional arguments becomes unmanageable and is likely to be rewritten by the maintenance team, instead of being improved.
*Table 7.*8 shows a list of query writing guidelines that help create effective, efficient, and manageable queries.
| Guideline | What is the impact**?** |
|---|---|
| Limit the number of rows that are returned | Be specific in the WHERE clause and consider using LIMIT to avoid unnecessary I/O. For pagination, avoid large OFFSET values because the database must scan and discard rows; instead, prefer keyset pagination (seek method) or a window-function approach to fetch the next page efficiently. |
| Limit the number of columns that are returned | Being specific in the column selection reduces network traffic between client and server, and it also tells the user about the exact sequence and names of columns. |
Use JOINs to help the planner | Explicitly using the JOIN clause, instead of just listing the tables in the FROM clause, helps the planner identify the optimal join order, especially for multi-join queries (up to join_collapse_limit, which defaults to 8). This shortens the planning time for queries that join many tables. |
Define highly selective WHERE clauses, especially when using JOINS | WHERE clauses tell the planner what data needs to be loaded into memory. Selective WHERE clauses, especially for the initial table of a JOIN, can significantly reduce I/O. |
Define meaningful aliases in the SELECT clause using AS to avoid duplicate column names | Meaningful names make the query results easier to understand for users and makes the query easier to maintain. The sequence of columns output by SELECT * can change due to ALTER TABLE statements and cause unintentional havoc at the application level. Always use column names! |
| Use snake_case in the alias statements to improve readability | When referring to the id column in the customer table, the use of customer_id will make it easier to understand the output and work with it. |
Use the aliases defined in the FROM clause in the SELECT and GROUP clauses to avoid typos and shorten the code | Improves the readability and maintainability of the code. |
| Use views to standardize complex and frequently used queries | Views standardize database requests and eliminate redundant code. Writing the view once, making it as efficient and effective as possible, and using it in all queries that access the same data, will improve efficiency and manageability. |
| Use CTEs instead of subqueries | CTEs are easier to design and maintain than complex subqueries, as every expression can be tested individually. CTEs also support recursion and often simplify it, though recursion can also be implemented using SQL/PL/pgSQL functions or application code. |
Table 7.8: Guidelines for writing efficient, effective, and manageable queries
Several of the guidelines in *Table 7.*8 mention aliases. Aliases can be shared across different parts of the query, but only in the sequence in which the query building blocks are evaluated. *Table 7.*9 shows the SQL query building blocks and their order of execution.
| Order | Statement Building Block |
|---|---|
| 1 | FROM/JOIN: Specifies the tables from which to retrieve data. |
| 2 | WHERE: Filters the rows that meet the condition before grouping. |
| 3 | GROUP BY: Groups rows that share a property. |
| 4 | HAVING: Filters groups based on conditions, applied after grouping. |
| 5 | SELECT: Specifies the columns to retrieve or calculate. |
| 6 | DISTINCT: Removes duplicate rows from the result set. |
| 7 | ORDER BY: Sorts the result set by specified columns. |
| 8 | LIMIT: Specifies the maximum number of rows to return. |
| 9 | OFFSET: Specifies how many rows to skip before starting to return rows. |
Table 7.9: SQL order of execution
Tips and tricks to write better queries
Section titled “Tips and tricks to write better queries”Here are some lessons that we learned while writing queries:
- If you need to use
SELECT COUNT, count the entries in an indexed column, if possible. The count can then be done using the index only and avoids accessing the heap. Be careful withSELECT COUNTon large tables, as it can displace significant amounts of active data from shared buffers and impact the performance of concurrent sessions and queries. If you only need an approximate row count, PostgreSQL’s table statistics may be sufficient and much cheaper than runningCOUNT(``*).
COUNT(``col) counts only non-NULL values; use COUNT(``*) for total rows.
- If you need to know if a value is in the table, use
EXISTSinstead ofIN(``SELECT …``). For exclusion checks, preferNOT EXISTSoverNOT IN, especially when the subquery might returnNULLvalues.JOINsbenefit greatly fromWHEREclauses that filter rows early, starting with the initial table in theFROMclause, and when possible, every table in the list of joins. - Study the
EXPLAINplans (see Chapter 8*,* Understanding and Monitoring Transactional Application Performance) once you have realistic test data.EXPLAINreveals inefficiencies.
Appending, updating, and dealing with MVCC hotspots
Section titled “Appending, updating, and dealing with MVCC hotspots”Before we close this chapter, we need to touch on one more issue that plagues many novice PostgreSQL developers, especially those who have started their career on other databases such as Oracle: hotspots caused by Multi-Version Concurrency Control (MVCC), PostgreSQL’s mechanism to manage the transaction isolation discussed in Chapter 5*,* Transactions, ACID Compliance, and Data Normalization.
Here is a brief, simplified explanation of what happens when data changes in a database that uses MVCC. A new version of the record is created for every transaction that changes it. Once the transaction has been committed, the old record, also known as the dead tuple, is flagged as no longer current; the new record becomes the current version, and eventually the autovacuum daemon will reclaim the old versions of the record. If the updated column was indexed, the index must be updated as well!
In PostgreSQL, bloat is created by updates or deletes, not by inserts. MVCC hotspots are often single rows (or small sets of rows) that are frequently updated, which leads to many “old” versions of the same record, but can also lead to row-locking contention.
These are ways to avoid hotspots:
- Try to avoid frequent updates focused on the same row by designing a more distributed approach or an approach that appends a new record instead of updating the old one.
- Reduce the indexing of tables that contain hotspots.
- Ensure that the table containing hotspots does not participate in any long-running transactions, as these will prevent the vacuuming of any dead tuples within their scope.
- Tune the vacuum for that specific table to prevent dead tuples from accumulating and monitor bloat in that table (more on that in Chapter 8*,* Understanding and Monitoring Transactional Application Performance).
- Heap Only Tuples (HoT s) are another technique for mitigating update hotspots. A HoT update occurs when the updated row version can be stored on the same page without modifying indexed columns. This avoids writing new index entries, thereby reducing write amplification and improving performance.
- Adjusting the fill factor for an update-intensive table and leaving free space on each page for future updates further improves the likelihood of HoT updates. For example, this command updates the fill factor of the inventory table – which is frequently updated – to 50 (the default is 100):
ALTER TABLE SET (``fillfactor= 50``);. Adjusting the fill factor for a read-only or append-only table will not have the same benefit. - Optimize the data ingestion strategy for an append-heavy workload to avoid unnecessary write amplification.
- Batch inserts: Instead of single-row inserts, group them into larger batches (e.g., 50,000 rows per transaction) to minimize commit overhead.
- Use COPY for bulk loading: The
COPYcommand is optimized for large-scale data ingestion and is significantly faster than multipleINSERTstatements.
- Use COPY for bulk loading: The
- Batch inserts: Instead of single-row inserts, group them into larger batches (e.g., 50,000 rows per transaction) to minimize commit overhead.
Let’s look at the first recommendation in more detail. Assuming we are developing a social network that tracks the number of followers for our participants.
DROP TABLE IF EXISTS users;CREATE TABLE users ( id SERIAL PRIMARY KEY, f_name TEXT, l_name TEXT, email TEXT UNIQUE NOT NULL, nbr_followers INTEGER, UNIQUE (f_name, l_name));
CREATE INDEX idx_user_test_fname_lname ON users (f_name, l_name);If we frequently update the column with the number of followers, then this table can become a hotspot. Even though we only update one column, the whole row record has to be updated every time, which leads to the creation of a dead tuple and requires an update of the primary key index and the multi-column index on first name and last name.
As a first step, we can move the follower count to a separate table, thus reducing the size of the bloat and moving the frequently updated column into a table with only one index.
CREATE TABLE follower_count ( user_id INTEGER REFERENCES users(id) ON DELETE CASCADE, follower_count INTEGER);The next step can partition the follower_count table, distributing the actual updates over multiple hash partitions. This spreads the update activity, distributing the work for the vacuum processes, and reducing the potential locking contention.
DROP TABLE IF EXISTS follower_count CASCADE;CREATE TABLE follower_count ( user_id INTEGER REFERENCES users(id) ON DELETE CASCADE, follower_count INTEGER) PARTITION BY HASH (user_id);
-- Create partitionsCREATE TABLE follower_count_part_0 PARTITION OF follower_count FOR VALUES WITH (MODULUS 4, REMAINDER 0);CREATE TABLE follower_count_part_1 PARTITION OF follower_count FOR VALUES WITH (MODULUS 4, REMAINDER 1);CREATE TABLE follower_count_part_2 PARTITION OF follower_count FOR VALUES WITH (MODULUS 4, REMAINDER 2);CREATE TABLE follower_count_part_3 PARTITION OF follower_count FOR VALUES WITH (MODULUS 4, REMAINDER 3);Careful design reviews can identify potential hotspots and remove them from the architecture. However, many such issues will only become apparent in multi-session and high-volume testing. Monitoring for locks and persistent bloat is key to identifying and remediating hotspots.
Summary
Section titled “Summary”Data types are fundamental to SQL. Choosing the optimal data type that accurately represents your domain, provides the right operators, and can comfortably hold your expected data range is key to creating high-performance databases. Once data types are chosen and we understand the query pattern, we can then select the optimal indexes.
The next chapter reviews the tools to monitor and manage the performance of queries and transactions. This includes understanding query execution plans, analyzing actual execution behavior, identifying missing or unused indexes, and knowing which tools to choose in the PostgreSQL ecosystem to monitor and manage a high-performance database.
Further Reading
Section titled “Further Reading”Consult Chapter 11 of Learn SQL (Second Edition) by Luca Ferrari and Enrico Pirozzi, for a more detailed explanation of the MVCC mechanism in PostgreSQL.