[{"data":1,"prerenderedAt":28},["ShallowReactive",2],{"$fCiyuq-KrzKh1GSc-_Ooo_op3vIxnwMk9-dVQg7bV5ys":3},{"slug":4,"title":5,"description":6,"date":7,"tags":8,"draft":12,"readingMinutes":13,"html":14,"related":15},"postgres-partitioning","Postgres Partitioning: When It Pays Off, and the Traps","Postgres partitioning checked against the PostgreSQL 18 docs: range, list and hash, the primary key rule, pruning, attaching without locks, and when not to bother.","2026-11-12",[9,10,11],"postgres","database","performance",false,4,"\u003Cp>Postgres partitioning splits one big table into smaller physical tables that you still query as one. You declare the parent with \u003Ccode>PARTITION BY RANGE\u003C/code>, \u003Ccode>LIST\u003C/code> or \u003Ccode>HASH\u003C/code>, create a partition per month (or per tenant, or per hash bucket), and the planner skips the partitions a query can&#39;t touch. It&#39;s been built in since PostgreSQL 10. On PostgreSQL 18, the current major version, it&#39;s mature enough that the hard part isn&#39;t the feature. It&#39;s knowing whether your table needs it at all.\u003C/p>\n\u003Cp>Most don&#39;t. I&#39;d say that first because partitioning shows up in a lot of &quot;how to scale Postgres&quot; lists, and people reach for it at 5 million rows when what they needed was an index.\u003C/p>\n\u003Cp>Everything below is checked against the \u003Ca href=\"https://www.postgresql.org/docs/18/ddl-partitioning.html\">PostgreSQL 18 partitioning docs\u003C/a> on November 12, 2026. (Side note: PostgreSQL 14 reaches end of life today, per the \u003Ca href=\"https://www.postgresql.org/support/versioning/\">versioning policy\u003C/a>. If your RDS instance is still on 14, that&#39;s a more urgent job than partitioning, and on RDS it now costs extra too.)\u003C/p>\n\u003Ch2>The one case where it clearly wins\u003C/h2>\n\u003Cp>An append-mostly table with a timestamp, queries that nearly always filter on recent time, and a retention rule. Events, audit logs, webhook deliveries, IoT readings, request logs. That shape.\u003C/p>\n\u003Cp>The win isn&#39;t mostly query speed. It&#39;s deleting old data. Without partitions, &quot;keep 90 days&quot; means a nightly \u003Ccode>DELETE FROM events WHERE created_at &lt; now() - interval &#39;90 days&#39;\u003C/code>, which touches millions of rows, bloats the table, leans on autovacuum and fills the WAL. With monthly partitions it&#39;s \u003Ccode>DROP TABLE events_2026_07\u003C/code>, which the docs describe as able to &quot;very quickly delete millions of records because it doesn&#39;t have to individually delete every record&quot;. It does take an \u003Ccode>ACCESS EXCLUSIVE\u003C/code> lock on the parent, so you want it in a quiet minute, but it&#39;s over almost instantly. \u003Ccode>DETACH PARTITION ... CONCURRENTLY\u003C/code> first if you can&#39;t afford even that.\u003C/p>\n\u003Cimg src=\"/blog/postgres-partitioning/retention-drawers.webp\" alt=\"Monthly Postgres partitions as a row of drawers: a query for the last 7 days opens only November, and retention drops July whole instead of deleting rows\" width=\"1600\" height=\"900\" loading=\"lazy\">\u003Ch2>Setting one up\u003C/h2>\n\u003Cpre>\u003Ccode class=\"language-sql\">CREATE TABLE events (\n  id         bigint GENERATED ALWAYS AS IDENTITY,\n  created_at timestamptz NOT NULL,\n  account_id bigint NOT NULL,\n  payload    jsonb,\n  PRIMARY KEY (id, created_at)\n) PARTITION BY RANGE (created_at);\n\nCREATE TABLE events_2026_11 PARTITION OF events\n  FOR VALUES FROM (&#39;2026-11-01&#39;) TO (&#39;2026-12-01&#39;);\n\u003C/code>\u003C/pre>\n\u003Cp>Notice the primary key. It&#39;s \u003Ccode>(id, created_at)\u003C/code>, not \u003Ccode>id\u003C/code>. The docs are blunt about it: a unique or primary key constraint&#39;s &quot;columns must include all of the partition key columns&quot;. So you can&#39;t have a plain \u003Ccode>id\u003C/code> primary key on a table partitioned by time, and you can&#39;t enforce &quot;email is unique&quot; across a table partitioned by anything other than email. That rule alone rules partitioning out for most user-facing tables, and it&#39;s the first thing I&#39;d check before anything else.\u003C/p>\n\u003Cp>Ranges include the lower bound and exclude the upper one, so months chain cleanly. And if a row arrives for a month with no partition, the insert fails with &quot;no partition of relation ... found for row&quot;. That&#39;s the classic outage: someone created partitions by hand through December, and on January 1 every insert errors. Either add a \u003Ccode>DEFAULT\u003C/code> partition as a catch-all or, better, let \u003Ca href=\"https://github.com/pgpartman/pg_partman\">pg_partman\u003C/a> create them ahead of time (5.5.0 is the current release, from July 2026). Supabase and RDS both ship it as an extension.\u003C/p>\n\u003Ch2>Pruning only works if you ask the right way\u003C/h2>\n\u003Cp>The planner skips partitions using the partition key in your \u003Ccode>WHERE\u003C/code> clause, and only that. The docs: pruning &quot;is driven only by the constraints defined implicitly by the partition keys, not by the presence of indexes&quot;. So \u003Ccode>WHERE created_at &gt; now() - interval &#39;7 days&#39;\u003C/code> touches one or two partitions. \u003Ccode>WHERE account_id = 42\u003C/code> with no time filter scans every partition, and it&#39;s now slower than the unpartitioned table, because it&#39;s 24 index lookups instead of one.\u003C/p>\n\u003Cp>Run \u003Ccode>EXPLAIN\u003C/code> on your top ten queries before you partition. If most of them don&#39;t filter on the key you picked, pick a different key or don&#39;t partition.\u003C/p>\n\u003Cp>How many partitions is fine? The docs say the planner handles &quot;up to a few thousand&quot; well, as long as queries prune down to a few. Daily partitions for a table you keep for years gets you there faster than you&#39;d think. Monthly is my default; weekly if a month is still huge.\u003C/p>\n\u003Ch2>Converting a table that already exists\u003C/h2>\n\u003Cp>There&#39;s no \u003Ccode>ALTER TABLE ... PARTITION BY\u003C/code>. You create a new partitioned parent and move things over. The trick that saves you from copying everything: attach the old table itself as one partition.\u003C/p>\n\u003Cp>\u003Ccode>ATTACH PARTITION\u003C/code> normally scans the table to prove every row fits the range, holding an \u003Ccode>ACCESS EXCLUSIVE\u003C/code> lock on it while it does. The docs&#39; way around that is to add a \u003Ccode>CHECK\u003C/code> constraint that matches the range first (that can be added \u003Ccode>NOT VALID\u003C/code> and validated separately, with a weaker lock), then attach, then drop the now-redundant check. On a 200 GB table, that&#39;s the difference between a long lock and a quick one. The parent itself only needs \u003Ccode>SHARE UPDATE EXCLUSIVE\u003C/code> for the attach, so reads and writes keep going.\u003C/p>\n\u003Cp>Indexes have their own gotcha. \u003Ccode>CREATE INDEX CONCURRENTLY\u003C/code> doesn&#39;t work on a partitioned parent. You create the parent index with \u003Ccode>ON ONLY\u003C/code>, build each partition&#39;s index concurrently, then \u003Ccode>ALTER INDEX ... ATTACH PARTITION\u003C/code> each one; the parent index becomes valid when the last one attaches. Tedious, and worth scripting.\u003C/p>\n\u003Ch2>When I&#39;d skip it\u003C/h2>\n\u003Cp>If the table is under roughly 100 GB, has no retention rule, and its slow queries are slow because of a missing index or a bad plan, partitioning adds complexity and fixes nothing. Same for tables where every query filters by user and nothing filters by time. Fix the indexes, look at \u003Ccode>pg_stat_statements\u003C/code>, maybe add a read replica. Come back to partitioning when deleting old rows becomes the problem.\u003C/p>\n\u003Cp>If you&#39;re staring at a Postgres table that&#39;s grown past what the app was designed for and you&#39;d like a second pair of eyes before you restructure it, \u003Ca href=\"https://calendly.com/director-norsky/meeting\">book a free call\u003C/a>. All consultation is free.\u003C/p>\n",[16,20,24],{"slug":17,"title":18,"description":19},"postgres-jsonb","Postgres JSONB: When I Use It and Which Index I Pick","PostgreSQL jsonb in practice on Postgres 18: json vs jsonb, containment queries, jsonb_ops vs jsonb_path_ops GIN indexes, and the update traps.",{"slug":21,"title":22,"description":23},"postgres-full-text-search","Postgres Full Text Search: Enough for Most Apps","Postgres full text search checked on PostgreSQL 18: tsvector columns, GIN indexes, websearch_to_tsquery, ranking, ts_headline, typos with pg_trgm, and the limits.",{"slug":25,"title":26,"description":27},"postgres-vs-mongodb","Postgres vs MongoDB: Pick by the Questions You'll Ask Later","Postgres vs MongoDB in November 2026: Postgres 19 just shipped, MongoDB 8.3, JSONB vs documents, joins, transactions, licensing, and how I choose for a new app.",1795910047884]