133 commands · 9 cheat sheets · SQL

Modeling and Data Types master quick reference

Browse 133 commands from 9 focused cheat sheets on page 1 of 1. Each example opens its matching detailed section.

Modeling and Data Types · 14 commands

PostgreSQL Arrays, Ranges, and Multiranges Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Construct a typed arrayARRAY['read', 'write']::text[]View examples
Read the first elementpermissions[1]View examples
Count all elementscardinality(permissions)View examples
Match any element'admin' = ANY (permissions)View examples
Test array containmentpermissions @> ARRAY['read', 'write']::text[]View examples
Test array overlappermissions && ARRAY['admin', 'owner']::text[]View examples
Expand with positionsCROSS JOIN LATERAL unnest(t.tags) WITH ORDINALITY AS tag(value, position)View examples
Create a half-open rangetstzrange(starts_at, ends_at, '[)')View examples
Test range containmentvalid_during @> now()View examples
Test range overlapreserved_during && tstzrange($1, $2, '[)')View examples
Prevent overlapping bookingsEXCLUDE USING gist (room_id WITH =, reserved_during WITH && )View examples
Construct a date multirangedatemultirange(daterange('2026-08-01', '2026-08-08', '[)'), daterange('2026-08-15', '2026-08-22', '[)'))View examples
Index array operatorsCREATE INDEX documents_tags_gin_idx ON app.documents USING gin (tags);View examples
Index range operatorsCREATE INDEX bookings_during_gist_idx ON app.bookings USING gist (reserved_during);View examples

Modeling and Data Types · 14 commands

PostgreSQL Binary Data: bytea and Large Objects Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Create a bytea columnCREATE TABLE app.assets (asset_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, body bytea NOT NULL);View examples
Write a hex literalINSERT INTO app.assets (body) VALUES ('\x89504e47'::bytea);View examples
Decode text into bytesSELECT decode('89504e47', 'hex');View examples
Encode bytes as base64SELECT encode(body, 'base64') FROM app.assets WHERE asset_id = 42;View examples
Measure stored bytesSELECT octet_length(body) FROM app.assets WHERE asset_id = 42;View examples
Hash binary contentSELECT encode(digest(body, 'sha256'), 'hex') FROM app.assets WHERE asset_id = 42;View examples
Inspect datum storageSELECT pg_column_size(body), octet_length(body) FROM app.assets WHERE asset_id = 42;View examples
Set TOAST storage policyALTER TABLE app.assets ALTER COLUMN body SET STORAGE EXTERNAL;View examples
Create a large objectSELECT lo_from_bytea(0, decode('89504e47', 'hex'));View examples
Read a large-object rangeSELECT lo_get(content_oid, 0, 4096) FROM app.large_assets WHERE asset_id = 42;View examples
Write a large-object rangeSELECT lo_put(content_oid, 4096, decode('00010203', 'hex')) FROM app.large_assets WHERE asset_id = 42;View examples
Grant large-object read accessGRANT SELECT ON LARGE OBJECT 24680 TO asset_reader;View examples
Delete a large objectSELECT lo_unlink(24680);View examples
List large-object metadataSELECT oid, lomowner::regrole FROM pg_largeobject_metadata ORDER BY oid;View examples

Modeling and Data Types · 16 commands

PostgreSQL Collations and Locale Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Inventory available collationsSELECT collname, collprovider, collisdeterministic, collversion FROM pg_collation ORDER BY collname;View examples
Decode provider metadataSELECT collname, CASE collprovider WHEN 'b' THEN 'builtin' WHEN 'c' THEN 'libc' WHEN 'i' THEN 'icu' END FROM pg_collation;View examples
Create a deterministic ICU collationCREATE COLLATION app.en_sort (provider = icu, locale = 'en-US');View examples
Create a builtin collation aliasCREATE COLLATION app.unicode_fast (provider = builtin, locale = 'PG_UNICODE_FAST');View examples
Copy a known collationCREATE COLLATION app.bytewise FROM pg_catalog."C";View examples
Create case-insensitive comparisonCREATE COLLATION app.case_insensitive (provider = icu, locale = 'und-u-ks-level2', deterministic = false);View examples
Ignore accent differencesCREATE COLLATION app.base_letter (provider = icu, locale = 'und-u-ks-level1-kc-true', deterministic = false);View examples
Set a column collationdisplay_name text COLLATE app.en_sort NOT NULLView examples
Override one expressionSELECT display_name FROM app.people ORDER BY display_name COLLATE app.en_sort;View examples
Resolve mixed-collation inputSELECT left_text COLLATE app.en_sort < right_text COLLATE app.en_sort FROM app.comparisons;View examples
Enforce insensitive uniquenessCREATE UNIQUE INDEX users_name_ci_key ON app.users (name COLLATE app.case_insensitive);View examples
Index a specific sort orderCREATE INDEX people_name_en_idx ON app.people (display_name COLLATE app.en_sort);View examples
Detect collation version driftSELECT collname FROM pg_collation WHERE collversion IS DISTINCT FROM pg_collation_actual_version(oid);View examples
Rebuild collation-dependent indexesREINDEX INDEX CONCURRENTLY app.people_name_en_idx;View examples
Record the current provider versionALTER COLLATION app.en_sort REFRESH VERSION;View examples
Delegate collation creationGRANT USAGE, CREATE ON SCHEMA app TO locale_admin;View examples

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
CMDMEMO TERMINALREAD ONLY