Sub topic 4
Publishing tables with CREATE PUBLICATION
This chapter assumes you can run psql, edit postgresql.conf, and create tables with primary keys. It also assumes you know that wal_level = logical is already set on the publisher and that a replication role exists. Earlier chapters covered both. Here the focus is the object that decides what leaves the publisher: the publication.
What a publication is
A publication is a named set of tables on the publisher. It holds no data. It is a definition that tells logical decoding which changes to send and which operations to include. A subscriber later attaches to one or more publications by name.
A few facts shape everything else in this chapter:
- A publication lives in one database. It cannot span databases.
- A table can belong to several publications, and one publication can serve many subscribers.
- Only base tables and partitioned tables can be published. Views, materialized views, and foreign tables cannot.
- A publication sends row changes only. Sequences, schema changes, and large objects are not replicated.
Creating a publication
The simplest form names the tables explicitly. Run this on the publisher:
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL
);
CREATE PUBLICATION orders_pub FOR TABLE orders;By default a publication sends all four operations: INSERT, UPDATE, DELETE, and TRUNCATE. Creating the publication does not start any copying. Nothing is sent until a subscription connects.
Three forms select tables in different ways:
| Form | What it publishes | Minimum version |
|---|---|---|
| `FOR TABLE a, b` | The listed tables only | 10 |
| `FOR ALL TABLES` | Every table in the database, including tables created later | 10 |
| `FOR TABLES IN SCHEMA s` | Every table in schema `s`, including tables created later | 15 |
You can combine the table list and schema forms in PostgreSQL 15 and later:
CREATE PUBLICATION sales_pub
FOR TABLES IN SCHEMA sales, TABLE public.customers;CREATE PUBLICATION everything_pub FOR ALL TABLES;FOR ALL TABLES and FOR TABLES IN SCHEMA are convenient, but they add each new table to the publication automatically. A new table with no primary key then starts publishing at once, and its updates may fail (see the replica identity section below). The subscriber also has to create the matching table, or its apply worker will stop with an error. Explicit table lists make each change a deliberate step.
Privileges
The rules depend on the form you use:
- To create any publication, you need the
CREATEprivilege on the database. - To add a table to a publication, you must own that table.
FOR ALL TABLESandFOR TABLES IN SCHEMArequire superuser, because they can cover tables you do not own.
The role you use to create the publication is not the role the subscriber connects with. The connecting role (for example repl_user) needs the REPLICATION attribute and SELECT on the published tables, so the initial copy can read them. Grant it explicitly:
GRANT SELECT ON orders TO repl_user;If you publish with FOR TABLES IN SCHEMA, grant SELECT on every table in that schema. Do the same for tables added to it later.
Choosing which operations to publish
The publish option restricts the operations that leave the publisher. This works in every supported version:
CREATE PUBLICATION orders_inserts_pub
FOR TABLE orders
WITH (publish = 'insert');This is useful when a subscriber only needs an append-only feed, such as a history table. The initial copy still includes all existing rows. Only later changes are filtered by the option.
If you omit TRUNCATE from the list, a TRUNCATE on the publisher leaves the subscriber's rows untouched. Check that this is what you want. A subscriber that quietly keeps rows the publisher has removed is a common source of confusion.
Row filters and column lists, which narrow what is sent within a table, arrive in PostgreSQL 15. A later chapter covers them. This chapter covers only the table-level choices.
Replica identity and updates
A publication that includes UPDATE or DELETE needs a way to tell the subscriber which row changed. That is the table's replica identity. The default is the primary key.
Creating a publication for a table without a primary key succeeds. The failure comes later, on the first UPDATE or DELETE on the publisher:
CREATE TABLE audit_log (
logged_at timestamptz NOT NULL,
message text NOT NULL
);
CREATE PUBLICATION audit_pub FOR TABLE audit_log;
INSERT INTO audit_log VALUES (now(), 'started'); -- works
UPDATE audit_log SET message = 'restarted'; -- failsThe UPDATE fails on the publisher with an error such as cannot update table "audit_log" because it does not have a replica identity and publishes updates. This is a failure of the publisher's own write, not only of the replication stream, so it breaks your application. Fix it before you add the table to a publication:
ALTER TABLE audit_log REPLICA IDENTITY FULL;FULL makes the publisher log every old column value, and the subscriber uses them all to find the row. It works without a key, but it increases WAL volume. The subscriber also has to scan for the row, which is slow on large tables without a suitable index. A later chapter covers replica identity in detail. For now, treat a primary key as a requirement for any table that updates or deletes.
Partitioned tables
Since PostgreSQL 13 you can publish a partitioned table. The publish_via_partition_root option controls how its changes are labeled:
false(default): changes are sent as changes to the individual partitions. The subscriber needs a matching table for each partition, under the same names.true: changes are sent as if they came from the root table. The subscriber can use a different partition layout, or a plain table.
CREATE PUBLICATION measurements_pub
FOR TABLE measurements
WITH (publish_via_partition_root = true);With the default, adding a partitioned table to a publication also publishes its current and future partitions. Setting true is usually the better choice when publisher and subscriber differ in layout. It matters in an upgrade or migration, where you may want to change the partition scheme.
Changing a publication
Use ALTER PUBLICATION to change the membership. The change takes effect for connected subscribers on the publisher's side immediately:
ALTER PUBLICATION orders_pub ADD TABLE order_items;
ALTER PUBLICATION orders_pub DROP TABLE order_items;
ALTER PUBLICATION orders_pub SET TABLE orders, order_items;
ALTER PUBLICATION orders_pub SET (publish = 'insert, update');SET TABLE replaces the whole list. It removes any table you leave out, so check the current list first.
Adding a table does not make the subscriber copy it. DDL is not replicated, so you must create order_items on the subscriber yourself. Then refresh the subscription so it copies the existing rows and begins streaming:
-- On the subscriber, after creating order_items there
ALTER SUBSCRIPTION orders_sub REFRESH PUBLICATION;Dropping a table from a publication stops its changes at once. The subscriber keeps its copy of the table with the rows it already has.
Inspecting publications
Use the catalogs to see what you have defined:
SELECT pubname, puballtables, pubinsert, pubupdate, pubdelete, pubtruncate
FROM pg_publication;
SELECT pubname, schemaname, tablename
FROM pg_publication_tables
ORDER BY pubname, schemaname, tablename;pg_publication_tables expands ALL TABLES and schema publications into the concrete tables they currently cover. In psql, \dRp+ orders_pub shows the same information for one publication. Check this view after creating any publication that is not an explicit list. It shows what will actually be sent.
You can remove a publication with DROP PUBLICATION orders_pub;. The tables and their data are unaffected. Any subscription that still uses the publication will then fail when it tries to start streaming, so drop or alter the subscription first.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `UPDATE` or `DELETE` fails on the publisher with a replica identity error | Published table has no primary key and no replica identity | Add a primary key, or `ALTER TABLE ... REPLICA IDENTITY FULL` |
| `permission denied for database` on `CREATE PUBLICATION` | Role lacks `CREATE` on the database | Grant `CREATE` on the database to the role |
| `must be superuser to create FOR ALL TABLES publication` | Wider forms need superuser | Use an explicit table list, or a superuser role |
| New rows in a newly added table never arrive | Subscription was not refreshed | Create the table on the subscriber, then `REFRESH PUBLICATION` |
| Subscriber still has rows after `TRUNCATE` on the publisher | `truncate` is not in the `publish` list | Add `truncate` to `publish`, or truncate the subscriber too |
Exercise
You run CREATE PUBLICATION auditpub FOR TABLE auditlog; on a table with no primary key. The command succeeds. The next day, an application's UPDATE on audit_log starts failing. Why did the failure appear only then, and what are two ways to fix it?
Show answer
Creating a publication does not check replica identity. The check happens when a published operation (UPDATE or DELETE) writes its WAL record, because the publisher cannot describe which row changed. The application's first UPDATE therefore failed on the publisher itself. You can fix it by adding a primary key to the table, or by running ALTER TABLE audit_log REPLICA IDENTITY FULL, which logs all old column values. A third option is to restrict the publication to inserts with WITH (publish = 'insert'), if the subscriber only needs an append-only feed.
Exercise
A publication orderspub is changed on the publisher with ALTER PUBLICATION orderspub ADD TABLE orderitems;. The subscriber shows no rows for orderitems. What two steps are missing on the subscriber?
Show answer
First, create the orderitems table on the subscriber with compatible columns, because DDL is not replicated. Second, run ALTER SUBSCRIPTION orderssub REFRESH PUBLICATION; so the subscription copies the existing rows and starts streaming changes for the new table.