HomeAll tracks · pricing · account
Python11 apps · Python, SQL & data
Start free Log in

BitSize Python · PostgreSQL

Query a real database.

Real PostgreSQL in your browser, on a café database. Nothing to install.

SELECT * FROM orders… WHERE qty >= 2SELECT item, sum(qty) … GROUP BY item
itemqtyprice
1tea22.50
2coffee13.20
3cake33.80
4coffee23.20
5tea42.50
itemsum
cake3
coffee2
tea6

Track your progress

Save where you are and see what you remember.

Sign up free →
Part 1

Querying basics

0/6

SELECT and columns, WHERE, ORDER BY and LIMIT, NULL and COALESCE, expressions and CASE, DISTINCT.

  1. 01 SELECT: ask for the columns you needSELECT · FROM · column lists · * · AS · expressions Up next
  2. 02 WHERE: keep only the rows you wantWHERE · = <> < > <= >= · AND · OR · NOT · brackets · IN · BETWEEN · LIKE · ILIKE · date literals Free account
  3. 03 ORDER BY and LIMIT: top-N and pagesORDER BY · ASC · DESC · several keys · NULLS FIRST/LAST · LIMIT · OFFSET · FETCH FIRST … WITH TIES Free account
  4. 04 NULL: the missing valueIS NULL · IS NOT NULL · three-valued logic · COALESCE · NULLIF · IS DISTINCT FROM · NOT IN trap 🔒 Subscribe
  5. 05 Expressions and CASE: compute new columnsinteger vs numeric division · :: casts · round · upper · lower · initcap · length · left · replace · ::date · extract · CASE 🔒 Subscribe
  6. 06 DISTINCT and DISTINCT ON: one row per …DISTINCT · several columns · NULLs in DISTINCT · DISTINCT ON (key) · ORDER BY picks the winner · tie-breakers 🔒 Subscribe
Part 2

Aggregation

0/6

COUNT, SUM and AVG, GROUP BY, HAVING, FILTER, string_agg and array_agg, ROLLUP.

  1. 07 Aggregates: one number from many rowscount(*) · count(col) · count(DISTINCT col) · sum · avg · min · max · NULLs are skipped · zero rows 🔒 Subscribe
  2. 08 GROUP BY: one row per groupGROUP BY · several keys · grouped or aggregated · group by an expression · CASE bands · ORDER BY an aggregate · NULL group 🔒 Subscribe
  3. 09 HAVING and the order a query runs inHAVING · WHERE vs HAVING · both in one query · HAVING on an unselected aggregate · logical clause order · aliases in ORDER BY 🔒 Subscribe
  4. 10 FILTER and conditional aggregates: a pivot in one querycount(*) FILTER (WHERE …) · sum(x) FILTER · sum(CASE WHEN … ELSE 0 END) · pivots · shares with 100.0 · NULLIF · COALESCE 🔒 Subscribe
  5. 11 string_agg, array_agg and yes/no aggregatesstring_agg · array_agg · ORDER BY inside an aggregate · DISTINCT in an aggregate · count(DISTINCT) · bool_and · bool_or 🔒 Subscribe
  6. 12 Subtotals: GROUPING SETS, ROLLUP and CUBEGROUP BY ROLLUP · CUBE · GROUPING SETS · grouping() · COALESCE labels for total rows 🔒 Subscribe
Part 3

Joins

0/7

Inner and outer joins, self-joins, many-to-many, anti and semi joins, and the fan-out trap.

  1. 13 JOIN: combine two tablesJOIN … ON · table aliases · qualified columns · USING · inner join drops non-matches · join then filter 🔒 Subscribe
  2. 14 Several joins: walking the schemachained JOINs · one ON per table · bridge tables · many-to-many · join + GROUP BY · count(DISTINCT) · row-count checks 🔒 Subscribe
  3. 15 LEFT JOIN: keep everything on the leftLEFT JOIN · NULL-padded rows · count(col) vs count(*) · COALESCE(sum, 0) · conditions in ON vs WHERE · RIGHT JOIN 🔒 Subscribe
  4. 16 Self-joins: a table joined to itselfself-join · two aliases on one table · staff → manager · LEFT self-join · pairs with a.id < b.id · comparing rows 🔒 Subscribe
  5. 17 Semi and anti joins: who has, who hasn'tEXISTS · NOT EXISTS · LEFT JOIN … IS NULL · semi join · anti join · NOT IN and NULL 🔒 Subscribe
  6. 18 FULL and CROSS JOIN: complete gridsFULL OUTER JOIN · CROSS JOIN · generate_series · calendar tables · LEFT JOIN onto a grid · COALESCE to 0 🔒 Subscribe
  7. 19 The fan-out trap: when joins multiply rowsfan-out · row-count checks · count(DISTINCT) · subquery in FROM · pre-aggregation · grain 🔒 Subscribe
