cs.oldnet

All sheets / Data

PostgreSQL & SQL

SQL query patterns plus Postgres indexing, transactions and tuning.

Joins

JoinReturns
INNERmatching rows in both
LEFTall left rows, NULLs where no match
RIGHT / FULLall right / all from both
CROSScartesian product
self jointable joined to itself (manager/employee)
-- rows in A with no match in B (anti-join)
SELECT a.* FROM a LEFT JOIN b ON b.a_id = a.id WHERE b.id IS NULL;
SELECT * FROM a WHERE NOT EXISTS (SELECT 1 FROM b WHERE b.a_id = a.id);

Aggregation

SELECT dept, COUNT(*) AS n, AVG(salary)
FROM emp
WHERE active                 -- filters rows
GROUP BY dept
HAVING COUNT(*) > 5          -- filters groups
ORDER BY n DESC
LIMIT 10;

Logical order: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT.

Window functions

-- top 3 earners per department
SELECT * FROM (
  SELECT name, dept, salary,
         DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rk
  FROM emp
) t WHERE rk <= 3;

SUM(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) -- 7-day rolling
LAG(price) OVER (PARTITION BY sku ORDER BY ts)   -- previous row
ROW_NUMBER() / RANK() / DENSE_RANK() / NTILE(4)

RANK skips after ties (1,1,3), DENSE_RANK doesn't (1,1,2), ROW_NUMBER is always unique.

CTEs & upsert

WITH recent AS (
  SELECT * FROM orders WHERE created_at > now() - interval '7 days'
)
SELECT user_id, count(*) FROM recent GROUP BY 1;

WITH RECURSIVE tree AS (
  SELECT id, parent_id FROM nodes WHERE id = 1
  UNION ALL
  SELECT n.id, n.parent_id FROM nodes n JOIN tree t ON n.parent_id = t.id
) SELECT * FROM tree;

INSERT INTO users (email, name) VALUES ($1, $2)
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name
RETURNING id;

Indexes

TypeGood for
B-tree (default)=, <, >, BETWEEN, ORDER BY, prefix LIKE 'a%'
Hash= only
GINJSONB, arrays, full-text search
GiST / SP-GiSTgeometric, ranges, nearest-neighbour
BRINhuge, naturally ordered tables (timestamps)
CREATE INDEX CONCURRENTLY idx_orders_user_created ON orders (user_id, created_at DESC);
CREATE INDEX ON orders (status) WHERE status = 'pending';  -- partial
CREATE INDEX ON users (lower(email));                      -- expression
CREATE INDEX ON orders (user_id) INCLUDE (total);          -- covering

Composite index works left-to-right: (a, b) helps WHERE a= and WHERE a= AND b=, not WHERE b= alone.

EXPLAIN

EXPLAIN (ANALYZE, BUFFERS) SELECT ...;
  • Seq Scan on big table + selective filter → missing index.
  • Index Only Scan = best (covering index, visibility map up to date).
  • Estimated vs actual rows far apart → ANALYZE table (stale stats).
  • Join types: Nested Loop (small inner), Hash Join (large, equality), Merge Join (sorted).

Transactions & isolation

  • ACID: Atomic, Consistent, Isolated, Durable.
  • Postgres uses MVCC: readers don't block writers; old row versions cleaned by VACUUM.
LevelPrevents
Read Committed (PG default)dirty reads
Repeatable Read+ non-repeatable reads (PG: also phantoms)
Serializable+ write skew (may abort: retry)
BEGIN;
SELECT * FROM accounts WHERE id = 1 FOR UPDATE;   -- row lock
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
COMMIT;
SELECT ... FOR UPDATE SKIP LOCKED LIMIT 10;  -- job queue pattern

Performance tuning

  • Connection pooling (PgBouncer / RDS Proxy); Postgres processes are heavy.
  • pg_stat_statements for top queries by total time.
  • Keyset pagination: WHERE id > $last ORDER BY id LIMIT 50 instead of big OFFSET.
  • Autovacuum tuning for high-churn tables; watch bloat.
  • Read replicas for read scaling; partitioning (range by date) for huge tables.
  • Avoid SELECT *, N+1 queries, functions on indexed columns in WHERE.

Normalization

  • 1NF atomic values; 2NF no partial dependency on composite key; 3NF no transitive dependency.
  • Denormalize deliberately for read performance (materialized views, cached counts).