Skip to content

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 ​

SectionUse it when
ConnectionConnecting, URIs, environment defaults and checking where you landed
Meta-commands (psql)Meta-commands inside psql: describing objects, \watch, \copy, \gexec
DDLCreating and altering tables, constraints and partitions
DMLInserts, upserts, MERGE, CTEs, windows, JSON and pagination
IndexesChoosing, building and auditing indexes
Transactions & isolationIsolation levels, row and advisory locks, timeouts and retries
Admin & monitoringSessions, locks, statistics, vacuum, replication and settings
Diagnostic queriesLong SQL moved out of the tables, ready to paste
Config knobsDefaults and sizing hints for the main settings
Backup & restoreDumps, restores, base backups and PITR
Users, roles & grantsRoles, privileges, row-level security and pg_hba.conf
Common errorsSQLSTATE codes and what to do about them
Go snippetspgx pool, queries, transactions and DSN options
Laravel snippetsConfig, raw queries, locks and upsert
ReferencesOfficial documentation

Connection ​

TaskCommandNotes
Connect with flagspsql -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 URIpsql "postgresql://app:secret@db:5432/shop?sslmode=verify-full"Same URI works in pgx, libpq, Laravel DB_URL
Run one statementpsql -d shop -c "select now()"-c can be repeated; each runs in its own implicit transaction
Run a filepsql -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 outputpsql -At -F',' -d shop -c "select id,name from users"-A unaligned, -t tuples only, -F field separator
Env defaultsPGHOST PGPORT PGUSER PGDATABASE PGSSLMODE PGAPPNAMElibpq reads these when a flag is missing
List databasespsql -lSame as \l inside psql
Connection string keywordshost=db port=5432 dbname=shop user=app sslmode=require connect_timeout=5key=value form, space separated
Check what you are connected toselect current_database(), current_user, inet_server_addr(), version();Run after every failover or pooler change

Meta-commands (psql) ​

TaskCommandNotes
List tables / with sizes\dt / \dt+\dt *.* shows every schema
Describe a table\d users / \d+ usersColumns, indexes, constraints, FKs, triggers; + adds storage and description
List indexes, views, sequences\di \dv \dsAdd + 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 appOpens a new connection
Expanded output\x autoSwitches to vertical layout only when the row is too wide
Timing\timing onPrints elapsed ms per statement
Repeat a queryselect now() \watch 2Re-runs every 2 seconds until interrupted
Generate then run SQLsee Diagnostic queries\gexec executes every cell of the result as a statement
Client-side copy\copy users to 'users.csv' csv headerReads or writes on the client machine, no superuser needed
Edit last query\eOpens $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 ​

TaskCommandNotes
Create tablesee Diagnostic queriesPrefer identity over serial; prefer timestamptz
Add / drop columnalter 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 typealter table orders alter column total type numeric(14,2);May rewrite the table and take ACCESS EXCLUSIVE
Renamealter table orders rename to sales;Also rename column a to b
Primary / uniquealter table orders add constraint orders_pk primary key (id);unique nulls not distinct (col) treats NULLs as equal (v15+)
Foreign key without long locksee Diagnostic queriesNOT VALID skips the scan; validate takes a weaker lock
Check constraintalter table orders add constraint pos check (total >= 0);Also supports not valid + validate constraint
Exclusion constraintexclude using gist (room with =, during with &&)Needs btree_gist for = on scalars
Not null / defaultalter table orders alter column note set not null; / set default 'x'set not null scans unless a validated check proves it
Enum / domaincreate type status as enum ('new','paid'); / create domain pos_int as int check (value > 0);Enum values can be added, not removed
Generated columnalter table orders add column gross numeric generated always as (total * 1.2) stored;Stored only; v18 adds virtual generated columns
Identity restartalter table orders alter column id restart with 1000;Use setval for classic sequences
Range partitioncreate table ev (id bigint, at timestamptz not null) partition by range (at);The partition key must be part of any primary key
Create a partitioncreate table ev_2026_11 partition of ev for values from ('2026-11-01') to ('2026-12-01');Upper bound exclusive
List / hash partitionpartition by list (region) / partition by hash (id) + for values with (modulus 4, remainder 0)Hash needs all remainders created
Detach onlinealter table ev detach partition ev_2026_11 concurrently;Not allowed with a default partition
Unlogged / tempcreate unlogged table t (...) / create temp table t (...)Unlogged skips WAL and is truncated after a crash
Drop / truncatedrop table if exists t cascade; / truncate t restart identity;cascade follows dependents, double-check
Transactional DDLbegin; alter table ...; rollback;Most DDL is transactional in PostgreSQL

