764 commands · 48 cheat sheets · 6 subcategories

SQL master quick reference — Page 3

Browse 195 commands from 12 focused cheat sheets on page 3 of 4. Each example opens its matching detailed section.

Performance and Planning · 17 commands

PostgreSQL Parallel Query and JIT Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Find parallel nodesEXPLAIN (COSTS, VERBOSE) SELECT count(*) FROM app.orders;View examples
Measure workers launchedEXPLAIN (ANALYZE, SUMMARY) SELECT count(*) FROM app.orders;View examples
Show worker detailEXPLAIN (ANALYZE, VERBOSE) SELECT count(*) FROM app.orders;View examples
Set a local worker capSET LOCAL max_parallel_workers_per_gather = 4;View examples
Inspect worker settingsSELECT name, setting FROM pg_settings WHERE name LIKE 'max_parallel%';View examples
Inspect setup costSHOW parallel_setup_cost;View examples
Inspect table thresholdSHOW min_parallel_table_scan_size;View examples
Label a function safeALTER FUNCTION app.net_amount(numeric, numeric) PARALLEL SAFE;View examples
Label a function restrictedALTER FUNCTION app.read_backend_state() PARALLEL RESTRICTED;View examples
Disable parallel useALTER FUNCTION app.write_audit(text) PARALLEL UNSAFE;View examples
Disable parallelism locallySET LOCAL max_parallel_workers_per_gather = 0;View examples
Check transaction isolationSHOW transaction_isolation;View examples
Enable JIT locallySET LOCAL jit = on;View examples
Inspect the JIT thresholdSHOW jit_above_cost;View examples
Disable JIT locallySET LOCAL jit = off;View examples
Show JIT availabilitySHOW jit_provider;View examples
Track nondefault plan settingsEXPLAIN (SETTINGS, SUMMARY) SELECT sum(total) FROM app.orders;View examples

Performance and Planning · 16 commands

PostgreSQL Prepared Statements and Plan Caching Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Prepare a typed queryPREPARE order_by_id (bigint) AS SELECT id, status, total FROM app.orders WHERE id = $1;View examples
Execute a statementEXECUTE order_by_id(42001);View examples
Prepare a writePREPARE add_event (uuid, text) AS INSERT INTO app.events(account_id, kind) VALUES ($1, $2) RETURNING id;View examples
Fix parameter meaningPREPARE events_since (timestamptz) AS SELECT id FROM app.events WHERE occurred_at >= $1::timestamptz;View examples
Inspect the chosen planEXPLAIN (ANALYZE, BUFFERS, SETTINGS) EXECUTE orders_for_tenant(42);View examples
Test custom planningSET LOCAL plan_cache_mode = 'force_custom_plan';View examples
Test generic planningSET LOCAL plan_cache_mode = 'force_generic_plan';View examples
Restore automatic choiceSET plan_cache_mode = 'auto';View examples
List prepared statementsSELECT name, parameter_types, generic_plans, custom_plans FROM pg_prepared_statements ORDER BY name;View examples
Find generic-plan usersSELECT name, generic_plans, custom_plans FROM pg_prepared_statements WHERE generic_plans > 0;View examples
Discard cached plansDISCARD PLANS;View examples
Release one statementDEALLOCATE order_by_id;View examples
Release all statementsDEALLOCATE ALL;View examples
Pin object resolutionPREPARE active_accounts AS SELECT id FROM app.accounts WHERE disabled_at IS NULL;View examples
Check server versionSHOW server_version;View examples
Identify two-phase stateSELECT gid, prepared, owner, database FROM pg_prepared_xacts ORDER BY prepared;View examples

Performance and Planning · 16 commands

