
Fully managed, hosted Postgres on AWS, GCP, and Azure.
Joined August 2013
- Tweets3.7K
- Following2.1K
- Followers7.6K
- Likes1.1K
With `FOR UPDATE`, queue workers wait in line for the same row. With `SKIP LOCKED`, each one takes the next free row and wait 2s for a response. With 'NOWAIT', it returns immediately.
You know you can use psql with the extended protocol.
What each command does
• \bind 42 sets the parameters for the next query and makes psql send it with the extended protocol
• \g sends the query buffer to the server, the same as ending it with ;
• \parse s1 creates a prepared statement named s1 from the query buffer. Nothing runs yet
• \bind_named s1 7 sets the parameters for the existing s1, and \g runs it
• \startpipeline starts a batch, \sendpipeline queues the current query in place of \g, and \endpipeline ends the batch and prints the results
Run one query with a parameter:
`SELECT $1::int \bind 42 \g`
Name a statement, then run it:
```
SELECT $1::int \parse s1
\bind_named s1 7 \g
```
Most apps don't send raw SQL strings to Postgres. Under the hood, the wire protocol splits a single query into four separate messages:
• Parse turns SQL with $1 placeholders into a prepared statement, checking syntax and resolving names
• Bind attaches parameter values, picks text or binary format per column, and creates a "portal"
• Execute runs the portal, optionally capping returned rows with maxRows
• Sync ends the batch so the server replies with ReadyForQuery
Because your SQL and your values travel in separate messages, SQL injection protection comes from the protocol itself. You also get:
• Statement reuse by naming the statement in Parse, and subsequent calls can skip straight to Bind and Execute
• Pipelining can queue several Parse/Bind/Execute sequences before a single Sync to cut down on network round trips
Want to see which protocol your app uses? Turn on log_statement = 'all' and check your logs:
• Simple (one Query string): statement: SELECT * FROM users WHERE id = 42
• Extended: execute <unnamed>: SELECT * FROM users WHERE id = $1 followed by DETAIL: Parameters: $1 = '42'
In Postgres 19, effective_wal_level is a high-quality developer experience upgrade. It's nice, simple, and obvious, which makes it hard to explain.
Previously, enabling logical slots required a restart to set wal_level to logical. Now you don't. (the end)
Looking back since beta3 (August 13), what is in Postgres 19rc2 and what is not?
✅ still there in rc2
❌ in beta3, gone in rc2
🆕 new in rc2
Performance
✅ Async I/O workers that scale between `io_min_workers` and `io_max_workers`
✅ Parallel autovacuum
✅ `REPACK`, including `CONCURRENTLY`
✅ `pg_plan_advice` and `pg_stash_advice`
Developer Experience
❌ SQL/PGQ property graph queries
❌ `UPDATE ... FOR PORTION OF`
❌ `ALTER TABLE ... MERGE PARTITIONS` and `SPLIT PARTITION`
❌ SQL functions that return the DDL for roles, databases and tablespaces
✅ `INSERT ... ON CONFLICT DO SELECT`
✅ String functions in `jsonpath`
✅ `random()` for dates and timestamps
✅ Read-your-writes on replicas by waiting for an LSN
Security
✅ `password_expiration_warning_threshold`
✅ `md5_password_warnings`
Monitoring
✅ `pg_stat_lock` and `pg_stat_recovery`
✅ `started_by` and `mode` in `pg_stat_progress_vacuum`
✅ `EXPLAIN (ANALYZE, IO)`
❌ `pg_stat_progress_data_checksums`
Logical Replication
✅ `CREATE PUBLICATION ... EXCEPT`
✅ `CREATE SUBSCRIPTION ... SERVER`
✅ `effective_wal_level`
Defaults and Other Changes
❌ Online enabling and disabling of data checksums
✅ JIT is off by default
✅ `default_toast_compression` defaults to `lz4`
On its last day of community support, Postgres 14.25 was released with a healthy set of security and bug fixes.
postgresql.org/docs/release/…
Today is Postgres 14's EOL.
When launched just over 5 years ago, it added / improved:
• SEARCH and CYCLE clauses for recursive CTEs
• Multirange types, so a set of ranges fits in one value
• date_bin(), which buckets timestamps into fixed intervals
• Subscripting for jsonb: data['user']['id']
• Pipeline mode in libpq, which sends several queries before waiting on results
• pg_stat_wal, pg_stat_progress_copy and pg_stat_replication_slots views
• pg_stat_statements tracking top-level and nested statements separately
• VACUUM that gets more aggressive as a database nears transaction ID wraparound
• B-tree index updates that reduce bloat
Today is Postgres 14's EOL.
When launched just over 5 years ago, it added / improved:
• SEARCH and CYCLE clauses for recursive CTEs
• Multirange types, so a set of ranges fits in one value
• date_bin(), which buckets timestamps into fixed intervals
• Subscripting for jsonb: data['user']['id']
• Pipeline mode in libpq, which sends several queries before waiting on results
• pg_stat_wal, pg_stat_progress_copy and pg_stat_replication_slots views
• pg_stat_statements tracking top-level and nested statements separately
• VACUUM that gets more aggressive as a database nears transaction ID wraparound
• B-tree index updates that reduce bloat
`date_bin()` buckets timestamps into fixed intervals, like `date_trunc` for any width. `date_bin('15 minutes', ts, '2000-01-01')` groups events into 15-minute slots.
1
1
139
Crunchy Data retweeted
For months I was scared to post this post. Not because I wasn't excited for the feature, in fact the opposite. To me this was the most exciting feature in PG19, I was worried if it would land vs. being reverted.
Luckily looks like REPACK is coming in PG19 snowflake.com/en/blog/engine…
Want to tail the output of a query? End it with `\watch`:
```
SELECT state, count(*) FROM pg_stat_activity GROUP BY state \watch
```
psql reruns it every 2 seconds, with a timestamp over each result, until you hit Ctrl-C. Handy for watching a backfill, a migration, or locks clearing.
• Pick the interval with `\watch 1`
• `\watch count=5` stops on its own
By default, psql trims error messages. `\errverbose` shows the whole thing.
Want it every time? `\set VERBOSITY verbose`.
Or, require typing in "production" to verify intent to connect to a production database:
```
SELECT :'HOST' ~ 'prod' OR :'DBNAME' ~ 'prod' AS is_prod \gset
\if :is_prod
\echo '\033[1;37;41m PRODUCTION:' :DBNAME 'on' :HOST ' \033[0m'
\set PROMPT1 '%[%033[1;37;41m%] PROD %[%033[0m%] %n@%/%R%# '
\prompt 'Type "production" to continue: ' confirm
SELECT :'confirm' <> 'production' AS cancel \gset
\if :cancel
\! kill $PPID
\endif
\endif
```
All things Postgres roles & permissions 🧵
Think of Postgres permissioning a series of independent gates (authentication > database > schema > object > row):
1. can the role even connect? (pg_hba.conf)
2. can the role use this database? (CONNECT privilege)
3. can the role see this schema? (USAGE privilege)
4. can the role read/write this object? (SELECT/INSERT/UPDATE/DELETE privileges)
5. can the role see this row? (row-level security policies)
Postgres's permission system is complicated when implemented haphazardly. When implemented thoughtfully, most of the confusion disappears.
For a basic `SELECT`, a role needs USAGE on a schema and SELECT on a table.
Postgres has a built-in listen/notify channel. One session sends a notification, and any session running `LISTEN new_order` receives it. The payload is a string up to around 8 KB.
Notifications are transactional: if the sending transaction rolls back, the message is never delivered. If it commits, every listener connected at commit time gets it, in commit order. No message is stored, so any listener that connects after the commit misses the message.
When copying a query from pg_stat_statements or logs, and attempting to run EXPLAIN on it, you'll get "there is no parameter $1".
Since Postgres 16, EXPLAIN (GENERIC_PLAN) plans it as-is. It returns the plan a prepared statement would cache and reuse. Since it can't run the query, there's no ANALYZE.
How do you hint a query your ORM writes with the new Postgres 19 `pg_plan_advice` feature?
Most ORMs use prepared statements: the query is sent once with placeholders like `$1`, and later executions send only the values. And, you have these queries all over your application.
Good news! Unlike hint comments, to use the new feature, you don't have to change the query text or add a comment.
With pg_plan_advice, advice is attached to queries by their query id, which is a hash of the parsed query with the constant values left out (though a literal and a `$1` still hash differently). So, there are no queries to change or settings to make in the ORM. `pg_stash_advice` stores advice by query id, and a role setting applies it to every session the application opens.
First, load the libraries
```
shared_preload_libraries = 'pg_plan_advice,pg_stash_advice,pg_stat_statements'
```
and on the database, run:
```sql
CREATE EXTENSION pg_stash_advice;
CREATE EXTENSION pg_stat_statements;
```
Hopefully, you'll have had `pg_stat_statements` already loaded (we actually have to refrain from mentioning it every single week). If you haven't used it previously, you'll have to wait for some queries to be logged.
Next, find the query id for the query that you want to advise. Don't paste the ORM's query into psql and compute it yourself. The id depends on how the driver sends the query. Fortunately, if you use `pg_stat_statements`, it will list the query id:
```sql
SELECT queryid, calls, query
FROM pg_stat_statements
WHERE userid = 'your_app_user'::regrole;
```
Stash the advice and point the role at it:
```sql
SELECT pg_create_advice_stash('app');
SELECT pg_set_stashed_advice('app', <queryid>, '<advice>');
ALTER ROLE your_app_user SET pg_stash_advice.stash_name = 'app';
```
Are you imagining how you can have different advice for different applications, or change the advice for a set of application runners without changing the application code? You can do that with different stashes and different role settings (see the caveats below first).
Reconnect the application, and it will use the advice.
Different ORMs build the same query differently, which generates different query ids. Django binds values client-side by default, so Postgres sees a literal, and that hashes differently from `$1`. SQLAlchemy sends `$1::INTEGER`, and the cast gives it its own id. Rails, GORM, and Django with server-side binding shared one id, despite different SQL text. If several applications share the database, stash advice under each id they send.
A few caveats:
• The same advice applies to every value the ORM sends, not just the one you tested. The stash is keyed by query id, and the query id ignores parameter values, so `customer_id = 1` and `customer_id = 42` get the same plan. With skewed data, that cuts both ways: stash a seq scan because your biggest customer has 500,000 orders, and it helps that customer (37 ms to 26 ms in our test). But every customer with 100 orders gets a seq scan too: 20 ms instead of 0.04 ms, about 500 times slower.
• Copy only the piece of advice that fixes the problem. `EXPLAIN (PLAN_ADVICE)` generates advice for the whole plan: every scan, the join order, and every join method. Paste all of it, and you freeze the entire plan, so the planner can't adapt when the data grows, statistics change, or someone adds an index. If only one decision is wrong, say it chose a nested loop where a hash join belongs, stash just that join method, such as `HASH_JOIN(o)` for the `orders` alias, and let the planner choose the rest.






