Feeding the PostgreSQL Data Warehouse
local graph
Chapter 11 — Feeding the PostgreSQL Data Warehouse
Section titled “Chapter 11 — Feeding the PostgreSQL Data Warehouse”Feeding the PostgreSQL Data Warehouse
Section titled “Feeding the PostgreSQL Data Warehouse”Extract, t ransform, and l oad (ETL) are the traditional steps to move data from transactional systems to analytics systems. In the ETL process, a change data capture (CDC) mechanism or a batch extraction from the transaction system is followed by a transformation process. The results of that process are applied to the data warehouse incrementally or as a batch reload.
One of the major drivers for this approach was the fact that the technology used for transactional databases differed from that used for the analytics components, and that third-party products such as Oracle GoldenGate, Informatica PowerCenter, or Talend Data Fabric were used to implement the ETL processes that move data from the transactional systems to the analytical systems.
With PostgreSQL’s growing analytics capabilities, analytics requirements can often be met with PostgreSQL alone, without the need for specialty data warehousing software. PostgreSQL logical replication also provides a native CDC process, making it easy to extract and load data. The transformation step can then also be realized using built-in PostgreSQL capabilities. This is an e xtract, l oad, and t ransform (ELT) process that can be realized entirely in PostgreSQL!
Whereas ETL transforms data in an intermediate step, ELT moves the data to the target system and then transforms it there, as shown in Figure 11.1. This enables us to leverage the database’s data transformation capabilities and implement an incremental transformation process, which is necessary to achieve near-real-time analytics.

Figure 11.1: Comparing ETL and ELT
In this chapter, you will learn the following:
- How to set up an incremental extract and load process using PostgreSQL logical replication
- How to set up a batch process for extract and load using PostgreSQL’s
COPYcommand
Both approaches can be used to transfer data from a transactional database to an analytics database, laying the groundwork for an analytics-focused denormalized data model.
Technical requirements
Section titled “Technical requirements”The code for the logical replication is part of the standard setup for the sample e-commerce infrastructure and is available in the GitHub repo at psql_scripts /replication/ customer_sales_replication_setup.sql. It is part of the overall replication setup scripts and does not need to be run separately.
The code for the batch-copy model is available in the GitHub repo under psql_scripts / sample_scripts / chapter_11.sql and psql_scripts / sample_scripts / chapter_11.sh.
How to use logical replication to feed the data warehouse
Section titled “How to use logical replication to feed the data warehouse”In PostgreSQL, logical replication consists of two building blocks:
- The publication makes changes to the data (inserts, updates, and deletes) available to subscribers
- The subscription signs up for one or more publications to receive and consume their changes
For the extraction step in the ELT process, we use PostgreSQL’s logical publications, which include a built-in CDC process that publishes changes (inserts, updates, and deletes).
For the load process, we leverage PostgreSQL’s subscription capability, which subscribes to one or more publications and applies all the changes forwarded by the publisher.
In PostgreSQL, the data models in the publisher and subscriber must be similar, as PostgreSQL cannot rename or transform data mid-stream. It can only filter out rows and columns. While many classical ETL tools transform data midstream, in PostgreSQL, we transform the normalized schema into a star schema using materialized views or triggers after applying the data to the target data model. This is advantageous because we have the full power of ACID-compliant SQL to transform the data.
Figure 11.2 shows how publication and subscription work together to extract and load data from two distributed transactional systems into one centralized analytics system:
- East e-commerce and West e-commerce each create a publication.
- Personal data we don’t want to make available in the analytics system is filtered out by the publication using column-level filtering.
- Central Analytics has two subscriptions that consume the data published by the two publications.
- The customer data uses UUIDs as primary keys, which maintains uniqueness in a distributed architecture.