DML ​

TaskCommandNotes
Insert and returninsert into users (email) values ('a@x.io') returning id, created_at;RETURNING also works on update, delete, merge
Multi-row insertinsert into t (a,b) values (1,'x'),(2,'y');Faster than many single inserts
Upsertinsert 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 absentinsert into kv (k,v) values ('a',1) on conflict do nothing;Returns no row when skipped
Update with joinupdate orders o set status='paid' from payments p where p.order_id = o.id returning o.id;FROM joins extra tables
Delete with joindelete from sessions s using users u where u.id = s.user_id and u.banned;USING is the delete analog of FROM
MERGEsee Diagnostic queriesv15+; v17 adds RETURNING
CTEwith 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 CTEwith 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 CTEwith d as (delete from queue where id = 1 returning *) insert into archive select * from d;One statement, one snapshot
Window: rankselect *, 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 totalsum(total) over (order by created_at rows between unbounded preceding and current row)Also lag(), lead(), ntile(), rank()
Latest per groupselect distinct on (user_id) * from orders order by user_id, created_at desc;PostgreSQL-specific, needs matching ORDER BY
JSON accessselect data->'a'->>'b', data #>> '{a,b}' from docs;-> returns jsonb, ->> returns text
JSON containmentselect * from docs where data @> '{"role":"admin"}';Uses a GIN index on data
JSON build / expandjsonb_build_object('a',1), jsonb_agg(x), jsonb_array_elements(d->'items')jsonb_each, jsonb_set, jsonb_path_query also useful
JSON modifyupdate docs set data = jsonb_set(data, '{a}', '2');Whole value is rewritten
Arraysselect * from t where tags && array['a','b'];@> contains, && overlaps, unnest() expands
Paginationselect * from orders where (created_at, id) < ($1, $2) order by created_at desc, id desc limit 50;Keyset beats OFFSET on deep pages
Explainexplain (analyze, buffers) select ...;analyze really executes; wrap writes in a rolled-back transaction
Bulk loadcopy users (id,email) from stdin csv;Fastest load path; use \copy from psql
GROUP BY / HAVING, window and pagination patternsSQL Queries & Indexes Cheatsheetworked examples with plan lines

Indexes ​

TaskCommandNotes
B-tree (default)create index on orders (user_id, created_at desc);Equality, range, sort; column order matters
Without blocking writescreate index concurrently idx_o_u on orders (user_id);Cannot run inside a transaction; failure leaves an INVALID index to drop
Rebuild onlinereindex index concurrently idx_o_u;Also reindex table concurrently (v12+)
Uniquecreate unique index on users (lower(email));Doubles as an expression index
Partialcreate index on orders (user_id) where status = 'open';Query must imply the predicate
Expressioncreate index on users (lower(email));Query must use the same expression
Coveringcreate index on orders (user_id) include (total);Enables index-only scans; INCLUDE columns are not searchable keys
Hashcreate 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-GiSTcreate index on places using gist (geom);Ranges, geometry, nearest neighbour
BRINcreate index on ev using brin (at);Tiny; works when values correlate with physical order
Drop onlinedrop index concurrently idx_o_u;No CASCADE option with concurrently
Index sizessee Diagnostic queries
Unused indexessee Diagnostic queriesCounters reset with pg_stat_reset(); check all replicas
Invalid indexesselect indexrelid::regclass from pg_index where not indisvalid;Left behind by a failed CONCURRENTLY
Missing FK indexessee Diagnostic queriesHeuristic, review by hand
Worked examplesSQL Queries & Indexes Cheatsheetcomposite order, sort path, "is the index used?", GROUP BY / HAVING

Transactions & isolation ​

