PostgreSQL Cheat Sheet

Core PostgreSQL commands, SQL patterns, and object management for daily engineering work.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Connect and Inspect with psql

Launch psql and explore databases, schemas, and tables.

Connect to a database

Open an interactive psql session to a database.

bashANYpsqlconnect
bash
psql -d appdb
Notes

Use environment variables like PGHOST, PGPORT, PGUSER, and PGPASSWORD to avoid repeating connection flags.

Connect with URI

Connect using a full PostgreSQL connection string.

bashANYpsqlconnecturi
bash
psql postgresql://appuser:secret@localhost:5432/appdb
Notes

Useful for scripts and for matching application connection strings.

List databases

Show all databases in the cluster.

sqlANYpsqlmeta-commanddatabase
sql
\l
Notes

A common first command after connecting to a server.

List roles

Show roles and memberships.

sqlANYpsqlrolessecurity
sql
\du
Notes

Useful when checking login capability, superuser privileges, or group roles.

List schemas

Show schemas in the current database.

sqlANYpsqlschemainspect
sql
\dn
Notes

See summary for usage details.

List tables views and sequences

List relations across schemas.

sqlANYpsqltablesinspect
sql
\dt *.*
Notes

Use patterns like `\dt public.*` to limit output.

Describe a table

Show columns, indexes, defaults, storage details, and more for a relation.

sqlANYpsqltabledescribe
sql
\d+ public.users
Notes

See summary for usage details.

Toggle expanded output

Use expanded output automatically when rows are wide.

sqlANYpsqlformattingoutput
sql
\x auto
Notes

See summary for usage details.

Toggle query timing

Show execution time after each statement.

sqlANYpsqltimingdebug
sql
\timing on
Notes

See summary for usage details.

Run SQL file

Execute commands from a SQL script file.

bashANYpsqlscriptsautomation
bash
psql -d appdb -f schema.sql
Notes

See summary for usage details.

Database and Role Lifecycle

Create, alter, and drop databases and roles.

Create database

Create a new database in the cluster.

sqlANYdatabaseddl
sql
CREATE DATABASE appdb;
Notes

Databases are cluster-level objects and must be created from another existing database such as `postgres`.

Create database with owner

Create a database with explicit owner and template.

sqlANYdatabaseddlowner
sql
CREATE DATABASE appdb OWNER appuser TEMPLATE template0 ENCODING 'UTF8';
Notes

See summary for usage details.

Rename database

Rename an existing database.

sqlANYdatabasealter
sql
ALTER DATABASE appdb RENAME TO appdb_prod;
Notes

Cannot rename the currently connected database.

Drop database

Delete a database permanently.

sqlANYdatabasedropdanger
sql
DROP DATABASE appdb;
Notes

See summary for usage details.

Create login role

Create a role that can log in.

sqlANYrolesecurityddl
sql
CREATE ROLE appuser WITH LOGIN PASSWORD 'secret';
Notes

Roles replace the older distinction between users and groups.

Create role with privileges

Create a role with explicit capability flags.

sqlANYrolesecurity
sql
CREATE ROLE readonly WITH LOGIN PASSWORD 'secret' NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT;
Notes

See summary for usage details.

Change role password

Update a role password.

sqlANYrolepasswordsecurity
sql
ALTER ROLE appuser WITH PASSWORD 'new-secret';
Notes

See summary for usage details.

Grant role membership

Add a role as a member of another role.

sqlANYrolegrantmembership
sql
GRANT readonly TO analyst_user;
Notes

See summary for usage details.

Revoke role membership

Remove inherited privileges from a member role.

sqlANYrolerevokemembership
sql
REVOKE readonly FROM analyst_user;
Notes

See summary for usage details.

Drop role

Remove a role from the cluster.

sqlANYroledropsecurity
sql
DROP ROLE readonly;
Notes

Roles owning objects or memberships may need cleanup first.

Schemas, Tables, and Core DDL

Design schemas and evolve tables safely.

Create schema

Create a namespace for objects.

sqlANYschemaddl
sql
CREATE SCHEMA accounting AUTHORIZATION appuser;
Notes

See summary for usage details.

Set search path

Change schema lookup order for the current session.

sqlANYschemasearch_pathsession
sql
SET search_path TO accounting, public;
Notes

See summary for usage details.

Create table

Create a basic table with primary key and defaults.