Part 4

Subqueries & CTEs

0/6

Scalar, IN and EXISTS subqueries, correlated queries, WITH, recursive trees, LATERAL.

  1. 20 Scalar subqueries: one value, used anywherescalar subquery · subquery in WHERE · subquery in SELECT · share of a total · empty means NULL · more than one row 🔒 Subscribe
  2. 21 IN, ANY and ALL with subqueriesIN (SELECT …) · NOT IN (SELECT …) · NOT IN and NULL · = ANY · > ANY · > ALL · ALL over no rows · NOT EXISTS 🔒 Subscribe
  3. 22 Correlated subqueries: a question per rowcorrelated subquery · outer references · aliases · per-row max/count · empty set gives NULL or 0 · rewrite as a join 🔒 Subscribe
  4. 23 WITH: name your stepsWITH · CTE · chained CTEs · reusing a step · CROSS JOIN to one row · filter at the right step · MATERIALIZED 🔒 Subscribe
  5. 24 WITH RECURSIVE: trees and sequencesWITH RECURSIVE · anchor · UNION ALL · recursive member · depth · path · walking up and down a tree · date spine · termination 🔒 Subscribe
  6. 25 LATERAL: a subquery for every rowJOIN LATERAL · ON true · LEFT JOIN LATERAL · ORDER BY + LIMIT per row · top N per group · generate_series per row 🔒 Subscribe
Part 5

Window functions

0/7

OVER and PARTITION BY, ranking, running totals, LAG and LEAD, frames, top-N per group.

  1. 26 Window functions: totals without losing rowsOVER () · PARTITION BY · sum/avg/count OVER · share of a total · windows over GROUP BY · window vs GROUP BY 🔒 Subscribe
  2. 27 Ranking: row_number, rank and dense_rankrow_number() · rank() · dense_rank() · ntile(n) · OVER (PARTITION BY … ORDER BY …) · ties · tie-breakers 🔒 Subscribe
  3. 28 Running totals and the default framesum() OVER (ORDER BY …) · running count · running max · PARTITION BY · default RANGE frame · peers · ROWS BETWEEN 🔒 Subscribe
  4. 29 LAG and LEAD: compare with the row beforelag() · lead() · offset and default · day-on-day change · interval gaps · percentage change with NULLIF · PARTITION BY 🔒 Subscribe
  5. 30 Window frames: moving averages and first/lastROWS BETWEEN · PRECEDING / FOLLOWING · moving average · first_value · last_value · nth_value · RANGE with an interval 🔒 Subscribe
  6. 31 Top N per group and filtering on a windowrow_number in a CTE · WHERE rn <= n · rank and ties · DISTINCT ON for N = 1 · JOIN LATERAL · filter before or after ranking 🔒 Subscribe
  7. 32 Window patterns: streaks, shares and named windowsgaps and islands · date - row_number() · percent_rank · cume_dist · WINDOW w AS (…) · CTE + window reports 🔒 Subscribe
Part 6

PostgreSQL types

0/7

Text and regex, dates and intervals, time buckets, casting, JSONB and arrays.

  1. 33 Text functions: slice, pad and formatsplit_part · strpos · substring · left/right · btrim · lpad/rpad · concat · concat_ws · format · repeat · lower 🔒 Subscribe
  2. 34 Regular expressions: match, extract, clean~ · ~* · !~ · anchors ^ $ · [0-9] \d \s · groups · regexp_match · substring FROM · regexp_replace … 'g' · regexp_split_to_table · regexp_count 🔒 Subscribe
  3. 35 Dates, times and intervalsdate · timestamp · timestamptz · date − date · interval · extract(epoch / dow / isodow) · age() · make_date · to_char · justify_interval 🔒 Subscribe
  4. 36 Time buckets: by hour, day, week and zonedate_trunc · date_bin · extract(hour / isodow) · to_char labels · generate_series over timestamps · AT TIME ZONE 'Europe/London' 🔒 Subscribe
  5. 37 Casting: changing a value's type::type · CAST(x AS type) · to_number · to_date · numeric vs float8 · round(x::numeric, n) · CASE + regex guards · boolean casts 🔒 Subscribe
  6. 38 JSONB: documents inside a column-> · ->> · #>> · @> · ? · jsonb_typeof · jsonb_object_keys · jsonb_array_elements_text · (x->>k)::int · jsonb_build_object · jsonb_agg 🔒 Subscribe
  7. 39 Arrays: lists inside a rowtext[] · arr[1] · cardinality · = ANY(arr) · @> · && · unnest · array_agg · array_to_string · string_to_array · array_position · array_append 🔒 Subscribe
Part 7

Writing data & schema

0/8