TaskCommandNotes
Start with optionsbegin isolation level repeatable read read only deferrable;Options: isolation level, read write or read only, [not] deferrable
Set after BEGINset transaction isolation level serializable;Must come before the first query
Session defaultset session characteristics as transaction isolation level repeatable read;Or default_transaction_isolation setting
Levelsread committed (default), repeatable read, serializableread uncommitted behaves as read committed
Savepointssavepoint a; ... rollback to savepoint a; release savepoint a;Lets a transaction survive a failed statement
Commit / rollbackcommit; / rollback;After an error the transaction is aborted (25P02) until rollback
Pessimistic row lockselect * from accounts where id = 1 for update;Blocks other writers and lockers of that row
Weaker locksfor share, for no key update, for key shareno key update is what FK checks conflict least with
Fail fastselect ... for update nowait;Error 55P03 instead of waiting
Queue workerselect * from jobs where state='new' order by id limit 10 for update skip locked;Locked rows are skipped, no double pick
Limit one tableselect ... for update of orders;Needed when joining
Table locklock 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 timeoutset local lock_timeout = '2s';Always set before DDL on live tables
Statement timeoutset local statement_timeout = '5s';Also idle_in_transaction_session_timeout
Retry ruleRetry on 40001 (serialization failure) and 40P01 (deadlock)Retry the whole transaction, not the statement
Two-phase commitprepare transaction 'tx1'; / commit prepared 'tx1';Needs max_prepared_transactions > 0

Admin & monitoring ​

TaskCommandNotes
Active queriessee Diagnostic queriesstate: active, idle, idle in transaction
Idle in transactionsee Diagnostic queriesHolds locks and blocks vacuum
Cancel / killselect pg_cancel_backend(pid); / select pg_terminate_backend(pid);Cancel stops the query, terminate drops the connection
Who blocks whomsee Diagnostic queriesFollow the chain to the root blocker
Lock waitsselect * from pg_locks where not granted;Join pg_stat_activity on pid
Top queriessee Diagnostic queriesNeeds shared_preload_libraries = 'pg_stat_statements' and create extension pg_stat_statements
Reset statementsselect pg_stat_statements_reset();
Table activitysee Diagnostic queriesHigh seq_scan on big tables suggests a missing index
Vacuum progressselect * from pg_stat_progress_vacuum;Also pg_stat_progress_create_index, _analyze, _cluster
Manual vacuumvacuum (verbose, analyze) orders;vacuum full rewrites and locks, avoid on live tables
Wraparound riskselect datname, age(datfrozenxid) from pg_database order by 2 desc;Alarm well before 2 billion
Database sizeselect pg_size_pretty(pg_database_size(current_database()));
Table sizesee Diagnostic queriesTotal includes indexes and TOAST
Biggest tablessee Diagnostic queries
Cache hit ratioselect 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 bytesselect 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 replicaselect pg_is_in_recovery();
Replication slotssee Diagnostic queriesAn inactive slot holds WAL forever
Reload configselect pg_reload_conf();Applies sighup parameters without restart
Show a settingsee Diagnostic queriescontext says whether restart is needed
Persist a settingalter 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.

sql
SELECT format('vacuum %I', relname) FROM pg_class WHERE relkind = 'r' \gexec

Create table. Prefer identity over serial; prefer timestamptz.

sql
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.

sql
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.

sql
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.

sql
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.

sql
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.

sql
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.

sql
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.

sql
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.

sql
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.

sql
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.

sql
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.

sql
SELECT pg_size_pretty(pg_total_relation_size('orders')),
       pg_size_pretty(pg_relation_size('orders'));

Biggest tables.

sql
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.

sql
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.

sql
SHOW work_mem;
SELECT name, setting, unit, context, pending_restart
FROM pg_settings
WHERE name = 'work_mem';

Config knobs ​

TaskCommandNotes
max_connectionsDefault 100Keep low, put a pooler (PgBouncer) in front
shared_buffersDefault 128MBStart near 25 percent of RAM; restart required
work_memDefault 4MBPer sort or hash node per query, not per connection; raise per role or session
maintenance_work_memDefault 64MBSpeeds CREATE INDEX and vacuum
effective_cache_sizeDefault 4GBPlanner hint only, allocates nothing; counts shared_buffers plus OS cache; sizing rule of thumb not verified
wal_levelDefault replicalogical for logical replication and CDC
max_wal_sizeDefault 1GBRaise to cut checkpoint frequency on write-heavy loads
checkpoint_timeoutDefault 5minLonger means fewer checkpoints, longer crash recovery
random_page_costDefault 4.0Lower it on SSD (1.1 is common advice, not stated in the docs)
autovacuum_vacuum_scale_factorDefault 0.2Lower per big table with alter table ... set (autovacuum_vacuum_scale_factor = 0.02)
idle_in_transaction_session_timeoutDefault 0 (off)Set to e.g. 60s to kill forgotten transactions
statement_timeoutDefault 0 (off)Set per role for web workloads
lock_timeoutDefault 0 (off)Set in migrations
synchronous_commitDefault onoff trades up to a few WAL-writer cycles of durability for latency
log_min_duration_statementDefault -1 (off)Set 200 to log slow queries in ms

