Common queries and commands, ready to adapt and copy.
Core examples target PostgreSQL 15+. Replace names such as public.your_table, column names, dates and PIDs with your own. Each block is an independent example. Actions that change data, privileges or indexes are labelled in their description. Some monitoring details require extra privileges.
Connection, settings & transactions
Which database, server and role am I using?
Run this before doing anything else on an unfamiliar connection.
SELECT current_database() AS database_name,
current_user AS effective_role,
session_user AS login_role,
inet_server_addr() AS server_address,
inet_server_port() AS server_port,
pg_backend_pid() AS my_pid,
version() AS postgres_version;
SHOW search_path;
Find a setting and its source
Search settings without changing them. Some file-path details require additional privileges.
SELECT name, setting, unit, context, source, pending_restart
FROM pg_settings
WHERE name ILIKE '%work_mem%'
OR name IN ('max_connections', 'shared_buffers', 'statement_timeout',
'lock_timeout', 'TimeZone')
ORDER BY name;
Read-only investigation transaction
Ends with ROLLBACK so the transaction is closed. SET LOCAL lasts only for this transaction.
BEGIN READ ONLY;
SET LOCAL statement_timeout = '30s';
SET LOCAL lock_timeout = '3s';
SELECT current_database(), current_user;
-- Put inspection SELECTs here.
ROLLBACK;
Compare two queries against the same snapshot
Both queries see the same snapshot. Finish promptly; an old snapshot can hold back cleanup.
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT count(*) FROM public.your_table;
-- Run the second comparison query here.
ROLLBACK;
Transaction time versus wall-clock time
now() stays fixed within a transaction; clock_timestamp() advances.
SELECT now() AS transaction_started,
statement_timestamp() AS statement_started,
clock_timestamp() AS wall_clock,
current_setting('TimeZone') AS session_timezone;
Back to top
Schemas, tables, columns & definitions
List schemas and owners
Excludes PostgreSQL internal schemas.
SELECT nspname AS schema_name,
pg_get_userbyid(nspowner) AS owner
FROM pg_namespace
WHERE nspname NOT LIKE 'pg_%'
AND nspname <> 'information_schema'
ORDER BY nspname;
Find tables, views, materialized views and partitions
Search relation names; change the pattern. Partitioned parents do not contain their own row storage.
SELECT n.nspname AS schema_name, c.relname AS object_name,
CASE c.relkind
WHEN 'r' THEN 'table' WHEN 'p' THEN 'partitioned table'
WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view'
WHEN 'f' THEN 'foreign table'
END AS object_type,
c.relispartition AS is_partition,
pg_get_userbyid(c.relowner) AS owner
FROM pg_class AS c
JOIN pg_namespace AS n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f')
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND n.nspname NOT LIKE 'pg_toast%'
AND c.relname ILIKE '%your_name%'
ORDER BY 1, 2;
Columns, types, defaults, identity and generated expressions
Replace public.your_table. Uses PostgreSQL catalog types rather than generic information_schema type names.
SELECT a.attnum AS position, a.attname AS column_name,
format_type(a.atttypid, a.atttypmod) AS data_type,
a.attnotnull AS not_null,
pg_get_expr(d.adbin, d.adrelid) AS default_or_generation_expression,
a.attidentity AS identity_kind,
a.attgenerated AS generated_kind
FROM pg_attribute AS a
LEFT JOIN pg_attrdef AS d
ON d.adrelid = a.attrelid AND d.adnum = a.attnum
WHERE a.attrelid = 'public.your_table'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum;
Primary keys, unique keys, checks and foreign keys
convalidated = false identifies a constraint that has not been validated against all existing rows.
SELECT conname, contype, convalidated,
pg_get_constraintdef(oid, true) AS definition
FROM pg_constraint
WHERE conrelid = 'public.your_table'::regclass
ORDER BY contype, conname;
Which tables reference this table?
Incoming foreign-key dependencies.
SELECT conrelid::regclass AS referencing_table,
conname,
pg_get_constraintdef(oid, true) AS definition
FROM pg_constraint
WHERE contype = 'f'
AND confrelid = 'public.your_table'::regclass
ORDER BY 1, 2;
Show a view or materialized view definition
For CREATE TABLE DDL, use pg_dump --schema-only rather than trying to reconstruct everything from a short catalog query.
SELECT pg_get_viewdef('public.your_view'::regclass, true);
Find function signatures and definitions
Use the returned signature with pg_get_functiondef. Works for ordinary functions and procedures; aggregate definitions need other tooling.
SELECT p.oid::regprocedure AS signature,
pg_get_functiondef(p.oid) AS definition
FROM pg_proc AS p
JOIN pg_namespace AS n ON n.oid = p.pronamespace
WHERE n.nspname = 'public'
AND p.proname ILIKE '%your_function%'
AND p.prokind IN ('f', 'p')
ORDER BY 1;
Show a partition tree and partition bounds
Replace the partitioned parent table.
SELECT t.relid::regclass AS relation,
t.parentrelid::regclass AS parent,
t.isleaf, t.level,
pg_get_expr(c.relpartbound, c.oid) AS partition_bound
FROM pg_partition_tree('public.your_parent'::regclass) AS t
JOIN pg_class AS c ON c.oid = t.relid
ORDER BY t.level, t.relid::regclass::text;
Installed extensions
Shows what is installed in this database, not every extension available on the server.
SELECT extname, extversion, extnamespace::regnamespace AS schema_name
FROM pg_extension
ORDER BY extname;
Back to top
Sizes, row counts & table health
Database sizes
Requires sufficient access to calculate the size of each database.
SELECT datname,
pg_size_pretty(pg_database_size(oid)) AS size
FROM pg_database
WHERE NOT datistemplate
ORDER BY pg_database_size(oid) DESC;
Largest tables and materialized views
Heap means main table storage; total includes indexes and TOAST. Physical partitions appear separately.
SELECT n.nspname AS schema_name, c.relname,
pg_size_pretty(pg_relation_size(c.oid)) AS main_heap,
pg_size_pretty(pg_indexes_size(c.oid)) AS indexes,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total
FROM pg_class AS c
JOIN pg_namespace AS n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'm')
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND n.nspname NOT LIKE 'pg_toast%'
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 30;
One table: table/TOAST, indexes and total
pg_table_size includes TOAST and auxiliary forks. A partitioned parent does not roll up its children here.
SELECT pg_size_pretty(pg_table_size('public.your_table')) AS table_and_toast,
pg_size_pretty(pg_indexes_size('public.your_table')) AS indexes,
pg_size_pretty(pg_total_relation_size('public.your_table')) AS total;
Total size across all leaf partitions
Avoids treating the parent relation size as the size of the whole dataset.
SELECT pg_size_pretty(
coalesce(sum(pg_total_relation_size(relid)), 0)::bigint
) AS total_leaf_size
FROM pg_partition_tree('public.your_parent'::regclass)
WHERE isleaf;
Fast approximate row counts
These are estimates from statistics, not an exact COUNT(*).
SELECT schemaname, relname,
n_live_tup AS estimated_live_rows,
n_dead_tup AS estimated_dead_rows,
last_analyze, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_live_tup DESC;
Exact row count and a filtered count
An exact count can scan a large amount of data. Replace the table and condition.
SELECT count(*) AS rows_total,
count(*) FILTER (WHERE status = 'active') AS rows_active
FROM public.your_table;
Dead-row estimates, vacuum and analyze history
Dead rows are not a measurement of physical bloat. Counters depend on statistics collection and resets.
SELECT schemaname, relname, n_live_tup, n_dead_tup,
round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 2)
AS estimated_dead_percent,
n_mod_since_analyze,
last_vacuum, last_autovacuum, last_analyze, last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC;
Tables with the oldest transaction-ID age
A diagnostic starting point, not a replacement for monitoring configured freeze thresholds.
SELECT c.oid::regclass AS relation,
age(c.relfrozenxid) AS xid_age
FROM pg_class AS c
WHERE c.relkind IN ('r', 'm')
ORDER BY age(c.relfrozenxid) DESC
LIMIT 30;
Back to top
Sessions, long queries & blocking
Connection counts by database, role and state
Background processes can have null database or role values.
SELECT datname, usename, application_name, state, count(*) AS connections
FROM pg_stat_activity
GROUP BY datname, usename, application_name, state
ORDER BY connections DESC;
Currently running queries
clock_timestamp() shows real elapsed time even inside a transaction. Other sessions’ details may require pg_read_all_stats.
SELECT pid, datname, usename, application_name,
clock_timestamp() - query_start AS query_age,
wait_event_type, wait_event,
left(query, 1000) AS query
FROM pg_stat_activity
WHERE state = 'active'
AND pid <> pg_backend_pid()
ORDER BY query_start;
Idle-in-transaction sessions and oldest transactions
An idle transaction can retain locks and old snapshots.
SELECT pid, datname, usename, state,
clock_timestamp() - xact_start AS transaction_age,
clock_timestamp() - state_change AS time_in_state,
backend_xmin, left(query, 1000) AS last_query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
AND pid <> pg_backend_pid()
ORDER BY xact_start;
Who is blocking whom?
Uses pg_blocking_pids instead of a hand-written lock compatibility join.
SELECT blocked.pid AS blocked_pid,
blocked.usename AS blocked_user,
clock_timestamp() - blocked.query_start AS blocked_query_age,
left(blocked.query, 500) AS blocked_query,
blocker.pid AS blocker_pid,
blocker.state AS blocker_state,
left(blocker.query, 500) AS blocker_query
FROM pg_stat_activity AS blocked
CROSS JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid)
LEFT JOIN pg_stat_activity AS blocker ON blocker.pid = b.pid
ORDER BY blocked.query_start;
Locks for a selected backend
Replace 12345 with a PID you have inspected. Relation names are meaningful for locks in the current database.
SELECT locktype, mode, granted,
CASE WHEN database = (SELECT oid FROM pg_database
WHERE datname = current_database())
THEN relation::regclass::text END AS relation_name,
transactionid, virtualxid, waitstart
FROM pg_locks
WHERE pid = 12345
ORDER BY granted, locktype, mode;
Cancel one query without disconnecting the session
Operational action: replace 12345 with the inspected PID. Cancellation requires permission and can leave an explicit transaction aborted.
SELECT pg_cancel_backend(12345);
Current VACUUM progress
Shows active VACUUM operations, not vacuum history.
SELECT pid, datname, relid::regclass AS relation, phase,
heap_blks_total, heap_blks_scanned, heap_blks_vacuumed,
round(100.0 * heap_blks_scanned / nullif(heap_blks_total, 0), 1)
AS heap_scan_percent
FROM pg_stat_progress_vacuum;
Back to top
Indexes, usage & query plans
Index definitions, size and validity
Invalid or not-ready indexes need investigation; a failed concurrent build is one possible cause.
SELECT i.indexrelid::regclass AS index_name,
pg_size_pretty(pg_relation_size(i.indexrelid)) AS size,
i.indisprimary, i.indisunique, i.indisvalid, i.indisready,
pg_get_indexdef(i.indexrelid) AS definition
FROM pg_index AS i
WHERE i.indrelid = 'public.your_table'::regclass
ORDER BY pg_relation_size(i.indexrelid) DESC;
Index scan counters
A low scan count alone is not a reason to drop an index: consider constraints, workload coverage and statistics resets.
SELECT schemaname, relname AS table_name, indexrelname,
idx_scan, idx_tup_read, idx_tup_fetch,
pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
ORDER BY pg_relation_size(indexrelid) DESC;
SELECT stats_reset
FROM pg_stat_database
WHERE datname = current_database();
Estimated execution plan without running the query
Replace the sample SELECT. Plain EXPLAIN plans the statement without executing it.
EXPLAIN (COSTS, VERBOSE, FORMAT TEXT)
SELECT *
FROM public.your_table
WHERE id = 42;
Actual execution plan, buffers and JSON export
EXPLAIN ANALYZE executes the statement. Use a SELECT without side-effecting functions; writes and sequences have effects even during analysis.
EXPLAIN (ANALYZE, BUFFERS, SETTINGS, TIMING OFF, FORMAT JSON)
SELECT *
FROM public.your_table
WHERE id = 42;
Top statements by cumulative execution time
Optional extension: pg_stat_statements must already be configured and installed. Schema-qualify its view if it is not on your search_path.
SELECT queryid, calls,
round(total_exec_time::numeric, 1) AS total_ms,
round(mean_exec_time::numeric, 1) AS mean_ms,
rows, shared_blks_hit, shared_blks_read,
left(query, 1000) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 25;
Create a B-tree index concurrently
DDL: run outside a transaction block. Concurrent builds still consume resources; this example is for a regular table, not a partitioned parent.
CREATE INDEX CONCURRENTLY your_table_customer_created_idx
ON public.your_table (customer_id, created_at DESC);
Partial index for a frequently queried subset
DDL: the query predicate must support using the partial index. Replace the example columns and condition.
CREATE INDEX CONCURRENTLY your_table_open_created_idx
ON public.your_table (created_at)
WHERE status = 'open';
Refresh planner statistics or run ordinary vacuum
Maintenance commands. VACUUM cannot run inside a transaction block. ANALYZE updates estimates; ordinary VACUUM makes space reusable but generally does not shrink the file.
ANALYZE public.your_table;
-- Run separately, outside BEGIN / COMMIT:
VACUUM (ANALYZE, VERBOSE) public.your_table;
Back to top
Data checks, duplicates & reconciliation
Find duplicate business keys
Add every column that makes up the intended key. GROUP BY groups null key values together.
SELECT source_system, external_id, count(*) AS copies
FROM public.your_table
GROUP BY source_system, external_id
HAVING count(*) > 1
ORDER BY copies DESC, source_system, external_id;
Preview duplicate rows while keeping the newest
Read-only preview. The final id tie-breaker must be unique to make the keep/delete decision deterministic.
WITH ranked AS (
SELECT t.*,
row_number() OVER (
PARTITION BY source_system, external_id
ORDER BY updated_at DESC NULLS LAST, id DESC
) AS duplicate_rank
FROM public.your_table AS t
)
SELECT *
FROM ranked
WHERE duplicate_rank > 1
ORDER BY source_system, external_id, duplicate_rank;
Count missing, blank and distinct values
COUNT(DISTINCT ...) excludes null. Trimming identifies whitespace-only text.
SELECT count(*) AS total_rows,
count(*) FILTER (WHERE customer_id IS NULL) AS missing_customer_id,
count(*) FILTER (WHERE email IS NULL) AS null_email,
count(*) FILTER (WHERE email IS NOT NULL AND btrim(email) = '') AS blank_email,
count(DISTINCT customer_id) AS distinct_customer_ids
FROM public.your_table;
Find orphaned references
Use NOT EXISTS rather than NOT IN when the subquery may contain nulls.
SELECT child.*
FROM public.child AS child
WHERE child.parent_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM public.parent AS parent
WHERE parent.id = child.parent_id
);
Rows present in source but missing from target
EXCEPT removes duplicate result rows. Select the same comparable columns on both sides.
SELECT id, status, amount FROM staging.your_table
EXCEPT
SELECT id, status, amount FROM public.your_table;
Compare source and target by key, including null-safe differences
Assumes id is unique and not null on both sides. Duplicate keys would multiply the joined rows.
SELECT coalesce(s.id, t.id) AS id,
CASE WHEN s.id IS NULL THEN 'target only'
WHEN t.id IS NULL THEN 'source only'
ELSE 'changed' END AS difference,
s.status AS source_status, t.status AS target_status,
s.amount AS source_amount, t.amount AS target_amount
FROM staging.your_table AS s
FULL JOIN public.your_table AS t USING (id)
WHERE s.id IS NULL OR t.id IS NULL
OR ROW(s.status, s.amount) IS DISTINCT FROM ROW(t.status, t.amount);
Back to top
Everyday SELECT patterns
Latest record per customer with DISTINCT ON
The DISTINCT ON expressions must lead ORDER BY. id is a deterministic tie-breaker.
SELECT DISTINCT ON (customer_id)
customer_id, id, status, updated_at
FROM public.your_table
ORDER BY customer_id, updated_at DESC NULLS LAST, id DESC;
Several metrics in one grouped query
Null amounts are ignored by SUM; coalesce the result if you need zero instead of null.
SELECT customer_id,
count(*) AS total_orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
coalesce(sum(amount) FILTER (WHERE status = 'paid'), 0) AS paid_amount
FROM public.orders
GROUP BY customer_id;
Running total and previous value
An explicit ROWS frame avoids peer-group surprises when dates repeat.
SELECT customer_id, id, created_at, amount,
sum(amount) OVER (
PARTITION BY customer_id ORDER BY created_at, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_amount,
lag(amount) OVER (
PARTITION BY customer_id ORDER BY created_at, id
) AS previous_amount
FROM public.orders
ORDER BY customer_id, created_at, id;
Keyset pagination instead of a growing OFFSET
Assumes created_at and id are non-null and id makes the ordering unique. Use the last row of the previous page as the cursor.
SELECT id, created_at, status
FROM public.your_table
WHERE (created_at, id) > (TIMESTAMPTZ '2026-01-01 00:00:00+00', 12345)
ORDER BY created_at, id
LIMIT 100;
Filter a time range with a half-open interval
Includes the lower bound and excludes the upper bound, so adjacent ranges do not overlap.
SELECT *
FROM public.events
WHERE created_at >= TIMESTAMPTZ '2026-01-01 00:00:00+00'
AND created_at < TIMESTAMPTZ '2026-02-01 00:00:00+00';
Group timestamptz events by Amsterdam calendar day
Use a named timezone to account for DST. Assumes created_at is timestamptz.
SELECT (created_at AT TIME ZONE 'Europe/Amsterdam')::date AS local_day,
count(*) AS events
FROM public.events
GROUP BY 1
ORDER BY 1;
Fill missing dates with zeros
Generate dates independently of the data, then left join the daily counts.
WITH days AS (
SELECT DATE '2026-01-01' + n AS day
FROM generate_series(0, 30) AS g(n)
), counts AS (
SELECT (created_at AT TIME ZONE 'Europe/Amsterdam')::date AS day,
count(*) AS events
FROM public.events
WHERE created_at >= TIMESTAMPTZ '2026-01-01 00:00:00 Europe/Amsterdam'
AND created_at < TIMESTAMPTZ '2026-02-01 00:00:00 Europe/Amsterdam'
GROUP BY 1
)
SELECT d.day, coalesce(c.events, 0) AS events
FROM days AS d
LEFT JOIN counts AS c USING (day)
ORDER BY d.day;
Small inline lookup table with VALUES
Useful for a mapping, a small test case or joining a fixed list.
WITH status_labels(code, label) AS (
VALUES ('N', 'New'), ('P', 'Processing'), ('D', 'Done')
)
SELECT t.id, t.status, s.label
FROM public.your_table AS t
LEFT JOIN status_labels AS s ON s.code = t.status;
Filter using an array
The explicit cast makes the array type unambiguous, including for an empty array.
SELECT *
FROM public.your_table
WHERE id = ANY (ARRAY[10, 20, 30]::bigint[]);
Back to top
JSONB, arrays & text
Read JSONB fields as JSON or text
-> keeps a JSON value; ->> extracts text. A missing key returns null.
SELECT payload -> 'customer' AS customer_json,
payload ->> 'status' AS status_text,
payload #>> '{customer,email}' AS email,
(payload ->> 'amount')::numeric AS amount
FROM public.events
WHERE payload @> '{"status":"paid"}'::jsonb;
Expand a JSONB array into rows
Assumes items is a JSON array when present. A JSON null or another JSON type needs handling before expansion.
SELECT e.id, item.value ->> 'sku' AS sku,
(item.value ->> 'quantity')::integer AS quantity
FROM public.events AS e
CROSS JOIN LATERAL jsonb_array_elements(
coalesce(e.payload -> 'items', '[]'::jsonb)
) AS item(value);
Build an ordered JSONB array from rows
COALESCE produces [] when no rows match.
SELECT coalesce(
jsonb_agg(jsonb_build_object('id', id, 'status', status) ORDER BY id),
'[]'::jsonb
) AS result
FROM public.your_table;
Build a sorted, deduplicated list
Null values are omitted. Use a delimiter that makes sense for your output.
SELECT customer_id,
string_agg(DISTINCT tag, ', ' ORDER BY tag) AS tags
FROM public.customer_tags
GROUP BY customer_id;
Generate SQL with quoted identifiers and literals
This generates text only; it does not execute the generated statements.
SELECT format('SELECT count(*) FROM %I.%I;', schemaname, tablename)
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY tablename;
SELECT format('SELECT %L AS example;', 'O''Brien');
Back to top
INSERT, UPDATE & transaction templates
Insert or update on a unique key
Writes data. customer_id must have a matching unique constraint or unique index.
INSERT INTO public.customers (customer_id, name, updated_at)
VALUES (42, 'Example customer', now())
ON CONFLICT (customer_id) DO UPDATE
SET name = EXCLUDED.name,
updated_at = EXCLUDED.updated_at
RETURNING *;
Upsert only when values actually differ
Writes data. Avoids an update when the existing name already matches, including null-safe comparison.
INSERT INTO public.customers AS target (customer_id, name)
VALUES (42, 'Example customer')
ON CONFLICT (customer_id) DO UPDATE
SET name = EXCLUDED.name
WHERE target.name IS DISTINCT FROM EXCLUDED.name
RETURNING *;
Insert and skip duplicates
Writes data. The conflict target must be backed by a suitable unique constraint or index.
INSERT INTO public.customers (customer_id, name)
VALUES (42, 'Example customer')
ON CONFLICT (customer_id) DO NOTHING
RETURNING *;
Update a specific row and inspect RETURNING before committing
Writes temporarily and takes a row lock. Ends with ROLLBACK; change it to COMMIT only when you intend to retain the update. Other sessions may wait until this transaction ends.
BEGIN;
SET LOCAL lock_timeout = '3s';
SET LOCAL statement_timeout = '30s';
SELECT id, status FROM public.your_table WHERE id = 42 FOR UPDATE;
UPDATE public.your_table
SET status = 'processed'
WHERE id = 42
RETURNING id, status;
ROLLBACK;
Update from another table with a one-to-one key
Writes data. Ensure staging has at most one row per target id; multiple matches otherwise produce an unpredictable source choice.
UPDATE public.your_table AS target
SET status = source.status,
amount = source.amount
FROM staging.your_table AS source
WHERE target.id = source.id
AND ROW(target.status, target.amount)
IS DISTINCT FROM ROW(source.status, source.amount)
RETURNING target.id, target.status, target.amount;
Temporary scratch table for one transaction
Creates a temporary table which is automatically dropped at commit. CTAS does not copy the source table’s indexes, defaults or constraints.
BEGIN;
CREATE TEMP TABLE scratch ON COMMIT DROP AS
SELECT * FROM public.your_table WHERE status = 'open';
SELECT count(*) FROM scratch;
COMMIT;
Back to top
Roles, permissions & row-level security
Direct role memberships
Shows direct grants, not every inherited membership path.
SELECT parent.rolname AS granted_role,
member.rolname AS member_role,
m.admin_option
FROM pg_auth_members AS m
JOIN pg_roles AS parent ON parent.oid = m.roleid
JOIN pg_roles AS member ON member.oid = m.member
ORDER BY 1, 2;
Check the current role’s effective privileges
These check privileges; row-level security can still limit which rows are visible.
SELECT has_schema_privilege(current_user, 'public', 'USAGE') AS schema_usage,
has_table_privilege(current_user, 'public.your_table', 'SELECT') AS can_select,
has_table_privilege(current_user, 'public.your_table', 'INSERT') AS can_insert,
has_table_privilege(current_user, 'public.your_table', 'UPDATE') AS can_update,
has_table_privilege(current_user, 'public.your_table', 'DELETE') AS can_delete;
Row-level security flags and policies
Inspect both table flags and the policies that apply to the table.
SELECT relrowsecurity AS rls_enabled, relforcerowsecurity AS force_rls
FROM pg_class
WHERE oid = 'public.your_table'::regclass;
SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check
FROM pg_policies
WHERE schemaname = 'public' AND tablename = 'your_table'
ORDER BY policyname;
Grant a role read access to existing and future tables
Changes privileges. Replace app_reader and table_owner. Default privileges apply to objects created by table_owner, not every creator in the schema.
GRANT USAGE ON SCHEMA public TO app_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO app_reader;
ALTER DEFAULT PRIVILEGES FOR ROLE table_owner IN SCHEMA public
GRANT SELECT ON TABLES TO app_reader;
Back to top
psql copy, export & quick commands
psql navigation and output
These are psql client commands, not SQL. Type them in psql; do not paste them into a JDBC SQL editor.
\conninfo
\l+
\dn+
\dt public.*
\d+ public.your_table
\di+ public.*
\du
\dx
\timing on
\x auto
Export a query to a local CSV file
psql command: the output path is on the client machine. Keep the \copy command on one physical line.
\copy (SELECT id, status, created_at FROM public.your_table ORDER BY id) TO '/tmp/export.csv' WITH (FORMAT csv, HEADER true)
Import a local CSV into explicit columns
psql command; writes data. The CSV column order must match this explicit column list.
\copy public.your_table (id, status, created_at) FROM '/tmp/import.csv' WITH (FORMAT csv, HEADER true)
Stop a psql script on its first error
psql command. This stops processing but does not itself wrap the script in a transaction.
\set ON_ERROR_STOP on
\i /path/to/script.sql
Back to top