sqlANYtableddlcreate
sql
CREATE TABLE public.users (
  user_id bigserial PRIMARY KEY,
  email text NOT NULL UNIQUE,
  created_at timestamptz NOT NULL DEFAULT now()
);
Notes

See summary for usage details.

Create identity column

Use a SQL-standard identity column instead of serial.

sqlANYtableidentityddl
sql
CREATE TABLE events (
  event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  payload jsonb NOT NULL
);
Notes

See summary for usage details.

Add column

Add a nullable column to an existing table.

sqlANYtablealter
sql
ALTER TABLE public.users ADD COLUMN last_login_at timestamptz;
Notes

See summary for usage details.

Set column default

Change a column default value.

sqlANYtablealterdefault
sql
ALTER TABLE public.users ALTER COLUMN created_at SET DEFAULT now();
Notes

See summary for usage details.

Set NOT NULL

Enforce non-nullability on a column.

sqlANYtablealterconstraint
sql
ALTER TABLE public.users ALTER COLUMN email SET NOT NULL;
Notes

Existing rows must already satisfy the constraint.

Add check constraint

Add a named CHECK constraint.

sqlANYtableconstraintcheck
sql
ALTER TABLE orders ADD CONSTRAINT orders_total_nonnegative CHECK (total_amount >= 0);
Notes

See summary for usage details.

Rename table

Rename a relation without recreating it.

sqlANYtablerename
sql
ALTER TABLE public.users RENAME TO app_users;
Notes

See summary for usage details.

Drop table

Remove a table if it exists.

sqlANYtabledropdanger
sql
DROP TABLE IF EXISTS public.temp_import;
Notes

See summary for usage details.

Insert, Update, Delete, and Merge

Common DML patterns for application and admin work.

Insert row

Insert one row into a table.

sqlANYinsertdml
sql
INSERT INTO public.users (email) VALUES ('a@example.com');
Notes

See summary for usage details.

Insert multiple rows

Insert many rows in one statement.

sqlANYinsertbulk
sql
INSERT INTO public.users (email)
VALUES ('a@example.com'), ('b@example.com'), ('c@example.com');
Notes

See summary for usage details.

Insert with RETURNING

Insert rows and immediately return generated values.

sqlANYinsertreturning
sql
INSERT INTO public.users (email)
VALUES ('d@example.com')
RETURNING user_id, email, created_at;
Notes

See summary for usage details.

Upsert with ON CONFLICT

Handle unique conflicts by updating instead of failing.

sqlANYinsertupsertconflict
sql
INSERT INTO public.users (email)
VALUES ('a@example.com')
ON CONFLICT (email) DO UPDATE
SET created_at = now();
Notes

See summary for usage details.

Update rows

Modify matching rows.

sqlANYupdatedml
sql
UPDATE public.users SET last_login_at = now() WHERE user_id = 42;
Notes

See summary for usage details.

Update from another table

Update rows using another table in the same statement.

sqlANYupdatejoin
sql
UPDATE orders o
SET customer_tier = c.tier
FROM customers c
WHERE o.customer_id = c.customer_id;
Notes

See summary for usage details.

Delete rows

Delete matching rows.

sqlANYdeletedml
sql
DELETE FROM sessions WHERE expires_at < now();
Notes

See summary for usage details.

Delete with RETURNING

Delete rows and return what was removed.

sqlANYdeletereturning
sql
DELETE FROM jobs WHERE status = 'done' RETURNING job_id;
Notes

See summary for usage details.

Merge source data

Synchronize target data from a source relation with a single statement.

sqlANYmergesyncdml
sql
MERGE INTO inventory AS i
USING inventory_stage AS s
ON i.sku = s.sku
WHEN MATCHED THEN UPDATE SET qty = s.qty
WHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (s.sku, s.qty);
Notes

See summary for usage details.

Truncate table

Quickly remove all rows and optionally reset identities.

sqlANYtruncatedangermaintenance
sql
TRUNCATE TABLE audit_log RESTART IDENTITY;
Notes

See summary for usage details.

Querying, Joins, and Aggregation

Frequently searched SQL patterns in PostgreSQL.

Basic SELECT

Fetch a sorted subset of rows.

sqlANYselectquery
sql
SELECT user_id, email FROM public.users ORDER BY user_id DESC LIMIT 20;
Notes

See summary for usage details.

Use DISTINCT ON

Pick one row per group using PostgreSQL's `DISTINCT ON` extension.

sqlANYselectdistinct-onpostgresql
sql
SELECT DISTINCT ON (customer_id)
  customer_id, order_id, created_at