Backup & restore ​

TaskCommandNotes
Logical dump, custom formatpg_dump -Fc -d shop -f shop.dumpCompressed, restores selectively and in parallel
Parallel directory dumppg_dump -Fd -j 4 -d shop -f dumpdir-j only with directory format
Plain SQL dumppg_dump -d shop --no-owner > shop.sqlRestore with psql -f
Schema only / data onlypg_dump -s -d shop / pg_dump -a -d shop
One tablepg_dump -t orders -d shop -Fc -f orders.dump
Restorepg_restore -d shop_new -j 4 --clean --if-exists shop.dumpCreate the target database first
All databases and rolespg_dumpall -g > globals.sql-g globals only (roles, tablespaces)
Physical base backuppg_basebackup -h primary -D /backup -Ft -z -P -X streamStarting point for a replica or PITR
PITR setuparchive_mode = on, archive_command, then restore_command plus recovery_target_timePut recovery.signal in the data dir
Quick copy of a table\copy (select * from orders) to 'o.csv' csv header

Users, roles & grants ​

TaskCommandNotes
Login rolecreate role app login password 'secret';create user is the same with LOGIN
Group rolecreate role readonly nologin; grant readonly to app;Membership inherits privileges by default
Database accessgrant connect on database shop to app;
Schema accessgrant usage on schema public to app;Without USAGE, tables are invisible
Table accessgrant select, insert, update on all tables in schema public to app;Existing tables only
Future tablesalter default privileges in schema public grant select on tables to readonly;Applies to objects created by the current role
Revokerevoke all on schema public from public;v15+ already removes CREATE from public
Row-level securityalter table docs enable row level security; create policy p on docs using (owner = current_user);Table owners bypass unless force row level security
Change passwordalter role app password 'new';Use scram-sha-256 (password_encryption)
Drop rolereassign owned by old to new; drop owned by old; drop role old;
pg_hba.conf linehostssl shop app 10.0.0.0/8 scram-sha-256Reload after edit; select * from pg_hba_file_rules; to check

Common errors ​

TaskCommandNotes
23505 unique_violationduplicate key value violates unique constraintUse ON CONFLICT or catch and map to 409
23503 foreign_key_violationinsert or delete breaks a referenceInsert parent first; check cascade rules
23502 not_null_violationnull in a NOT NULL column
40001 serialization_failurecould not serialize accessRetry the entire transaction
40P01 deadlock_detecteddeadlock detectedLock rows in a consistent order; retry
55P03 lock_not_availableNOWAIT or lock_timeout hitBack off and retry
57014 query_canceledstatement timeout or cancelTune statement_timeout or the query
25P02 in_failed_sql_transactioncommands ignored until end of transaction blockRoll back or use savepoints
42P01 undefined_tablerelation does not existCheck search_path and schema
42703 undefined_columncolumn does not exist
53300 too_many_connectionssorry, too many clients alreadyUse a pooler; lower pool sizes
28P01 invalid_passwordpassword authentication failed
08006 connection_failureconnection lostReconnect and retry idempotent work

Go snippets ​

go
// 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)
TaskCommandNotes
DSN formsURL or host=db user=app dbname=shop sslmode=requireBoth accepted by pgx.Connect and pgxpool.New
Pool settingspool_max_conns, pool_min_conns, pool_max_conn_lifetime, pool_health_check_periodpgxpool URL parameters
Detect error codevar pe *pgconn.PgError; errors.As(err, &pe); pe.Code == "23505"Compare against SQLSTATE strings
Batchb := &pgx.Batch{}; b.Queue(sql, args...); pool.SendBatch(ctx, b)One round trip for many statements
Bulk loadpool.CopyFrom(ctx, pgx.Identifier{"users"}, cols, pgx.CopyFromRows(rows))Uses the COPY protocol

Laravel snippets ​

php
// 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
TaskCommandNotes
Raw read / writeDB::select(), DB::insert(), DB::update(), DB::delete(), DB::statement()Always bind with ? placeholders
Manual transactionDB::beginTransaction(); DB::commit(); DB::rollBack();DB::transaction($cb, $attempts) retries on deadlock
Shared lock->sharedLock()Maps to FOR SHARE on PostgreSQL
Log queriesDB::listen(fn ($q) => logger($q->sql, $q->bindings));Put in a service provider
UpsertDB::table('kv')->upsert($rows, ['k'], ['v']);Generates ON CONFLICT

References ​

Built by Morteza Negahi