PostgreSQL Statistics and Cardinality Estimation Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Inspect estimated rows onlyEXPLAIN SELECT * FROM app.orders WHERE status = 'open';View examples
Measure actual rowsEXPLAIN (ANALYZE, BUFFERS) SELECT * FROM app.orders WHERE status = 'open';View examples
Expose planning settingsEXPLAIN (ANALYZE, SETTINGS) SELECT count(*) FROM app.orders;View examples
Analyze one tableANALYZE app.orders;View examples
Analyze selected columnsANALYZE app.orders (tenant_id, status);View examples
Inspect table statisticsSELECT * FROM pg_stats WHERE schemaname = 'app' AND tablename = 'orders';View examples
Check approximate table sizeSELECT reltuples, relpages FROM pg_class WHERE oid = 'app.orders'::regclass;View examples
Set a column targetALTER TABLE app.orders ALTER COLUMN tenant_id SET STATISTICS 500;View examples
Restore the default targetALTER TABLE app.orders ALTER COLUMN tenant_id SET STATISTICS DEFAULT;View examples
Create dependency statisticsCREATE STATISTICS app.orders_dep (dependencies) ON tenant_id, region FROM app.orders;View examples
Create MCV statisticsCREATE STATISTICS app.orders_mcv (mcv) ON tenant_id, status FROM app.orders;View examples
Inspect extended statisticsSELECT * FROM pg_stats_ext WHERE statistics_name = 'orders_tenant_status';View examples
Set a proportional distinct estimateALTER TABLE app.events ALTER COLUMN tenant_id SET (n_distinct = -0.02);View examples
Remove a distinct overrideALTER TABLE app.events ALTER COLUMN tenant_id RESET (n_distinct);View examples
Analyze a partition hierarchyANALYZE app.events;View examples
Inspect extended-stat data safelySELECT statistics_name, kinds FROM pg_stats_ext WHERE schemaname = 'app';View examples

Performance and Planning · 17 commands

PostgreSQL System Catalogs and Information Schema Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
List visible tablesSELECT table_schema, table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE';View examples
List PostgreSQL relationsSELECT oid::regclass, relkind FROM pg_catalog.pg_class WHERE relnamespace = 'app'::regnamespace;View examples
Resolve the catalog schemaSELECT pg_catalog.current_schema();View examples
Resolve a relation OIDSELECT to_regclass('app.orders');View examples
Find a relation kindSELECT relkind FROM pg_class WHERE oid = 'app.orders'::regclass;View examples
List portable columnsSELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'app' AND table_name = 'orders';View examples
Render a PostgreSQL typeSELECT format_type(atttypid, atttypmod) FROM pg_attribute WHERE attrelid = 'app.orders'::regclass AND attnum > 0;View examples
Resolve a type safelySELECT to_regtype('pg_catalog.int8');View examples
Show index definitionsSELECT indexrelid::regclass, indisvalid, pg_get_indexdef(indexrelid) FROM pg_index WHERE indrelid = 'app.orders'::regclass;View examples
Show a constraint definitionSELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conname = 'orders_pkey';View examples
Check table privilegeSELECT has_table_privilege('app_reader', 'app.orders', 'SELECT');View examples
Check schema usageSELECT has_schema_privilege('app_reader', 'app', 'USAGE');View examples
Check function executionSELECT has_function_privilege('app_reader', 'app.total(bigint)', 'EXECUTE');View examples
Describe a catalog objectSELECT pg_describe_object('pg_class'::regclass, 'app.orders'::regclass, 0);View examples
Inspect dependenciesSELECT * FROM pg_depend WHERE refobjid = 'app.orders'::regclass;View examples
Check server version numberSELECT current_setting('server_version_num')::int;View examples
Check recovery stateSELECT pg_is_in_recovery();View examples

Performance and Planning · 18 commands

PostgreSQL Table Partitioning and Pruning Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a range-partitioned tableCREATE TABLE events (event_id bigint, occurred_at timestamptz NOT NULL) PARTITION BY RANGE (occurred_at);View examples
Create a list-partitioned tableCREATE TABLE accounts (account_id bigint, region_code text NOT NULL) PARTITION BY LIST (region_code);View examples
Create a hash-partitioned tableCREATE TABLE jobs (job_id bigint, tenant_id bigint NOT NULL) PARTITION BY HASH (tenant_id);View examples
Create a monthly partitionCREATE TABLE events_2026_08 PARTITION OF events FOR VALUES FROM ('2026-08-01') TO ('2026-09-01');View examples
Create a default partitionCREATE TABLE events_default PARTITION OF events DEFAULT;View examples
Create a list partitionCREATE TABLE accounts_americas PARTITION OF accounts FOR VALUES IN ('BR', 'CA', 'US');View examples
Create a hash partitionCREATE TABLE jobs_h0 PARTITION OF jobs FOR VALUES WITH (MODULUS 4, REMAINDER 0);View examples
Create matching child indexesCREATE INDEX events_tenant_time_idx ON events (tenant_id, occurred_at);View examples
Declare partition-safe uniquenessPRIMARY KEY (event_id, occurred_at)View examples
Filter with matching range boundsWHERE occurred_at >= TIMESTAMPTZ '2026-08-01 00:00:00+00' AND occurred_at < TIMESTAMPTZ '2026-09-01 00:00:00+00'View examples
Inspect selected partitionsEXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE occurred_at >= TIMESTAMPTZ '2026-08-01 00:00:00+00';View examples
Check pruning configurationSHOW enable_partition_pruning;View examples
Build an attachable tableCREATE TABLE events_2026_09 (LIKE events INCLUDING DEFAULTS INCLUDING CONSTRAINTS);View examples
Validate the intended boundALTER TABLE events_2026_09 VALIDATE CONSTRAINT events_2026_09_bound;View examples
Attach a prepared partitionALTER TABLE events ATTACH PARTITION events_2026_09 FOR VALUES FROM ('2026-09-01') TO ('2026-10-01');View examples
List a partition hierarchySELECT relid, parentrelid, isleaf, level FROM pg_partition_tree('events'::regclass);View examples
Inspect partition boundsSELECT relname, pg_get_expr(relpartbound, oid) FROM pg_class WHERE relispartition ORDER BY relname;View examples
Analyze the partitioned parentANALYZE events;View examples

