Crunchy Data (@crunchydata) header
Crunchy Data (@crunchydata) profile picture

Fully managed, hosted Postgres on AWS, GCP, and Azure.

Joined August 2013
Photo by Crunchy Data (@crunchydata)Photo by Crunchy Data (@crunchydata)Photo by Crunchy Data (@crunchydata)Photo by Crunchy Data (@crunchydata)Photo by Crunchy Data (@crunchydata)Photo by Crunchy Data (@crunchydata)Photo by Crunchy Data (@crunchydata)Photo by Crunchy Data (@crunchydata)Photo by Crunchy Data (@crunchydata)Photo by Crunchy Data (@crunchydata)
With pg_stat_statements and simple SELECT statements, you can run the queries from psql by passing arguments using the \bind command. Doesn't work with IN statements, as pg_stat_statement collapses it. Use EXPLAIN (GENERIC_PLAN) instead.
2
12
685
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.
2
21
741
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 ```
1
4
23
936
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'
4
3
40
1,542
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)
1
2
27
985
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`
3
2
13
909
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
1
8
483
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
6
4
2
30
1,969
`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
JSONB supports subscripting: `data['user']['id']` instead of `data -> 'user' ->> 'id'`.
1
129
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…
3
2
10
1,659
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
2
1
18
802
By default, psql trims error messages. `\errverbose` shows the whole thing. Want it every time? `\set VERBOSITY verbose`.
3
23
957
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 ```
Use your .psqlrc to modify the prompt when connecting to production:
2
1
15
911
Use your .psqlrc to modify the prompt when connecting to production:
1
3
1
17
2,136
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.
1
13
898
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.
1
4
20
831
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.
1
2
17
868