PostgreSQL Cheatsheet
Dense quick reference for PostgreSQL 17/18: connect, define, query, index, lock, monitor, back up, and wire it into Go and Laravel. Chapters behind it: PostgreSQL fundamentals, Indexing, Isolation levels, MVCC & VACUUM.
How to use this page
- This is a lookup page: find the task in the first column, copy the command, and read the note before running it on production.
- For why, and for query and index examples, read the chapters linked in the summary above and the SQL Queries & Indexes Cheatsheet.
- Written for PostgreSQL 17/18; anything marked with a version (for example v15+) is absent below that version.
Page map
| Section | Use it when |
|---|---|
| Connection | Connecting, URIs, environment defaults and checking where you landed |
| Meta-commands (psql) | Meta-commands inside psql: describing objects, \watch, \copy, \gexec |
| DDL | Creating and altering tables, constraints and partitions |
| DML | Inserts, upserts, MERGE, CTEs, windows, JSON and pagination |
| Indexes | Choosing, building and auditing indexes |
| Transactions & isolation | Isolation levels, row and advisory locks, timeouts and retries |
| Admin & monitoring | Sessions, locks, statistics, vacuum, replication and settings |
| Diagnostic queries | Long SQL moved out of the tables, ready to paste |
| Config knobs | Defaults and sizing hints for the main settings |
| Backup & restore | Dumps, restores, base backups and PITR |
| Users, roles & grants | Roles, privileges, row-level security and pg_hba.conf |
| Common errors | SQLSTATE codes and what to do about them |
| Go snippets | pgx pool, queries, transactions and DSN options |
| Laravel snippets | Config, raw queries, locks and upsert |
| References | Official documentation |
Connection
| Task | Command | Notes |
|---|---|---|
| Connect with flags | psql -h db.example.com -p 5432 -U app -d shop | -W forces a password prompt; password can come from PGPASSWORD or ~/.pgpass |
| Connect with a URI | psql "postgresql://app:secret@db:5432/shop?sslmode=verify-full" | Same URI works in pgx, libpq, Laravel DB_URL |
| Run one statement | psql -d shop -c "select now()" | -c can be repeated; each runs in its own implicit transaction |
| Run a file | psql -d shop -v ON_ERROR_STOP=1 -1 -f schema.sql | -1 wraps the file in one transaction; ON_ERROR_STOP aborts at the first error |
| Script-friendly output | psql -At -F',' -d shop -c "select id,name from users" | -A unaligned, -t tuples only, -F field separator |
| Env defaults | PGHOST PGPORT PGUSER PGDATABASE PGSSLMODE PGAPPNAME | libpq reads these when a flag is missing |
| List databases | psql -l | Same as \l inside psql |
| Connection string keywords | host=db port=5432 dbname=shop user=app sslmode=require connect_timeout=5 | key=value form, space separated |
| Check what you are connected to | select current_database(), current_user, inet_server_addr(), version(); | Run after every failover or pooler change |
Meta-commands (psql)
| Task | Command | Notes |
|---|---|---|
| List tables / with sizes | \dt / \dt+ | \dt *.* shows every schema |
| Describe a table | \d users / \d+ users | Columns, indexes, constraints, FKs, triggers; + adds storage and description |
| List indexes, views, sequences | \di \dv \ds | Add + for size |
| Schemas, roles, extensions | \dn \du \dx | \du+ shows role attributes |
| List functions / show source | \df / \sf my_func | \sv does the same for views |
| Privileges | \dp users (alias \z) | Shows the ACL string |
| Switch database / user | \c shop / \c shop app | Opens a new connection |
| Expanded output | \x auto | Switches to vertical layout only when the row is too wide |
| Timing | \timing on | Prints elapsed ms per statement |
| Repeat a query | select now() \watch 2 | Re-runs every 2 seconds until interrupted |
| Generate then run SQL | see Diagnostic queries | \gexec executes every cell of the result as a statement |
| Client-side copy | \copy users to 'users.csv' csv header | Reads or writes on the client machine, no superuser needed |
| Edit last query | \e | Opens $EDITOR |
| Variables | \set ON_ERROR_STOP on / \echo :DBNAME | \set with no args lists all variables |
| Run a file / quit | \i file.sql / \q | \ir is relative to the current script |
| Help | \? \h CREATE INDEX | \h shows SQL syntax |
DDL
| Task | Command | Notes |
|---|---|---|
| Create table | see Diagnostic queries | Prefer identity over serial; prefer timestamptz |
| Add / drop column | alter table orders add column note text; / alter table orders drop column note; | Adding a nullable column or a constant default is a metadata-only change |
| Change type | alter table orders alter column total type numeric(14,2); | May rewrite the table and take ACCESS EXCLUSIVE |
| Rename | alter table orders rename to sales; | Also rename column a to b |
| Primary / unique | alter table orders add constraint orders_pk primary key (id); | unique nulls not distinct (col) treats NULLs as equal (v15+) |
| Foreign key without long lock | see Diagnostic queries | NOT VALID skips the scan; validate takes a weaker lock |
| Check constraint | alter table orders add constraint pos check (total >= 0); | Also supports not valid + validate constraint |
| Exclusion constraint | exclude using gist (room with =, during with &&) | Needs btree_gist for = on scalars |
| Not null / default | alter table orders alter column note set not null; / set default 'x' | set not null scans unless a validated check proves it |
| Enum / domain | create type status as enum ('new','paid'); / create domain pos_int as int check (value > 0); | Enum values can be added, not removed |
| Generated column | alter table orders add column gross numeric generated always as (total * 1.2) stored; | Stored only; v18 adds virtual generated columns |
| Identity restart | alter table orders alter column id restart with 1000; | Use setval for classic sequences |
| Range partition | create table ev (id bigint, at timestamptz not null) partition by range (at); | The partition key must be part of any primary key |
| Create a partition | create table ev_2026_11 partition of ev for values from ('2026-11-01') to ('2026-12-01'); | Upper bound exclusive |
| List / hash partition | partition by list (region) / partition by hash (id) + for values with (modulus 4, remainder 0) | Hash needs all remainders created |
| Detach online | alter table ev detach partition ev_2026_11 concurrently; | Not allowed with a default partition |
| Unlogged / temp | create unlogged table t (...) / create temp table t (...) | Unlogged skips WAL and is truncated after a crash |
| Drop / truncate | drop table if exists t cascade; / truncate t restart identity; | cascade follows dependents, double-check |
| Transactional DDL | begin; alter table ...; rollback; | Most DDL is transactional in PostgreSQL |
DML
| Task | Command | Notes |
|---|---|---|
| Insert and return | insert into users (email) values ('a@x.io') returning id, created_at; | RETURNING also works on update, delete, merge |
| Multi-row insert | insert into t (a,b) values (1,'x'),(2,'y'); | Faster than many single inserts |
| Upsert | insert into kv (k,v) values ('a',1) on conflict (k) do update set v = excluded.v; | excluded is the proposed row; target must match a unique index |
| Insert if absent | insert into kv (k,v) values ('a',1) on conflict do nothing; | Returns no row when skipped |
| Update with join | update orders o set status='paid' from payments p where p.order_id = o.id returning o.id; | FROM joins extra tables |
| Delete with join | delete from sessions s using users u where u.id = s.user_id and u.banned; | USING is the delete analog of FROM |
| MERGE | see Diagnostic queries | v15+; v17 adds RETURNING |
| CTE | with recent as (select * from orders where created_at > now() - interval '1 day') select count(*) from recent; | Since v12 CTEs are inlined unless materialized is written |
| Recursive CTE | with recursive t(n) as (select 1 union all select n+1 from t where n < 5) select * from t; | Always bound the recursion |
| Data-modifying CTE | with d as (delete from queue where id = 1 returning *) insert into archive select * from d; | One statement, one snapshot |
| Window: rank | select *, row_number() over (partition by user_id order by created_at desc) rn from orders; | Filter rn = 1 in an outer query for latest-per-group |
| Window: running total | sum(total) over (order by created_at rows between unbounded preceding and current row) | Also lag(), lead(), ntile(), rank() |
| Latest per group | select distinct on (user_id) * from orders order by user_id, created_at desc; | PostgreSQL-specific, needs matching ORDER BY |
| JSON access | select data->'a'->>'b', data #>> '{a,b}' from docs; | -> returns jsonb, ->> returns text |
| JSON containment | select * from docs where data @> '{"role":"admin"}'; | Uses a GIN index on data |
| JSON build / expand | jsonb_build_object('a',1), jsonb_agg(x), jsonb_array_elements(d->'items') | jsonb_each, jsonb_set, jsonb_path_query also useful |
| JSON modify | update docs set data = jsonb_set(data, '{a}', '2'); | Whole value is rewritten |
| Arrays | select * from t where tags && array['a','b']; | @> contains, && overlaps, unnest() expands |
| Pagination | select * from orders where (created_at, id) < ($1, $2) order by created_at desc, id desc limit 50; | Keyset beats OFFSET on deep pages |
| Explain | explain (analyze, buffers) select ...; | analyze really executes; wrap writes in a rolled-back transaction |
| Bulk load | copy users (id,email) from stdin csv; | Fastest load path; use \copy from psql |
| GROUP BY / HAVING, window and pagination patterns | SQL Queries & Indexes Cheatsheet | worked examples with plan lines |
Indexes
| Task | Command | Notes |
|---|---|---|
| B-tree (default) | create index on orders (user_id, created_at desc); | Equality, range, sort; column order matters |
| Without blocking writes | create index concurrently idx_o_u on orders (user_id); | Cannot run inside a transaction; failure leaves an INVALID index to drop |
| Rebuild online | reindex index concurrently idx_o_u; | Also reindex table concurrently (v12+) |
| Unique | create unique index on users (lower(email)); | Doubles as an expression index |
| Partial | create index on orders (user_id) where status = 'open'; | Query must imply the predicate |
| Expression | create index on users (lower(email)); | Query must use the same expression |
| Covering | create index on orders (user_id) include (total); | Enables index-only scans; INCLUDE columns are not searchable keys |
| Hash | create index on t using hash (token); | Equality only |
| GIN (jsonb, arrays, FTS) | create index on docs using gin (data jsonb_path_ops); | Slow writes, fast containment; gin_trgm_ops for LIKE '%x%' |
| GiST / SP-GiST | create index on places using gist (geom); | Ranges, geometry, nearest neighbour |
| BRIN | create index on ev using brin (at); | Tiny; works when values correlate with physical order |
| Drop online | drop index concurrently idx_o_u; | No CASCADE option with concurrently |
| Index sizes | see Diagnostic queries | |
| Unused indexes | see Diagnostic queries | Counters reset with pg_stat_reset(); check all replicas |
| Invalid indexes | select indexrelid::regclass from pg_index where not indisvalid; | Left behind by a failed CONCURRENTLY |
| Missing FK indexes | see Diagnostic queries | Heuristic, review by hand |
| Worked examples | SQL Queries & Indexes Cheatsheet | composite order, sort path, "is the index used?", GROUP BY / HAVING |
Transactions & isolation
| Task | Command | Notes |
|---|---|---|
| Start with options | begin isolation level repeatable read read only deferrable; | Options: isolation level, read write or read only, [not] deferrable |
| Set after BEGIN | set transaction isolation level serializable; | Must come before the first query |
| Session default | set session characteristics as transaction isolation level repeatable read; | Or default_transaction_isolation setting |
| Levels | read committed (default), repeatable read, serializable | read uncommitted behaves as read committed |
| Savepoints | savepoint a; ... rollback to savepoint a; release savepoint a; | Lets a transaction survive a failed statement |
| Commit / rollback | commit; / rollback; | After an error the transaction is aborted (25P02) until rollback |
| Pessimistic row lock | select * from accounts where id = 1 for update; | Blocks other writers and lockers of that row |
| Weaker locks | for share, for no key update, for key share | no key update is what FK checks conflict least with |
| Fail fast | select ... for update nowait; | Error 55P03 instead of waiting |
| Queue worker | select * from jobs where state='new' order by id limit 10 for update skip locked; | Locked rows are skipped, no double pick |
| Limit one table | select ... for update of orders; | Needed when joining |
| Table lock | lock table t in share row exclusive mode; | Eight modes; ACCESS EXCLUSIVE is the default |
| Advisory lock (session) | select pg_advisory_lock(42); / pg_advisory_unlock(42) | Survives COMMIT; leaks with pooled connections |
| Advisory lock (xact) | select pg_try_advisory_xact_lock(42); | Released at commit; returns boolean, never waits |
| Lock timeout | set local lock_timeout = '2s'; | Always set before DDL on live tables |
| Statement timeout | set local statement_timeout = '5s'; | Also idle_in_transaction_session_timeout |
| Retry rule | Retry on 40001 (serialization failure) and 40P01 (deadlock) | Retry the whole transaction, not the statement |
| Two-phase commit | prepare transaction 'tx1'; / commit prepared 'tx1'; | Needs max_prepared_transactions > 0 |
Admin & monitoring
| Task | Command | Notes |
|---|---|---|
| Active queries | see Diagnostic queries | state: active, idle, idle in transaction |
| Idle in transaction | see Diagnostic queries | Holds locks and blocks vacuum |
| Cancel / kill | select pg_cancel_backend(pid); / select pg_terminate_backend(pid); | Cancel stops the query, terminate drops the connection |
| Who blocks whom | see Diagnostic queries | Follow the chain to the root blocker |
| Lock waits | select * from pg_locks where not granted; | Join pg_stat_activity on pid |
| Top queries | see Diagnostic queries | Needs shared_preload_libraries = 'pg_stat_statements' and create extension pg_stat_statements |
| Reset statements | select pg_stat_statements_reset(); | |
| Table activity | see Diagnostic queries | High seq_scan on big tables suggests a missing index |
| Vacuum progress | select * from pg_stat_progress_vacuum; | Also pg_stat_progress_create_index, _analyze, _cluster |
| Manual vacuum | vacuum (verbose, analyze) orders; | vacuum full rewrites and locks, avoid on live tables |
| Wraparound risk | select datname, age(datfrozenxid) from pg_database order by 2 desc; | Alarm well before 2 billion |
| Database size | select pg_size_pretty(pg_database_size(current_database())); | |
| Table size | see Diagnostic queries | Total includes indexes and TOAST |
| Biggest tables | see Diagnostic queries | |
| Cache hit ratio | select sum(blks_hit)*100.0/nullif(sum(blks_hit+blks_read),0) from pg_stat_database; | Aim for 99 percent on OLTP |
| Replication status (primary) | select client_addr, state, sent_lsn, replay_lsn, replay_lag from pg_stat_replication; | *_lag columns are intervals |
| Lag in bytes | select pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) from pg_stat_replication; | |
| Replica lag (standby) | select now() - pg_last_xact_replay_timestamp(); | Misleading when the primary is idle |
| Is this a replica | select pg_is_in_recovery(); | |
| Replication slots | see Diagnostic queries | An inactive slot holds WAL forever |
| Reload config | select pg_reload_conf(); | Applies sighup parameters without restart |
| Show a setting | see Diagnostic queries | context says whether restart is needed |
| Persist a setting | alter system set work_mem = '64MB'; | Writes postgresql.auto.conf; then reload |
Diagnostic queries
Long queries moved out of the tables above, in table order; each table row points here.
Generate then run SQL. \gexec executes every cell of the result as a statement.
SELECT format('vacuum %I', relname) FROM pg_class WHERE relkind = 'r' \gexecCreate table. Prefer identity over serial; prefer timestamptz.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id bigint NOT NULL,
total numeric(12,2) NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now()
);Foreign key without long lock. NOT VALID skips the scan; validate takes a weaker lock.
ALTER TABLE orders ADD CONSTRAINT fk_u FOREIGN KEY (user_id) REFERENCES users(id) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT fk_u;MERGE. v15+; v17 adds RETURNING.
MERGE INTO stock s
USING inc i ON s.sku = i.sku
WHEN MATCHED THEN UPDATE SET qty = s.qty + i.qty
WHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (i.sku, i.qty);Index sizes.
SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid))
FROM pg_stat_user_indexes
ORDER BY pg_relation_size(indexrelid) DESC;Unused indexes. Counters reset with pg_stat_reset(); check all replicas.
SELECT s.relname, s.indexrelname, s.idx_scan, pg_size_pretty(pg_relation_size(s.indexrelid)) sz
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0 AND NOT i.indisunique AND NOT i.indisprimary
ORDER BY pg_relation_size(s.indexrelid) DESC;Missing FK indexes. Heuristic, review by hand.
SELECT conrelid::regclass, conname
FROM pg_constraint c
WHERE contype = 'f'
AND NOT EXISTS (
SELECT 1 FROM pg_index i
WHERE i.indrelid = c.conrelid
AND (i.indkey::int2[])[0:cardinality(c.conkey)-1] @> c.conkey
);Active queries. state: active, idle, idle in transaction.
SELECT pid, usename, state, wait_event_type, wait_event, now()-query_start AS age, left(query,80)
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY age DESC;Idle in transaction. Holds locks and blocks vacuum.
SELECT pid, now()-xact_start AS age, query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY age DESC;Who blocks whom. Follow the chain to the root blocker.
SELECT pid, pg_blocking_pids(pid) AS blockers, query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;Top queries. Needs shared_preload_libraries = 'pg_stat_statements' and create extension pg_stat_statements.
SELECT calls, round(mean_exec_time::numeric,2) mean_ms, round(total_exec_time::numeric) total_ms, left(query,80)
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;Table activity. High seq_scan on big tables suggests a missing index.
SELECT relname, seq_scan, idx_scan, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;Table size. Total includes indexes and TOAST.
SELECT pg_size_pretty(pg_total_relation_size('orders')),
pg_size_pretty(pg_relation_size('orders'));Biggest tables.
SELECT relid::regclass, pg_size_pretty(pg_total_relation_size(relid))
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 10;Replication slots. An inactive slot holds WAL forever.
SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) retained
FROM pg_replication_slots;Show a setting. context says whether restart is needed.
SHOW work_mem;
SELECT name, setting, unit, context, pending_restart
FROM pg_settings
WHERE name = 'work_mem';Config knobs
| Task | Command | Notes |
|---|---|---|
max_connections | Default 100 | Keep low, put a pooler (PgBouncer) in front |
shared_buffers | Default 128MB | Start near 25 percent of RAM; restart required |
work_mem | Default 4MB | Per sort or hash node per query, not per connection; raise per role or session |
maintenance_work_mem | Default 64MB | Speeds CREATE INDEX and vacuum |
effective_cache_size | Default 4GB | Planner hint only, allocates nothing; counts shared_buffers plus OS cache; sizing rule of thumb not verified |
wal_level | Default replica | logical for logical replication and CDC |
max_wal_size | Default 1GB | Raise to cut checkpoint frequency on write-heavy loads |
checkpoint_timeout | Default 5min | Longer means fewer checkpoints, longer crash recovery |
random_page_cost | Default 4.0 | Lower it on SSD (1.1 is common advice, not stated in the docs) |
autovacuum_vacuum_scale_factor | Default 0.2 | Lower per big table with alter table ... set (autovacuum_vacuum_scale_factor = 0.02) |
idle_in_transaction_session_timeout | Default 0 (off) | Set to e.g. 60s to kill forgotten transactions |
statement_timeout | Default 0 (off) | Set per role for web workloads |
lock_timeout | Default 0 (off) | Set in migrations |
synchronous_commit | Default on | off trades up to a few WAL-writer cycles of durability for latency |
log_min_duration_statement | Default -1 (off) | Set 200 to log slow queries in ms |
Backup & restore
| Task | Command | Notes |
|---|---|---|
| Logical dump, custom format | pg_dump -Fc -d shop -f shop.dump | Compressed, restores selectively and in parallel |
| Parallel directory dump | pg_dump -Fd -j 4 -d shop -f dumpdir | -j only with directory format |
| Plain SQL dump | pg_dump -d shop --no-owner > shop.sql | Restore with psql -f |
| Schema only / data only | pg_dump -s -d shop / pg_dump -a -d shop | |
| One table | pg_dump -t orders -d shop -Fc -f orders.dump | |
| Restore | pg_restore -d shop_new -j 4 --clean --if-exists shop.dump | Create the target database first |
| All databases and roles | pg_dumpall -g > globals.sql | -g globals only (roles, tablespaces) |
| Physical base backup | pg_basebackup -h primary -D /backup -Ft -z -P -X stream | Starting point for a replica or PITR |
| PITR setup | archive_mode = on, archive_command, then restore_command plus recovery_target_time | Put recovery.signal in the data dir |
| Quick copy of a table | \copy (select * from orders) to 'o.csv' csv header |
Users, roles & grants
| Task | Command | Notes |
|---|---|---|
| Login role | create role app login password 'secret'; | create user is the same with LOGIN |
| Group role | create role readonly nologin; grant readonly to app; | Membership inherits privileges by default |
| Database access | grant connect on database shop to app; | |
| Schema access | grant usage on schema public to app; | Without USAGE, tables are invisible |
| Table access | grant select, insert, update on all tables in schema public to app; | Existing tables only |
| Future tables | alter default privileges in schema public grant select on tables to readonly; | Applies to objects created by the current role |
| Revoke | revoke all on schema public from public; | v15+ already removes CREATE from public |
| Row-level security | alter table docs enable row level security; create policy p on docs using (owner = current_user); | Table owners bypass unless force row level security |
| Change password | alter role app password 'new'; | Use scram-sha-256 (password_encryption) |
| Drop role | reassign owned by old to new; drop owned by old; drop role old; | |
| pg_hba.conf line | hostssl shop app 10.0.0.0/8 scram-sha-256 | Reload after edit; select * from pg_hba_file_rules; to check |
Common errors
| Task | Command | Notes |
|---|---|---|
23505 unique_violation | duplicate key value violates unique constraint | Use ON CONFLICT or catch and map to 409 |
23503 foreign_key_violation | insert or delete breaks a reference | Insert parent first; check cascade rules |
23502 not_null_violation | null in a NOT NULL column | |
40001 serialization_failure | could not serialize access | Retry the entire transaction |
40P01 deadlock_detected | deadlock detected | Lock rows in a consistent order; retry |
55P03 lock_not_available | NOWAIT or lock_timeout hit | Back off and retry |
57014 query_canceled | statement timeout or cancel | Tune statement_timeout or the query |
25P02 in_failed_sql_transaction | commands ignored until end of transaction block | Roll back or use savepoints |
42P01 undefined_table | relation does not exist | Check search_path and schema |
42703 undefined_column | column does not exist | |
53300 too_many_connections | sorry, too many clients already | Use a pooler; lower pool sizes |
28P01 invalid_password | password authentication failed | |
08006 connection_failure | connection lost | Reconnect and retry idempotent work |
Go snippets
// go get github.com/jackc/pgx/v5
pool, err := pgxpool.New(ctx, "postgres://app:secret@db:5432/shop?sslmode=verify-full&pool_max_conns=10")
if err != nil { return err }
defer pool.Close()
// Query one row
var name string
err = pool.QueryRow(ctx, "select name from users where id = $1", id).Scan(&name)
// Query many rows
rows, _ := pool.Query(ctx, "select id, email from users where active")
users, err := pgx.CollectRows(rows, pgx.RowToStructByName[User])
// Transaction with retry-friendly helper
err = pgx.BeginTxFunc(ctx, pool, pgx.TxOptions{IsoLevel: pgx.Serializable}, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, "update accounts set balance = balance - $1 where id = $2", amt, from)
return err
})
// database/sql with the pgx driver
db, _ := sql.Open("pgx", dsn) // import _ "github.com/jackc/pgx/v5/stdlib"
db.SetMaxOpenConns(10); db.SetConnMaxLifetime(30 * time.Minute)| Task | Command | Notes |
|---|---|---|
| DSN forms | URL or host=db user=app dbname=shop sslmode=require | Both accepted by pgx.Connect and pgxpool.New |
| Pool settings | pool_max_conns, pool_min_conns, pool_max_conn_lifetime, pool_health_check_period | pgxpool URL parameters |
| Detect error code | var pe *pgconn.PgError; errors.As(err, &pe); pe.Code == "23505" | Compare against SQLSTATE strings |
| Batch | b := &pgx.Batch{}; b.Queue(sql, args...); pool.SendBatch(ctx, b) | One round trip for many statements |
| Bulk load | pool.CopyFrom(ctx, pgx.Identifier{"users"}, cols, pgx.CopyFromRows(rows)) | Uses the COPY protocol |
Laravel snippets
// config/database.php (env: DB_CONNECTION=pgsql, DB_URL=postgresql://app:secret@db:5432/shop)
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'sslmode' => 'prefer',
],
$rows = DB::select('select * from users where active = ?', [1]);
DB::statement('drop table temp_users');
DB::transaction(function () {
DB::update('update accounts set balance = balance - 10 where id = ?', [1]);
}, attempts: 3);
$user = DB::table('users')->where('id', $id)->lockForUpdate()->first(); // inside a transaction
$job = DB::selectOne("select * from jobs where state = 'new' order by id limit 1 for update skip locked"); // inside a transaction| Task | Command | Notes |
|---|---|---|
| Raw read / write | DB::select(), DB::insert(), DB::update(), DB::delete(), DB::statement() | Always bind with ? placeholders |
| Manual transaction | DB::beginTransaction(); DB::commit(); DB::rollBack(); | DB::transaction($cb, $attempts) retries on deadlock |
| Shared lock | ->sharedLock() | Maps to FOR SHARE on PostgreSQL |
| Log queries | DB::listen(fn ($q) => logger($q->sql, $q->bindings)); | Put in a service provider |
| Upsert | DB::table('kv')->upsert($rows, ['k'], ['v']); | Generates ON CONFLICT |
References
- SQL commands: INSERT, SELECT (locking clause), SET TRANSACTION, CREATE INDEX
- psql for connection flags and meta-commands
- Cumulative statistics system (pg_stat views) for monitoring queries
- Explicit locking for row, table and advisory locks
- pg_dump, pg_restore, pg_basebackup
- Error codes appendix
- pgx README for DSN,
pgxpoolanddatabase/sqlusage - Laravel 13 Database and Query Builder for configuration, transactions and locking