Transactions and Security · 17 commands

PostgreSQL Advisory Locks Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Lock for the transactionSELECT pg_advisory_xact_lock(7001, 42);View examples
Try a transaction lockSELECT pg_try_advisory_xact_lock(7001, 42);View examples
Take a shared lockSELECT pg_advisory_xact_lock_shared(7001, 42);View examples
Try a shared lockSELECT pg_try_advisory_xact_lock_shared(7001, 42);View examples
Lock for the sessionSELECT pg_advisory_lock(8001, 17);View examples
Try a session lockSELECT pg_try_advisory_lock(8001, 17);View examples
Unlock one session levelSELECT pg_advisory_unlock(8001, 17);View examples
Unlock all session locksSELECT pg_advisory_unlock_all();View examples
Bound lock waitsSET LOCAL lock_timeout = '2s';View examples
Order multiple keysSELECT DISTINCT resource_id FROM app.requested_resources WHERE batch_id = 88 ORDER BY resource_id;View examples
Limit before lockingSELECT pg_advisory_xact_lock(q.id) FROM ( SELECT id FROM app.jobs ORDER BY id LIMIT 10 ) AS q;View examples
List advisory locksSELECT pid, mode, granted, classid, objid, objsubid FROM pg_locks WHERE locktype = 'advisory';View examples
Find advisory waitersSELECT pid, mode, waitstart FROM pg_locks WHERE locktype = 'advisory' AND NOT granted ORDER BY waitstart;View examples
Find blocking processesSELECT pid, pg_blocking_pids(pid) AS blockers FROM pg_locks WHERE locktype = 'advisory' AND NOT granted;View examples
Use one 64-bit keySELECT pg_try_advisory_xact_lock(9223372036854770000::bigint);View examples
Namespace with two keysSELECT pg_try_advisory_xact_lock(7001, 42);View examples
Detect recoverySELECT pg_is_in_recovery();View examples

Transactions and Security · 17 commands

PostgreSQL Deadlocks, Timeouts, and Cancellation Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Lock rows in key orderSELECT id FROM app.accounts WHERE id = ANY (ARRAY[41,72]) ORDER BY id FOR UPDATE;View examples
Lock a table explicitlyLOCK TABLE app.ledger IN SHARE ROW EXCLUSIVE MODE;View examples
Inspect deadlock delaySHOW deadlock_timeout;View examples
Set transaction-local lock timeoutSET LOCAL lock_timeout = '2s';View examples
Disable the lock timeoutSET LOCAL lock_timeout = '0';View examples
Set a statement timeoutSET LOCAL statement_timeout = '30s';View examples
Set a role defaultALTER ROLE report_user SET statement_timeout = '30s';View examples
Inspect the timeoutSHOW statement_timeout;View examples
Bound idle transactionsSET idle_in_transaction_session_timeout = '60s';View examples
Bound a transactionSET transaction_timeout = '5min';View examples
Find blocking PIDsSELECT pg_blocking_pids(12345);View examples
List lock waitersSELECT pid, wait_event, query FROM pg_stat_activity WHERE wait_event_type = 'Lock';View examples
Inspect held locksSELECT * FROM pg_locks WHERE pid = 12345;View examples
Cancel a backend querySELECT pg_cancel_backend(12345);View examples
Terminate a backendSELECT pg_terminate_backend(12345, 5000);View examples
Inspect lock-wait loggingSHOW log_lock_waits;View examples
Inspect active transaction ageSELECT pid, xact_start, state FROM pg_stat_activity WHERE xact_start IS NOT NULL ORDER BY xact_start;View examples