FROM orders
ORDER BY customer_id, created_at DESC;
Notes

See summary for usage details.

Inner join

Combine matching rows from two tables.

sqlANYjoinselect
sql
SELECT o.order_id, c.name
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id;
Notes

See summary for usage details.

Left join

Keep all rows from the left side even when no match exists.

sqlANYjoinleft-join
sql
SELECT c.customer_id, o.order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
Notes

See summary for usage details.

Group and filter aggregates

Aggregate rows and then filter groups.

sqlANYgroup-byhavingaggregate
sql
SELECT customer_id, count(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING count(*) >= 5;
Notes

See summary for usage details.

Window function row_number

Assign row numbers within each partition.

sqlANYwindow-functionrow_number
sql
SELECT *, row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC)
FROM orders;
Notes

See summary for usage details.

Common table expression

Use a CTE to structure a multi-step query.

sqlANYctewithquery
sql
WITH recent_orders AS (
  SELECT * FROM orders WHERE created_at >= now() - interval '7 days'
)
SELECT customer_id, count(*)
FROM recent_orders
GROUP BY customer_id;
Notes

See summary for usage details.

Recursive CTE

Generate or traverse recursive data with `WITH RECURSIVE`.

sqlANYcterecursive
sql
WITH RECURSIVE nums(n) AS (
  VALUES (1)
  UNION ALL
  SELECT n + 1 FROM nums WHERE n < 10
)
SELECT * FROM nums;
Notes

See summary for usage details.

Expand array values

Turn array elements into rows.

sqlANYarrayunnest
sql
SELECT user_id, unnest(tags) AS tag FROM user_profiles;
Notes

See summary for usage details.

Extract JSONB field

Extract a text value from a JSONB document.

sqlANYjsonbselectoperator
sql
SELECT payload->>'event_type' AS event_type FROM events;
Notes

See summary for usage details.

Indexes and Constraints

Performance-critical DDL patterns and integrity rules.

Create index

Add a basic B-tree index to speed lookups.

sqlANYindexperformance
sql
CREATE INDEX idx_orders_customer_id ON orders (customer_id);
Notes

See summary for usage details.

Create index concurrently

Build an index with reduced write blocking.

sqlANYindexconcurrentlyperformance
sql
CREATE INDEX CONCURRENTLY idx_orders_created_at ON orders (created_at);
Notes

Use outside a transaction block.

Create unique index

Enforce uniqueness with an index.

sqlANYindexunique
sql
CREATE UNIQUE INDEX idx_users_email_unique ON public.users (email);
Notes

See summary for usage details.

Create partial index

Index only a subset of rows.

sqlANYindexpartialperformance
sql
CREATE INDEX idx_orders_open_only ON orders (created_at) WHERE status = 'open';
Notes

See summary for usage details.

Create expression index

Index an expression for case-insensitive lookups.

sqlANYindexexpression
sql
CREATE INDEX idx_users_lower_email ON public.users ((lower(email)));
Notes

See summary for usage details.

Create GIN index on JSONB

Accelerate JSONB containment queries.

sqlANYindexginjsonb
sql
CREATE INDEX idx_events_payload_gin ON events USING GIN (payload jsonb_path_ops);
Notes

See summary for usage details.

Add primary key

Define a primary key after table creation.

sqlANYprimary-keyconstraint
sql
ALTER TABLE invoices ADD CONSTRAINT invoices_pkey PRIMARY KEY (invoice_id);
Notes

See summary for usage details.

Add foreign key

Link rows to a parent table with referential integrity.

sqlANYforeign-keyconstraint
sql
ALTER TABLE orders
ADD CONSTRAINT orders_customer_fk
FOREIGN KEY (customer_id)
REFERENCES customers (customer_id)
ON DELETE RESTRICT;
Notes

See summary for usage details.

Add unique constraint

Ensure unique values through a table constraint.

sqlANYuniqueconstraint
sql
ALTER TABLE public.users ADD CONSTRAINT users_email_key UNIQUE (email);
Notes

See summary for usage details.

Drop index

Remove an index that is no longer needed.

sqlANYindexdrop
sql
DROP INDEX IF EXISTS idx_orders_open_only;
Notes

See summary for usage details.

Views, Functions, Triggers, and Extensions

Reusable logic and database programmability.

Create view

Create a reusable stored query.

sqlANYviewddl
sql
CREATE VIEW active_users AS
SELECT user_id, email
FROM public.users
WHERE deleted_at IS NULL;
Notes

