SQL Tutorials
Focused SQL and PostgreSQL tutorials for diagnosing real query and operational issues—including GROUP BY errors, N+1 query patterns, transaction deadlocks, missing indexes, and proving a pg_dump backup actually restores cleanly.
Every tutorial includes reproducible table DDL, sample rows, and exact query or EXPLAIN ANALYZE output.
Read the error, then fix it the right way: group by the column, aggregate it or move the aggregate into a subquery. After this, you know which fix keeps your numbers correct.
Keep one row per group in the order you choose with the PostgreSQL DISTINCT ON clause, and compare it with the standard ROW_NUMBER version.
Page through a table with keyset pagination: filter on the last row you showed and add a tie-breaker.
Turn one row per status into one column per status with aggregate FILTER and compare it with CASE. After this, you can build a small pivot table without an extension.
Add a running total with SUM and OVER, restart it for each group and avoid the default-frame surprise when dates tie.
Compare a query and its CTE rewrite in both directions with EXCEPT ALL, including duplicate and NULL rows that a plain set comparison can miss.
Choose timestamptz for a moment in time and see what the session time zone and AT TIME ZONE change. After this, the same moment shows correctly for every reader.
Rank rows inside each group and keep the first three, then decide what to do with ties and compare the LATERAL version.
Insert a row or update the one that is already there in a single statement, using the conflict target, DO NOTHING, DO UPDATE and the EXCLUDED row.
Run one slow query with EXPLAIN ANALYZE and read it with a five-question checklist: rows touched, filtered rows, estimates, loops and sort spills.
Turn on pg_stat_statements in a Docker container and list the statements that cost the most in total. After this, you know which query to tune first, and you do not have to guess.
Build an index with CREATE INDEX CONCURRENTLY while a writer is active, and handle the transaction-block error and the invalid index that a failed build leaves.