764 commands · 48 cheat sheets · 6 subcategories

SQL master quick reference — Page 2

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

Modeling and Data Types · 17 commands

PostgreSQL Custom Types, Domains, Enums, and Composites Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a constrained domainCREATE DOMAIN app.email_address AS text CONSTRAINT email_nonempty CHECK (btrim(VALUE) <> '');View examples
Use a domain in a tableemail app.email_address NOT NULLView examples
Stage a domain checkALTER DOMAIN app.email_address ADD CONSTRAINT email_length CHECK (octet_length(VALUE) <= 320) NOT VALID;View examples
Validate a domain checkALTER DOMAIN app.email_address VALIDATE CONSTRAINT email_length;View examples
Create an enum typeCREATE TYPE app.order_state AS ENUM ('pending', 'paid', 'shipped', 'cancelled');View examples
Append an enum labelALTER TYPE app.order_state ADD VALUE IF NOT EXISTS 'returned';View examples
Position an enum labelALTER TYPE app.order_state ADD VALUE 'processing' AFTER 'pending';View examples
Rename an enum labelALTER TYPE app.order_state RENAME VALUE 'shipped' TO 'dispatched';View examples
Order by enum semanticsSELECT id, state FROM app.orders ORDER BY state, id;View examples
Create a composite typeCREATE TYPE app.money_amount AS (amount numeric(18,2), currency_code text);View examples
Construct a typed compositeROW(49.90, 'USD')::app.money_amountView examples
Read a composite fieldSELECT (price).amount, (price).currency_code FROM app.products;View examples
Add a composite attributeALTER TYPE app.money_amount ADD ATTRIBUTE tax_included boolean CASCADE;View examples
Grant type usageGRANT USAGE ON TYPE app.order_state, app.email_address, app.money_amount TO app_writer;View examples
Cast text explicitlySELECT $1::text::app.order_state;View examples
Inventory custom typesSELECT n.nspname, t.typname, t.typtype FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace WHERE n.nspname = 'app';View examples
Inspect enum labelsSELECT enumlabel, enumsortorder FROM pg_enum WHERE enumtypid = 'app.order_state'::regtype ORDER BY enumsortorder;View examples

Modeling and Data Types · 12 commands