Transactions and Security · 16 commands

PostgreSQL Extensions and Extension Security Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
List available extensionsSELECT name, default_version, installed_version FROM pg_available_extensions ORDER BY name;View examples
Inspect installable versionsSELECT version, installed, superuser, trusted, relocatable FROM pg_available_extension_versions WHERE name = 'pgcrypto';View examples
Create a controlled schemaCREATE SCHEMA extensions AUTHORIZATION extension_owner;View examples
Protect the target schemaREVOKE CREATE ON SCHEMA extensions FROM PUBLIC;View examples
Install a pinned versionCREATE EXTENSION pgcrypto WITH SCHEMA extensions VERSION '1.3';View examples
Install only when absentCREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA extensions VERSION '1.3';View examples
Inspect installed extensionsSELECT extname, extversion, extnamespace::regnamespace, extrelocatable FROM pg_extension ORDER BY extname;View examples
Inspect update pathsSELECT source, target, path FROM pg_extension_update_paths('pgcrypto') ORDER BY source, target;View examples
Update to a reviewed versionALTER EXTENSION pgcrypto UPDATE TO '1.3';View examples
Move a relocatable extensionALTER EXTENSION pgcrypto SET SCHEMA extensions_v2;View examples
List extension membersSELECT pg_describe_object(d.classid,d.objid,d.objsubid) FROM pg_depend d WHERE d.refobjid = ( SELECT oid FROM pg_extension WHERE extname='pgcrypto' );View examples
Attach an existing objectALTER EXTENSION app_tools ADD FUNCTION app_tools.normalize_email(text);View examples
Drop without cascadingDROP EXTENSION pgcrypto RESTRICT;View examples
Preserve configuration dataSELECT pg_catalog.pg_extension_config_dump('app_tools.settings', 'WHERE NOT built_in');View examples
Secure an update script pathSELECT pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true);View examples
Pin a function search pathALTER FUNCTION extensions.secure_length(text) SET search_path = pg_catalog, pg_temp;View examples

Transactions and Security · 18 commands

PostgreSQL pgcrypto and Data Encryption Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Install pgcryptoCREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA extensions;View examples
Check its versionSELECT extversion FROM pg_extension WHERE extname = 'pgcrypto';View examples
Check FIPS modeSELECT extensions.fips_mode();View examples
Hash text with SHA-256SELECT encode(extensions.digest('payload', 'sha256'), 'hex');View examples
Hash binary dataSELECT extensions.digest(decode('00ff', 'hex'), 'sha512');View examples
Create an HMACSELECT extensions.hmac('payload', 'secret-key', 'sha256');View examples
Encode an HMACSELECT encode(extensions.hmac('payload', 'secret-key', 'sha256'), 'base64');View examples
Generate a bcrypt hashSELECT extensions.crypt('password', extensions.gen_salt('bf', 12));View examples
Verify a passwordSELECT extensions.crypt('candidate', password_hash) = password_hash FROM app.users WHERE id = 42;View examples
Generate SHA-512 cryptSELECT extensions.crypt('password', extensions.gen_salt('sha512crypt', 100000));View examples
Encrypt text symmetricallySELECT extensions.pgp_sym_encrypt('secret', 'passphrase', 'cipher-algo=aes256');View examples
Decrypt symmetric textSELECT extensions.pgp_sym_decrypt(ciphertext, 'passphrase') FROM app.secrets WHERE secret_id = 42;View examples
Encrypt binary dataSELECT extensions.pgp_sym_encrypt_bytea(decode('00ff', 'hex'), 'passphrase');View examples
Encrypt with a public keySELECT extensions.pgp_pub_encrypt('secret', extensions.dearmor(public_key)) FROM app.keyring WHERE key_id = 3;View examples
Decrypt with a private keySELECT extensions.pgp_pub_decrypt(ciphertext, extensions.dearmor(private_key), 'key-passphrase');View examples
Generate random bytesSELECT extensions.gen_random_bytes(32);View examples
Generate a random UUIDSELECT pg_catalog.gen_random_uuid();View examples
Check builtin crypto policySHOW pgcrypto.builtin_crypto_enabled;View examples

Transactions and Security · 14 commands

