Skip to content

SQL & PostgreSQL

Query, design and tune real databases.

Learn SQL from first SELECT to window functions, then design schemas, make queries fast with indexes and EXPLAIN, and understand transactions and concurrency. Finishes with the PostgreSQL admin basics every backend developer needs.

01SQL basics

Get data out of a single table.

  1. Installing PostgreSQL & using psqlPostgreSQL is a database server: a program that stores data and answers SQL queries over a network connection. psql is its command-line client, where you type SQL plus backslash meta-commands to explore databases and tables.9 min
  2. SELECT, WHERE, ORDER BY & LIMITSELECT reads rows from a table. WHERE keeps only rows that match a condition, ORDER BY sorts them and LIMIT returns just the first few. Without ORDER BY, row order is not guaranteed.9 min
  3. NULLs, expressions & built-in functionsNULL means "unknown or missing", not zero or empty text. Any comparison with NULL is unknown, so you need IS NULL and COALESCE. CASE and built-in functions transform strings, numbers and dates inside queries.9 min
  4. INSERT, UPDATE, DELETE & RETURNINGINSERT, UPDATE and DELETE change data. The WHERE clause decides which rows are touched, so run risky changes inside a transaction and use RETURNING to see exactly which rows changed before committing.9 min

02Joins & aggregation

Combine tables and summarise data.

  1. Inner, outer, self & cross joinsA join combines rows from two tables using a matching condition, usually a foreign key. The join type decides what happens to rows that have no match: dropped, kept with NULLs, or paired with everything.10 min
  2. GROUP BY, HAVING & aggregatesAggregates such as COUNT, SUM and AVG collapse many rows into one value. GROUP BY makes one result row per group, and HAVING filters those groups after the aggregates are computed.8 min
  3. UNION, INTERSECT, EXCEPT & DISTINCTSet operations stack or compare the results of two queries with the same number of compatible columns. UNION combines, INTERSECT keeps common rows, EXCEPT keeps rows from the first not in the second.8 min
  4. Practice: reporting queriesReporting queries turn business questions into SQL. Practise the same routine on a sample schema until joins, grouping and top-N patterns come without looking anything up.9 min

03Advanced queries

The features that separate SQL users from SQL experts.

  1. Subqueries, CTEs & recursive CTEsA subquery is a query inside another query. CTEs (WITH clauses) name those steps so complex logic reads top to bottom, and recursive CTEs repeat a step to walk hierarchies like org charts or category trees.10 min
  2. Window functionsWindow functions compute values across related rows without collapsing them. Each row keeps its identity but gains a rank, running total or previous value from its window, defined with OVER and PARTITION BY.9 min
  3. JSONB & arraysJSONB stores JSON documents in a binary form that Postgres can query and index. It suits flexible attributes that vary per row, while array columns hold simple lists of values.8 min
  4. Upserts, views & materialised viewsAn upsert inserts a row or updates it if it already exists, in one atomic statement. Views save a query under a name; materialised views also store its results so expensive reports read instantly.10 min

04Schema design

Good schemas make every query easier.

  1. Entities, relationships & ER diagramsData modelling turns requirements into tables. Nouns become entities (tables), their facts become columns, and relationships become foreign keys, with a join table for many-to-many links.11 min
  2. Normalisation & when to denormaliseNormalisation removes duplicated facts so each piece of data lives in one place. That prevents update anomalies, where changing a fact in one row leaves stale copies elsewhere. Denormalise only on purpose, for measured speed.11 min
  3. Data types, keys & constraintsGood types and constraints make the database reject bad data instead of hoping every app gets it right. Keys identify rows, foreign keys protect relationships, and CHECK and UNIQUE enforce business rules.11 min
  4. Schema migrationsMigrations are versioned scripts that change the schema step by step, stored in Git and applied the same way everywhere. Zero-downtime changes split risky edits into small, backward-compatible steps.11 min

05Indexes & performance

Why queries are slow and how to make them fast.

  1. How B-tree indexes workA B-tree index is a sorted, balanced tree of key values pointing to table rows. Postgres can walk from the root to the right leaf in a few page reads instead of scanning the whole table, and read leaves in order for sorting.12 min
  2. Reading EXPLAIN & EXPLAIN ANALYZEEXPLAIN shows the plan Postgres chose for a query: a tree of scan and join steps with cost estimates. EXPLAIN ANALYZE actually runs it and adds real row counts and timings, revealing where time goes.11 min
  3. Composite, partial, expression, GIN & BRIN indexesBeyond plain B-trees, Postgres offers composite, partial and expression indexes to match specific queries, and other index types: GIN for JSONB, arrays and full-text search, and BRIN for huge, naturally ordered tables.11 min
  4. Query tuning & avoiding N+1Most slow apps suffer from a few slow queries or from too many small ones. Measure first, rewrite or index the worst query, and replace N+1 patterns, where code runs one query per item, with a single batched query.11 min

06Transactions & concurrency

Correct results when many users write at once.

  1. ACID & transaction basicsA transaction groups several statements into one all-or-nothing unit. Either every change is committed together or none are, so a transfer can never take money from one account without adding it to the other.11 min
  2. MVCC & isolation levelsMVCC lets readers and writers work at the same time: every transaction sees a snapshot, and updates create new row versions instead of overwriting. Isolation levels decide how fresh that snapshot is and which anomalies can occur.12 min
  3. Locks, SELECT FOR UPDATE & deadlocksRow locks stop two transactions from changing the same row at once. SELECT ... FOR UPDATE locks rows you plan to change, preventing lost updates. Deadlocks happen when two transactions wait on each other; Postgres aborts one.12 min

07PostgreSQL admin basics

Keep a database healthy, secure and recoverable.

  1. Roles, privileges & row-level securityIn Postgres, users and groups are both roles. Give each app and person its own login role, grant privileges to group roles, and add row-level security when different users may see only their own rows.11 min
  2. Backup & restore: pg_dump, PITRpg_dump makes a logical backup of one database as SQL or an archive you restore with pg_restore. Point-in-time recovery combines a physical base backup with archived WAL so you can restore to any moment, such as just before a bad delete.11 min
  3. VACUUM, autovacuum & bloatBecause of MVCC, UPDATE and DELETE leave old row versions behind as dead tuples. VACUUM marks that space reusable and ANALYZE refreshes planner statistics; autovacuum runs both in the background so tables do not bloat.11 min
  4. Monitoring with pg_stat views & pg_stat_statementsPostgres records what it is doing in pg_stat views. pg_stat_activity shows live sessions, and the pg_stat_statements extension aggregates every query shape so you can find the slowest and most frequent queries.10 min
  5. Connection pooling & key config settingsEach Postgres connection is a separate server process with its own memory, so thousands of connections hurt performance. A pooler like PgBouncer shares a few server connections among many clients, and memory settings decide how much is cached and used per query.11 min

08Capstone project

Design, load, query and tune a real database.

  1. Model the domain & write the ER diagramThe capstone starts on paper: gather what the app must store, draw the entities and relationships, then write DDL and review it against 3NF before any data goes in.12 min
  2. Build a database for an app (e.g. e-commerce or library)The build turns the model into a working, documented database repo: versioned migrations, realistic seed data, analytics queries with CTEs and window functions, indexes proven by EXPLAIN, and a tested backup script.12 min