PostgreSQL SQL Cheat Sheet

Quick reference guide for PostgreSQL: JSONB, window functions, indexing, CTEs, and psql CLI.

Databases
postgresql
postgres
sql

PostgreSQL is a powerful, open-source object-relational database system known for reliability, feature robustness, and performance with complex queries.

Essential `psql` CLI Commands

Table
CommandAction / Purpose
psql -U username -d dbnameConnect to PostgreSQL database
\lList all databases on server
\c dbnameConnect to a different database
\dtList all tables in current database schema
\d tablenameDescribe table columns, data types, and indexes
\ef function_nameEdit PostgreSQL function definition
\qQuit psql interactive terminal

JSONB Operations & Query Operators

PostgreSQL provides native JSONB indexing and query operators for semi-structured data.

Table
OperatorMeaning / ActionSQL Example
->Extract JSON element by key (returns JSON)data->'user'
->>Extract JSON element as textdata->>'email'
#>Extract nested JSON by pathdata#>'{user, address}'
@>Check if JSONB contains targetdata @> '{"role": "admin"}'
?Check if string exists as top-level keydata ? 'active'
sql
-- Querying JSONB columns
SELECT id, data->>'name' AS user_name
FROM users
WHERE data @> '{"active": true}';

Common Table Expressions (CTEs) & Window Functions

sql
-- CTE (WITH clause) example
WITH regional_sales AS (
    SELECT region, SUM(amount) AS total_sales
    FROM orders
    GROUP BY region
)
SELECT region, total_sales
FROM regional_sales
WHERE total_sales > 10000;

-- Window function (ROW_NUMBER & OVER)
SELECT id, department, salary,
       ROW_NUMBER() OVER(PARTITION BY department ORDER BY salary DESC) AS rank
FROM employees;

Indexing Strategies

Table
Index TypeBest Use CaseSQL Example
B-TreeEquality and range queries (=, <, >)CREATE INDEX idx_user_email ON users(email);
GINJSONB, arrays, and full-text searchCREATE INDEX idx_user_data_gin ON users USING gin(data);
Partial IndexIndexing a subset of rowsCREATE INDEX idx_active_users ON users(email) WHERE active IS true;

Common Pitfalls & Tips

[!WARNING] Using -> returns JSON objects or quoted strings; use ->> when comparing JSON values against text literals in SQL WHERE clauses.

[!TIP] Always run EXPLAIN ANALYZE SELECT ... to inspect the query execution plan and verify that indexes are being utilized properly.