Figure 11.2: Publication and subscription with column-level filtering
We will use the publication of customer data from the East Coast e-commerce database to the analytics service to illustrate PostgreSQL’s publication and subscription features in detail.
Logical replication in PostgreSQL is mature and feature-rich. For a comprehensive overview of the power of logical replication, publications, and subscriptions, please refer to the PostgreSQL product documentation (https://www.postgresql.org/docs/current/logical-replication.html).
Extract: Setting up a publication
Section titled “Extract: Setting up a publication”The publication (east_customer_sales_publication) publishes the customer and sales data. It is defined in the East Coast e-commerce database – the source for this replication.
In PostgreSQL, the data models of the publisher and subscribers must be similar, except for columns that could be filtered out of the source or added in the target with default values. PostgreSQL currently cannot rename tables or columns or perform any transformations as part of a publication or subscription, except that publications can filter out columns or rows.
This sample publication uses column-level filtering to prevent the replication of personally identifiable information (PII), such as names and phone numbers. PII filtering is often used to comply with regulations such as the EU’s General Data Protection Regulation (GDPR) or India’s Digital Personal Data Protection (DPDP).
This is the table definition in the source databases east_commerce_data and west_commerce_data.
CREATE TABLE customer.customer ( id UUID PRIMARY KEY DEFAULT uuidv7(), first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, phone_numbers JSONB, street_address VARCHAR(100) NOT NULL, city VARCHAR(100) NOT NULL, postal_code VARCHAR(20) NOT NULL, country VARCHAR(50) NOT NULL, origin VARCHAR(4) NOT NULL DEFAULT :'origin' -- variable set in master_setup.sql);When we define the publication for customer data, we include all columns except names or phone numbers to filter out PII.
CREATE PUBLICATION east_customer_sales_publication FOR TABLE -- use column-level filter to avoid sharing PII customer.customer (id, street_address, city, postal_code, country, origin), sales.sales_transaction, sales.sales_transaction_line;The preceding example shows how to set up a publication for logical replication and how to use column-level filtering.
The key building blocks are as follows:
- The name of the publication (
east_customer_sales_publication) - The tables that will be published as is (
sales_transaction,sales_transaction_line) - The tables whose rows will be published selectively (
customer, with the rowsid,street, etc.)
Other important commands, not used here, include the WHERE clause to filter rows and the WITH clause to restrict publication to certain DML operations, such as INSERT, UPDATE, DELETE, or TRUNCATE. The FOR ALL TABLES and FOR TABLES IN SCHEMA clauses help publish all tables in a database. Generated columns can also be added using the WITH publish_generated_columns (stored) command.
Load: Setting up a subscription
Section titled “Load: Setting up a subscription”Subscriptions connect to the publisher’s database and read from publications. This requires a network address and login information. Behind the scenes, the subscriber creates a subscription slot on the publisher, which is used to track the subscription’s progress against the published transactions. As mentioned previously, our sample publication does not include first names, last names, or phone numbers to avoid sharing PII. On the replication target, those are filled in with default values. This provides a straightforward method for masking sensitive data.
CREATE TABLE customer.customer ( id UUID PRIMARY KEY, -- PII fields are masked (see replication setup scripts for column-level filtering) first_name VARCHAR(50) DEFAULT 'masked', last_name VARCHAR(50) DEFAULT 'masked', phone_numbers JSONB DEFAULT '{"home": "+1 (555) 123-345", "mobile": "+1 (555) 456-789"}', street_address VARCHAR(100) NOT NULL, city VARCHAR(100) NOT NULL, postal_code VARCHAR(20) NOT NULL, country VARCHAR(50) NOT NULL, origin VARCHAR(4) NOT NULL);Create the subscription on Central Analytics, the target system for this replication.
CREATE SUBSCRIPTION 'east_customer_sales_data_sub' CONNECTION :'publisher_conn_string3' PUBLICATION east_customer_sales_publication -- connect=false is essential for same-server setup -- on production servers, where databases are on different servers, -- this is not required WITH (connect = false);In our example, the publisher and subscriber databases are on the same server. This requires setting up the subscription first without a subscription slot, then creating the subscription slot on the publisher before reconnecting to the subscriber to activate the slot. This complex process is unnecessary when the publisher and subscriber are on different servers, which is typically the case in production. We chose a single-server setup to make it easier to follow the examples in this book. That architecture is not recommended for production.
Workaround 1: Create the logical replication slot on the e-commerce reference, the source system for this replication.
PERFORM pg_create_logical_replication_slot( 'east_customer_sales_data_sub', 'pgoutput');Workaround 2: Connect the subscription and enable the publication on the target system.
ALTER SUBSCRIPTION 'east_customer_sales_data_sub' ENABLE;ALTER SUBSCRIPTION 'east_customer_sales_data_sub' REFRESH PUBLICATION;Workarounds 1 and 2 would not be required if publication and subscription were on different database servers. Also, in the subscription setup shown, WITH (connect = false); would not be used, and the connection would be enabled by default.
Logical replication makes it very easy to set up an incremental ELT process that lays the foundation for near-real-time analytics.
However, sometimes, developers may want to use a batch-based approach that reloads the data warehouse periodically. The following section demonstrates how to utilize PostgreSQL for this purpose.
How to use the COPY command to feed the data warehouse
Section titled “How to use the COPY command to feed the data warehouse”The prior section taught us how to create an incremental data load process. In this section, we will achieve the same result with a batch-copy approach. Obviously, that will not be incremental and cannot support near-real-time analytics. Typically, the COPY command-based approach is only used for very small datasets or PoCs where incremental data loads are not required.
PostgreSQL has a powerful COPY command that we will use to create a batch-oriented process for extracting and loading data. To extract and load data in a single command, without requiring intermediate storage or processing, we will create a simple data pipeline using only PostgreSQL commands.
To illustrate this batch-copy approach, we create a new database, central_analytics_bcp, with the same schema and tables as central_analytics (see Figure 11.3).

Figure 11.3: ERD diagram for database central_analytics_bcp
We use a psql script that calls the COPY command, sending the data from the source tables to standard output. It then pipes this data to standard input and copies it into the target tables. We illustrate this with the customer table.
First, we truncate the target table.
echo 'truncating customer table in central_analytics_bcp'psql -d central_analytics_bcp -c 'TRUNCATE TABLE customer.customer CASCADE;'Then we copy the data from the source table in the East e-commerce database (only for the columns we want in the data warehouse) and pipe it into the target table (only for the selected columns – the other columns use their default values). The | symbol (pipe symbol) helps us send the data from stdout to stdin, without creating any intermediary files.
echo '--> Copying customer from east ecommerce'psql -d east_ecommerce_data -c 'COPY customer.customer (id, street_address, city, postal_code, country, origin) TO stdout' |\ psql -d central_analytics_bcp -c 'COPY customer.customer (id, street_address, city, postal_code, country, origin) FROM stdin'Then we repeat the process for the Western customers.
echo '--> Copying customer from west ecommerce'psql -d west_ecommerce_data -c 'COPY customer.customer (id, street_address, city, postal_code, country, origin) TO stdout' |\ psql -d central_analytics_bcp -c 'COPY customer.customer (id, street_address, city, postal_code, country, origin) FROM stdin'By omitting the PII fields from the extract command (COPY... TO stdout) and from the load command (COPY … FROM stdin), we mask the PII, just as we did with logical replication.
The COPY command is transactional by default. If the pipe breaks or another error occurs, all changes will be rolled back unless the ON_ERROR option, introduced in PostgreSQL 17, is used to specify an alternate behavior. PostgreSQL 18 has introduced numerous other enhancements that improve error handling and performance for the COPY command. Note that the earlier TRUNCATE command runs outside the transactional context, so it will not be rolled back if the COPY command fails!
While this batch-based approach does not support near-real-time analytics, it may be beneficial because it’s extremely easy to implement. It could be an initial solution for analytics of datasets (<500 GB) that do not require near-real-time analytics.
Summary
Section titled “Summary”In this chapter, we reviewed two approaches to moving data from the transactional system to the analytics system: logical replication to create a near-real-time solution, and batch copying, which is much simpler to implement but does not support real-time analytics.
Because the batch-copy approach is straightforward to implement and operate, it is often used as a starting point. It can create the same data model as the logical replication approach, but it introduces significant delays between the transactional and analytics systems. Also, in very large data warehouses, a complete refresh of the data requires lengthy batch windows and can quickly become impractical.
Both solutions can be used for the first two steps of the ELT process introduced in this chapter, and they create the data foundation for the transformation step of the ELT process, which will be discussed in the next chapter.