PostgreSQL Row-Level Security Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Enable row securityALTER TABLE app.invoice ENABLE ROW LEVEL SECURITY;View examples
Apply RLS to the ownerALTER TABLE app.invoice FORCE ROW LEVEL SECURITY;View examples
Grant baseline privilegesGRANT SELECT, INSERT, UPDATE, DELETE ON app.invoice TO app_runtime;View examples
Filter visible rowsCREATE POLICY invoice_select ON app.invoice FOR SELECT TO app_runtime USING (tenant_id = app.current_tenant_id());View examples
Validate inserted rowsCREATE POLICY invoice_insert ON app.invoice FOR INSERT TO app_runtime WITH CHECK (tenant_id = app.current_tenant_id());View examples
Constrain updatesCREATE POLICY inv_update ON app.invoice FOR UPDATE TO app_runtime USING (tenant_id = app.current_tenant_id()) WITH CHECK (tenant_id = app.current_tenant_id());View examples
Add an allow pathCREATE POLICY support_read ON app.invoice AS PERMISSIVE FOR SELECT TO support_agent USING (assigned_to = current_user);View examples
Add a mandatory conditionCREATE POLICY no_legal_hold_delete ON app.invoice AS RESTRICTIVE FOR DELETE TO app_runtime USING (NOT legal_hold);View examples
Remove RLS bypassALTER ROLE app_runtime NOBYPASSRLS;View examples
Error instead of filteringSET LOCAL row_security = off;View examples
Scope tenant contextSET LOCAL app.tenant_id = '42';View examples
Read optional contextSELECT current_setting('app.tenant_id', true);View examples
Inspect effective definitionsSELECT * FROM pg_policies WHERE schemaname = 'app' AND tablename = 'invoice';View examples
Check RLS for this callerSELECT row_security_active('app.invoice'::regclass);View examples

Transactions and Security · 12 commands

PostgreSQL Schemas, Roles, and Privileges Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a schemaCREATE SCHEMA app AUTHORIZATION app_owner;View examples
Set role search pathALTER ROLE app_runtime SET search_path = app, pg_catalog;View examples
Create a login roleCREATE ROLE app_runtime LOGIN PASSWORD NULL;View examples
Create a group roleCREATE ROLE app_readonly NOLOGIN;View examples
Grant role membershipGRANT app_readonly TO analyst_user;View examples
Allow schema lookupGRANT USAGE ON SCHEMA app TO app_readonly;View examples
Grant existing table readsGRANT SELECT ON ALL TABLES IN SCHEMA app TO app_readonly;View examples
Grant sequence useGRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA app TO app_runtime;View examples
Revoke public schema creationREVOKE CREATE ON SCHEMA public FROM PUBLIC;View examples
Grant future table readsALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app GRANT SELECT ON TABLES TO app_readonly;View examples
Test a privilegeSELECT has_table_privilege('app_runtime', 'app.orders', 'SELECT');View examples
Transfer ownershipALTER TABLE app.orders OWNER TO app_owner;View examples

Transactions and Security · 17 commands

PostgreSQL Transactions and Locking Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Start a transactionBEGIN;View examples
Commit changesCOMMIT;View examples
Discard changesROLLBACK;View examples
Create a savepointSAVEPOINT before_optional_step;View examples
Roll back partwayROLLBACK TO SAVEPOINT before_optional_step;View examples
Release a savepointRELEASE SAVEPOINT before_optional_step;View examples
Use read committedBEGIN ISOLATION LEVEL READ COMMITTED;View examples
Use repeatable readBEGIN ISOLATION LEVEL REPEATABLE READ;View examples
Use serializableBEGIN ISOLATION LEVEL SERIALIZABLE;View examples
Declare read-only workBEGIN READ ONLY;View examples
Limit statement duration locallySET LOCAL statement_timeout = '5s';View examples
Lock selected rowsSELECT * FROM accounts WHERE id = 42 FOR UPDATE;View examples
Use a weaker update lockSELECT * FROM accounts WHERE id = 42 FOR NO KEY UPDATE;View examples
Fail instead of waitingSELECT * FROM jobs WHERE id = 7 FOR UPDATE NOWAIT;View examples
Skip locked workSELECT * FROM jobs WHERE status = 'ready' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1;View examples
Lock a table explicitlyLOCK TABLE reports IN SHARE MODE;View examples
Lock in stable orderSELECT * FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;View examples
CMDMEMO TERMINALREAD ONLY