PostgreSQL Dates, Times, and Intervals Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Typed dateDATE '2026-08-12'View examples
Local timestampTIMESTAMP '2026-08-12 09:30:00'View examples
Instant with offsetTIMESTAMPTZ '2026-08-12 09:30:00-03:00'View examples
Transaction timeCURRENT_TIMESTAMPView examples
Wall-clock timeclock_timestamp()View examples
Typed durationINTERVAL '2 days 3 hours'View examples
Add a durationstarted_at + INTERVAL '30 minutes'View examples
Render in a zoneoccurred_at AT TIME ZONE 'America/Sao_Paulo'View examples
Truncate to a unitdate_trunc('month', occurred_at, 'UTC')View examples
Extract a fieldEXTRACT(ISODOW FROM occurred_at)View examples
Half-open time windowWHERE occurred_at >= $1 AND occurred_at < $2View examples
Format for displayto_char(occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI')View examples

Modeling and Data Types · 14 commands

PostgreSQL Identity, Generated Columns, and Sequences Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Protect an identity columnid bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEYView examples
Allow identity overridesid bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEYView examples
Configure the identity sequenceGENERATED ALWAYS AS IDENTITY (START WITH 1000 INCREMENT BY 1 CACHE 20 )View examples
Import explicit identity valuesINSERT INTO app.accounts OVERRIDING SYSTEM VALUE (id, name) VALUES (42, 'Ada');View examples
Regenerate imported identitiesINSERT INTO app.accounts OVERRIDING USER VALUE SELECT * FROM staging.accounts;View examples
Store a generated valuetotal numeric GENERATED ALWAYS AS (quantity * unit_price) STOREDView examples
Compute a virtual valuefull_name text GENERATED ALWAYS AS (first_name || ' ' || last_name) VIRTUALView examples
Allocate a sequence valueSELECT nextval('app.ticket_number_seq'::regclass);View examples
Read this session's valueSELECT currval('app.ticket_number_seq'::regclass);View examples
Create an owned sequenceCREATE SEQUENCE app.ticket_number_seq AS bigint CACHE 20 OWNED BY app.tickets.number;View examples
Grant allocation accessGRANT USAGE ON SEQUENCE app.ticket_number_seq TO app_writer;View examples
Find an attached sequenceSELECT pg_get_serial_sequence('app.accounts', 'id');View examples
Plan a sequence repairSELECT setval(pg_get_serial_sequence('app.accounts','id'), max(id), true) FROM app.accounts;View examples
Inspect generated attributesSELECT column_name, is_identity, identity_generation, is_generated FROM information_schema.columns WHERE table_schema = 'app';View examples

Modeling and Data Types · 12 commands

PostgreSQL JSON and JSONB Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create JSONB'{"status":"open"}'::jsonbView examples
Read JSON fieldpayload -> 'customer'View examples
Read text fieldpayload ->> 'status'View examples
Read a nested pathpayload #>> '{customer,email}'View examples
Test containmentpayload @> '{"status":"open"}'::jsonbView examples
Test a keypayload ? 'status'View examples
Match a JSON pathpayload @? '$.items[*] ? (@.price > 100)'View examples
Build an objectjsonb_build_object('id', id, 'name', name)View examples
Aggregate JSON objectsjsonb_agg(jsonb_build_object('id', id) ORDER BY id)View examples
Set a nested valuejsonb_set(payload, '{status}', '"closed"'::jsonb)View examples
Expand an arrayCROSS JOIN LATERAL jsonb_array_elements(payload -> 'items') AS itemView examples
Index JSONB operationsCREATE INDEX events_payload_gin_idx ON events USING GIN (payload);View examples

Modeling and Data Types · 16 commands

PostgreSQL Table Constraints Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a tableCREATE TABLE accounts (id bigint PRIMARY KEY, email text NOT NULL);View examples
Generate identifiersid bigint GENERATED ALWAYS AS IDENTITYView examples
Require a valuename text NOT NULLView examples
Supply a defaultcreated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMPView examples
Validate a conditionCONSTRAINT products_price_nonnegative CHECK (price >= 0)View examples
Declare a primary keyCONSTRAINT accounts_pkey PRIMARY KEY (id)View examples
Use a composite keyPRIMARY KEY (order_id, product_id)View examples
Require uniquenessCONSTRAINT accounts_email_key UNIQUE (email)View examples
Reference another tableFOREIGN KEY (customer_id) REFERENCES customers (id)View examples
Delete dependent rowsFOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADEView examples
Detach on deletionFOREIGN KEY (manager_id) REFERENCES employees (id) ON DELETE SET NULLView examples
Name a ruleCONSTRAINT quantity_positive CHECK (quantity > 0)View examples
Add a constraintALTER TABLE products ADD CONSTRAINT products_sku_key UNIQUE (sku);View examples
Defer existing-row validationALTER TABLE orders ADD CONSTRAINT orders_total_check CHECK (total >= 0) NOT VALID;View examples
Validate existing rowsALTER TABLE orders VALIDATE CONSTRAINT orders_total_check;View examples
Remove a constraintALTER TABLE products DROP CONSTRAINT products_sku_key;View examples

Modeling and Data Types · 18 commands

PostgreSQL Temporary and Unlogged Tables Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a session temporary tableCREATE TEMP TABLE work_items (item_id bigint PRIMARY KEY, payload jsonb NOT NULL);View examples
Preserve rows across commitsCREATE TEMP TABLE work_items (item_id bigint) ON COMMIT PRESERVE ROWS;View examples
Clear rows after each commitCREATE TEMP TABLE work_items (item_id bigint) ON COMMIT DELETE ROWS;View examples
Drop the table at commitCREATE TEMP TABLE work_items (item_id bigint) ON COMMIT DROP;View examples
Materialize a transaction-scoped resultCREATE TEMP TABLE recent_orders ON COMMIT DROP AS SELECT order_id, total FROM app.orders WHERE created_at >= CURRENT_DATE;View examples
Copy a table shapeCREATE TEMP TABLE staged_orders (LIKE app.orders INCLUDING DEFAULTS INCLUDING CONSTRAINTS);View examples
Index a populated temporary tableCREATE INDEX work_items_customer_idx ON work_items (customer_id);View examples
Collect temporary-table statisticsANALYZE work_items;View examples
Bypass temporary name shadowingSELECT order_id FROM app.orders;View examples
Restrict temporary-table creationREVOKE TEMPORARY ON DATABASE appdb FROM PUBLIC;View examples
Delegate temporary-table creationGRANT TEMPORARY ON DATABASE appdb TO batch_worker;View examples
Budget session-local temp buffersSET temp_buffers = '64MB';View examples
Create a shared unlogged tableCREATE UNLOGGED TABLE app.ingest_buffer (event_id bigint PRIMARY KEY, payload jsonb NOT NULL);View examples
Materialize an unlogged resultCREATE UNLOGGED TABLE app.daily_rollup AS SELECT account_id, sum(amount) AS total FROM app.ledger GROUP BY account_id;View examples
Promote data to crash-safe storageALTER TABLE app.ingest_buffer SET LOGGED;View examples
Convert rebuildable data to unloggedALTER TABLE app.daily_rollup SET UNLOGGED;View examples
Audit relation persistenceSELECT n.nspname, c.relname, c.relpersistence FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r';View examples
Preserve unlogged data in a logical dumppg_dump --format=custom --file=appdb.dump appdbView examples

Data Change and Programmability · 15 commands

PostgreSQL COPY Import and Export Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Import a client file\copy app.stage_order (external_id, ordered_at, amount) FROM './orders.csv' WITH (FORMAT csv, HEADER match)View examples
Import a server fileCOPY app.stage_order (external_id, ordered_at, amount) FROM '/srv/import/orders.csv' WITH (FORMAT csv, HEADER match);View examples
Stream from a clientCOPY app.stage_order (external_id, ordered_at, amount) FROM STDIN WITH (FORMAT csv, HEADER match);View examples
Verify CSV headingsCOPY app.stage_order (external_id, ordered_at, amount) FROM STDIN WITH (FORMAT csv, HEADER match);View examples
Choose a NULL markerCOPY app.stage_order FROM STDIN WITH (FORMAT csv, HEADER match, NULL 'NULL');View examples
Keep empty textCOPY app.contact FROM STDIN WITH (FORMAT csv, HEADER match, FORCE_NOT_NULL (display_name));View examples
Declare source encodingCOPY app.stage_order FROM STDIN WITH (FORMAT csv, HEADER match, ENCODING 'UTF8');View examples
Create transaction stagingCREATE TEMP TABLE stage_order (LIKE app.orders INCLUDING DEFAULTS) ON COMMIT DROP;View examples
Promote valid rowsINSERT INTO app.orders (external_id, ordered_at, amount) SELECT external_id, ordered_at, amount FROM stage_order;View examples
Bound conversion rejectsCOPY app.stage_order FROM STDIN WITH (FORMAT csv, HEADER match, ON_ERROR ignore, REJECT_LIMIT 20);View examples
Report rejected fieldsCOPY app.stage_order FROM STDIN WITH (FORMAT csv, ON_ERROR ignore, REJECT_LIMIT 20, LOG_VERBOSITY verbose);View examples
Export to a client file\copy app.orders (external_id, ordered_at, amount) TO './orders.csv' WITH (FORMAT csv, HEADER true)View examples
Export a stable projection\copy ( SELECT external_id, ordered_at, amount FROM app.orders ORDER BY external_id ) TO './orders.csv' WITH (FORMAT csv, HEADER true)View examples
Monitor COPY progressSELECT pid, command, type, bytes_processed, tuples_processed FROM pg_stat_progress_copy;View examples
Reclaim failed-load spaceVACUUM (ANALYZE) app.stage_order;View examples

Data Change and Programmability · 14 commands

PostgreSQL Functions, Procedures, and Triggers Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a SQL functionCREATE FUNCTION app.net_total(numeric, numeric) RETURNS numeric LANGUAGE sql IMMUTABLE RETURN $1 - $2;View examples
Call with named notationSELECT app.calculate_total(subtotal => 100, discount => 5);View examples
Return rowsRETURNS TABLE (order_id bigint, total numeric)View examples
Create PL/pgSQL functionCREATE FUNCTION app.require_positive(value integer) RETURNS integer LANGUAGE plpgsql AS $$ ... $$;View examples
Raise an errorRAISE EXCEPTION 'quantity must be positive' USING ERRCODE = '22023';View examples
Handle an expected errorEXCEPTION WHEN unique_violation THEN ...View examples
Create a procedureCREATE PROCEDURE app.refresh_reports() LANGUAGE plpgsql AS $$ ... $$;View examples
Call a procedureCALL app.refresh_reports();View examples
Declare stable behaviorLANGUAGE sql STABLEView examples
Return null on null inputRETURNS NULL ON NULL INPUTView examples
Run as function ownerSECURITY DEFINER SET search_path = pg_catalog, appView examples
Create trigger functionCREATE FUNCTION app.set_updated_at() RETURNS trigger LANGUAGE plpgsql AS $$ ... $$;View examples
Attach row triggerCREATE TRIGGER set_updated_at BEFORE UPDATE ON app.items FOR EACH ROW EXECUTE FUNCTION app.set_updated_at();View examples
Drop an exact signatureDROP FUNCTION app.net_total(numeric, numeric) RESTRICT;View examples

Data Change and Programmability · 12 commands

PostgreSQL Pattern Matching and Full-Text Search Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Simple patternWHERE title LIKE 'PostgreSQL%'View examples
Case-insensitive patternWHERE title ILIKE '%database%'View examples
Literal wildcardWHERE code LIKE 'A\_%' ESCAPE '\'View examples
POSIX regex matchWHERE value ~ '^[A-Z]{2}-[0-9]+$'View examples
Case-insensitive regexWHERE value ~* '^error:'View examples
Parse a documentto_tsvector('english', coalesce(title, '') || ' ' || coalesce(body, ''))View examples
Plain user queryplainto_tsquery('english', $1)View examples
Web-style querywebsearch_to_tsquery('english', $1)View examples
Match document and querysearch_vector @@ websearch_to_tsquery('english', $1)View examples
Rank a matchts_rank_cd(search_vector, query) AS rankView examples
Highlight fragmentsts_headline('english', body, query)View examples
Index a search vectorCREATE INDEX articles_search_idx ON articles USING GIN (search_vector);View examples

Data Change and Programmability · 12 commands

PostgreSQL Views and Materialized Views Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a viewCREATE VIEW active_users AS SELECT id, name FROM users WHERE active;View examples
Replace a compatible viewCREATE OR REPLACE VIEW active_users AS SELECT id, name FROM users WHERE active;View examples
Enforce view predicateCREATE VIEW open_items AS SELECT * FROM items WHERE status = 'open' WITH LOCAL CHECK OPTION;View examples
Create a security barrierCREATE VIEW safe_users WITH (security_barrier = true) AS SELECT id, name FROM users;View examples
Grant view accessGRANT SELECT ON active_users TO reporting_role;View examples
Create stored resultsCREATE MATERIALIZED VIEW sales_summary AS SELECT day, sum(total) FROM sales GROUP BY day;View examples
Create unpopulatedCREATE MATERIALIZED VIEW sales_summary AS SELECT ... WITH NO DATA;View examples
Refresh completelyREFRESH MATERIALIZED VIEW sales_summary;View examples
Refresh while readableREFRESH MATERIALIZED VIEW CONCURRENTLY sales_summary;View examples
Index stored resultsCREATE UNIQUE INDEX sales_summary_day_uidx ON sales_summary (day);View examples
Inspect a view definitionSELECT pg_get_viewdef('active_users'::regclass, true);View examples
Drop without cascadingDROP VIEW active_users RESTRICT;View examples

Data Change and Programmability · 17 commands

SQL Data Modification Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Insert one rowINSERT INTO customers (name, email) VALUES ('Ada', 'ada@example.com');View examples
Insert several rowsINSERT INTO tags (name) VALUES ('sql'), ('database'), ('backend');View examples
Insert query resultsINSERT INTO customer_archive (id, name) SELECT id, name FROM customers WHERE inactive = true;View examples
Use a column defaultINSERT INTO jobs (name, status) VALUES ('reindex', DEFAULT);View examples
Update matching rowsUPDATE customers SET active = false WHERE last_seen_at < DATE '2025-01-01';View examples
Update from the old valueUPDATE products SET price = price * 1.05 WHERE category = 'books';View examples
Update from another tableUPDATE products AS p SET price = i.price FROM imports AS i WHERE i.sku = p.sku;View examples
Delete matching rowsDELETE FROM sessions WHERE expires_at < CURRENT_TIMESTAMP;View examples
Delete using another tableDELETE FROM cart_items AS ci USING products AS p WHERE p.id = ci.product_id AND p.discontinued = true;View examples
Ignore a duplicate insertINSERT INTO tags (name) VALUES ('sql') ON CONFLICT (name) DO NOTHING;View examples
Upsert a rowINSERT INTO counters (key, value) VALUES ('views', 1) ON CONFLICT (key) DO UPDATE SET value = counters.value + EXCLUDED.value;View examples
Return changed valuesINSERT INTO customers (name) VALUES ('Ada') RETURNING id, name;View examples
Begin a transactionBEGIN;View examples
Commit a transactionCOMMIT;View examples
Roll back a transactionROLLBACK;View examples
Create a savepointSAVEPOINT before_optional_step;View examples
Roll back to a savepointROLLBACK TO SAVEPOINT before_optional_step;View examples

Performance and Planning · 15 commands

PostgreSQL Indexes and Query Plans Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a B-tree indexCREATE INDEX orders_customer_idx ON orders (customer_id);View examples
Enforce uniquenessCREATE UNIQUE INDEX users_email_uidx ON users (email);View examples
Index several columnsCREATE INDEX orders_customer_created_idx ON orders (customer_id, created_at DESC);View examples
Include payload columnsCREATE INDEX orders_status_idx ON orders (status) INCLUDE (total);View examples
Index a subsetCREATE INDEX orders_open_idx ON orders (created_at) WHERE status = 'open';View examples
Index an expressionCREATE INDEX users_lower_email_idx ON users (lower(email));View examples
Index composite values with GINCREATE INDEX documents_tags_idx ON documents USING GIN (tags);View examples
Summarize ordered storage with BRINCREATE INDEX events_time_brin_idx ON events USING BRIN (occurred_at);View examples
Build without blocking writesCREATE INDEX CONCURRENTLY orders_customer_idx ON orders (customer_id);View examples
Drop with less write blockingDROP INDEX CONCURRENTLY orders_customer_idx;View examples
Inspect estimated planEXPLAIN SELECT * FROM orders WHERE customer_id = 42;View examples
Measure executionEXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 42;View examples
Return a machine-readable planEXPLAIN (FORMAT JSON) SELECT * FROM orders WHERE customer_id = 42;View examples
Refresh planner statisticsANALYZE orders;View examples
List table indexesSELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'orders';View examples
CMDMEMO TERMINALREAD ONLY