CREATE TABLE, constraints, INSERT … RETURNING, UPDATE, DELETE, upserts, transactions, views.

  1. 40 INSERT: add rows and see what you addedINSERT INTO … (cols) VALUES · multi-row VALUES · DEFAULT · INSERT … SELECT · RETURNING · key and CHECK errors 🔒 Subscribe
  2. 41 UPDATE: change rows safelyUPDATE … SET … WHERE · several columns · expressions · CASE in SET · UPDATE … FROM · RETURNING old/new 🔒 Subscribe
  3. 42 DELETE: remove rows without regretsDELETE … WHERE · preview with SELECT · RETURNING · DELETE … USING · foreign key errors · children first · soft delete · removing duplicates 🔒 Subscribe
  4. 43 CREATE TABLE: design a tableCREATE TABLE · types · PRIMARY KEY · GENERATED ALWAYS AS IDENTITY · DEFAULT · NOT NULL · generated columns · ALTER TABLE · ALTER TYPE … USING · information_schema.columns 🔒 Subscribe
  5. 44 Constraints: let the database say noCHECK · multi-column CHECK · UNIQUE · NOT NULL · FOREIGN KEY · ON DELETE CASCADE / SET NULL · CONSTRAINT name · ALTER TABLE … ADD CONSTRAINT · pg_constraint 🔒 Subscribe
  6. 45 Upserts: INSERT … ON CONFLICT and MERGEON CONFLICT DO NOTHING · DO UPDATE SET · EXCLUDED · t.col + EXCLUDED.col · DO UPDATE … WHERE · conflict targets · MERGE · WHEN MATCHED / NOT MATCHED 🔒 Subscribe
  7. 46 Transactions: all or nothingBEGIN · COMMIT · ROLLBACK · SAVEPOINT · ROLLBACK TO SAVEPOINT · RELEASE SAVEPOINT · aborted transactions · isolation · FOR UPDATE 🔒 Subscribe
  8. 47 Views and materialised viewsCREATE VIEW · CREATE OR REPLACE VIEW · updatable views · WITH CHECK OPTION · CREATE MATERIALIZED VIEW · REFRESH MATERIALIZED VIEW 🔒 Subscribe
Part 8

Performance & power

0/5

Indexes and EXPLAIN, reading plans, PL/pgSQL functions and triggers.

  1. 48 Indexes: find rows without reading them allCREATE INDEX · B-tree · EXPLAIN (COSTS OFF) · Seq Scan vs Index Scan · composite · partial · expression · UNIQUE 🔒 Subscribe
  2. 49 Reading EXPLAIN: what the planner didEXPLAIN (COSTS OFF) · plan trees · Seq/Index/Bitmap Scan · Hash Join · Nested Loop · Merge Join · HashAggregate · EXPLAIN ANALYZE · sargable 🔒 Subscribe
  3. 50 Functions: SQL and PL/pgSQLCREATE FUNCTION · LANGUAGE sql · RETURNS TABLE · LANGUAGE plpgsql · DECLARE · IF/ELSIF · FOR loop · RAISE EXCEPTION · IMMUTABLE/STABLE 🔒 Subscribe
  4. 51 Triggers: react to every changeRETURNS trigger · CREATE TRIGGER · BEFORE / AFTER · FOR EACH ROW / STATEMENT · NEW · OLD · TG_OP · WHEN · RAISE EXCEPTION · audit log 🔒 Subscribe
  5. 52 Performance patterns that scalekeyset pagination · row comparison (a, b) > (x, y) · EXISTS vs count(*) > 0 · UNION ALL vs UNION · INCLUDE · N+1 · INSERT … SELECT · ON CONFLICT batches 🔒 Subscribe
Part 9

Case files

0/5

End-to-end reports on the café database: sales, cohorts, stock, funnels, cleaning.

  1. 53 Case file: the March sales reviewbusiness rules · order grain in a CTE · KPIs per branch and category · date_trunc week · lag · rank with ties · FILTER rates · GROUPING SETS reconciliation 🔒 Subscribe
  2. 54 Case file: who comes back?cohorts · date_trunc week · retention · repeat rate · lag · row_number · ntile RFM · CASE segments · reconciling totals 🔒 Subscribe
  3. 55 Case file: suppliers and deliveriesscorecards · FILTER · interval minutes · grace periods · missing as failures · LEFT JOIN coverage · ROLLUP checks · rank ties · cover days · reorder quantities 🔒 Subscribe
  4. 56 Case file: busy hours and staffinggenerate_series grids · CROSS JOIN · LEFT JOIN + COALESCE · FILTER pivots · range joins · NULLIF · window shares · rank ties · reconciliation 🔒 Subscribe
  5. 57 Case file: the messy importprofiling with FILTER · trim · initcap · regexp_replace · regex checks · to_date · text to numeric · row_number dedupe · matching · ON CONFLICT DO UPDATE · reconciliation 🔒 Subscribe