See summary for usage details.

Create materialized view

Persist query results for faster reads.

sqlANYmaterialized-viewddl
sql
CREATE MATERIALIZED VIEW daily_sales AS
SELECT date_trunc('day', created_at) AS day, sum(total_amount) AS revenue
FROM orders
GROUP BY 1;
Notes

See summary for usage details.

Refresh materialized view

Update a materialized view's contents.

sqlANYmaterialized-viewrefresh
sql
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;
Notes

Requires a unique index for concurrent refresh.

Create SQL function

Create a simple SQL-language function.

sqlANYfunctionsql
sql
CREATE FUNCTION public.user_email_domain(email text)
RETURNS text
LANGUAGE sql
AS $$
  SELECT split_part(email, '@', 2);
$$;
Notes

See summary for usage details.

Create PL/pgSQL function

Create a PL/pgSQL trigger helper function.

sqlANYfunctionplpgsqltrigger
sql
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS trigger AS $$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;
Notes

See summary for usage details.

Create trigger

Run a function automatically when rows change.

sqlANYtriggertable
sql
CREATE TRIGGER trg_users_updated_at
BEFORE UPDATE ON public.users
FOR EACH ROW
EXECUTE FUNCTION set_updated_at();
Notes

See summary for usage details.

Enable extension

Install an extension in the current database.

sqlANYextensionddl
sql
CREATE EXTENSION IF NOT EXISTS pgcrypto;
Notes

See summary for usage details.

List installed extensions

Show installed extensions and versions.

sqlANYpsqlextensionmeta-command
sql
\dx
Notes

See summary for usage details.

Add object comment

Document schema objects directly in the catalog.

sqlANYcommentdocumentation
sql
COMMENT ON TABLE public.users IS 'Application users';
Notes

See summary for usage details.

Drop function

Remove a function with its signature.

sqlANYfunctiondrop
sql
DROP FUNCTION IF EXISTS public.user_email_domain(text);
Notes

See summary for usage details.

JSONB, Arrays, and Date/Time Recipes

Popular PostgreSQL-specific data types and expressions.

Build JSON object

Construct JSONB on the fly in a query.

sqlANYjsonbfunction
sql
SELECT jsonb_build_object('user_id', user_id, 'email', email) FROM public.users LIMIT 5;
Notes

See summary for usage details.

Update JSONB path

Set or replace a value inside a JSONB document.

sqlANYjsonbupdate
sql
UPDATE events
SET payload = jsonb_set(payload, '{status}', '"processed"', true)
WHERE event_id = 1;
Notes

See summary for usage details.

JSONB containment query

Find rows whose JSONB contains a given structure.

sqlANYjsonbqueryoperator
sql
SELECT * FROM events WHERE payload @> '{"event_type":"signup"}'::jsonb;
Notes

See summary for usage details.

Append to array

Add an element to an array column.

sqlANYarrayupdate
sql
UPDATE user_profiles SET tags = array_append(tags, 'vip') WHERE user_id = 42;
Notes

See summary for usage details.

Check array membership

Match rows when an array contains a value.

sqlANYarrayquery
sql
SELECT * FROM user_profiles WHERE 'vip' = ANY(tags);
Notes

See summary for usage details.

Bucket timestamps

Group events into time buckets.

sqlANYdatetimeanalytics
sql
SELECT date_trunc('hour', created_at) AS hour, count(*)
FROM events
GROUP BY 1
ORDER BY 1;
Notes

See summary for usage details.

Use interval arithmetic

Compute relative timestamps with intervals.

sqlANYdateinterval
sql
SELECT now() - interval '30 days';
Notes

See summary for usage details.

Convert timezone

Convert timestamps between time zones.

sqlANYtimezonetimestamp
sql
SELECT created_at AT TIME ZONE 'UTC' AT TIME ZONE 'America/Los_Angeles'
FROM events
LIMIT 10;
Notes

See summary for usage details.

Generate date series

Generate date or timestamp ranges without a table.

sqlANYgenerate-seriesdate
sql
SELECT generate_series(date '2026-01-01', date '2026-01-07', interval '1 day');
Notes

See summary for usage details.

Use COALESCE

Provide fallback values for nullable columns.

sqlANYnullcoalesce
sql
SELECT user_id, COALESCE(display_name, email) AS name FROM public.users;
Notes

See summary for usage details.

Recommended next

No recommendations yet.