skipnothing/SQL

SQL

SELECT, JOIN, GROUP BY, window functions, transactions, indexes, work with relational data and see what the engine does behind every query.

You've used a spreadsheet, columns, rows, sorting, filtering, and can read code-like syntax. No prior database experience needed.

Loading…
01

The Relational Model

Tables, rows, columns, keys, the shape of relational data

4/4
#1

Tables, Rows, Columns

Spot when a list of values should become a table, name the type of each column, and predict why row order and duplicates aren't guaranteed.

A CSV says Ada,ada@x.example,28, and a database asks back: what columns, what shape do these values fit? Once that's declared, the engine knows what to allow and what to reject, every row follows the same plan.

12 min
#2

Types & NULL

Pick a type for each column (text, integer, timestamp, boolean), predict what NULL does in comparisons, and decide when a column should allow NULL.

A blank-looking cell can mean three different things: 0, '', or no value at all. The database makes you commit up front, the column carries that decision into every comparison and count it ever sees.

12 min
#3

Primary & Foreign Keys

Choose between a surrogate and a natural primary key, draw the foreign-key arrow from child to parent, and pick what happens to children when the parent row is deleted.

Three rows sit in users: Ada, Brent, Cleo. An order arrives carrying user_id = 2, which user does it point at, and what stops one arriving with user_id = 99 for a user who doesn't exist?

13 min
#4

Normalization

Split a wide spreadsheet into 1NF/2NF/3NF tables by tracing three named bugs to the duplication that causes them, and decide when denormalizing back is a measured trade.

A fat orders sheet stores Ada's name and email on every order she places. Change her email on one row, her three rows disagree; delete the only T-Shirt order, the catalog forgets its price; one shape, three bugs.

14 min
02

Querying One Table

SELECT, WHERE, ORDER BY, expressions, the four moves on a single table

4/4
03

Joining Tables

INNER, LEFT, RIGHT, FULL, set operations, combining rows across tables

4/4
#9

INNER JOIN

Pair rows from two tables on a join condition, predict the result row count when a row matches once or many times (fan-out), and pick between ON and USING.

Three users, four orders: the buyer's name sits in a separate table from the amount. Pair each order with its user by user_id and four matched rows come back; the user who never bought a thing is left out.

14 min
#10

LEFT, RIGHT & FULL JOIN

Keep the unmatched rows an inner join drops with LEFT, RIGHT, and FULL, read a NULL in the result as 'no match found' rather than missing data, and isolate rows with no partner by filtering the padded key with IS NULL.

Three users, but Cleo never ordered, so an inner join drops her. Keep her anyway: pin all three users into the result and let the order columns arrive empty wherever no user_id lines up.

14 min
#11

Self & Cross Joins

Alias a table into two copies so it can pair with itself for hierarchies and row comparisons, and drop the join condition with CROSS JOIN to generate every combination on purpose.

The employees table carries a manager_id column that points right back at its own id. Stand the table up beside a second copy of itself, and every worker can meet their boss on a single row.

12 min
#12

UNION, INTERSECT, EXCEPT

Stack two query results with UNION, INTERSECT, and EXCEPT, drop the duplicate-removal sort with UNION ALL when rows cannot overlap, and line the columns up by position before a reordered select list files the wrong data under the right name.

Two buyers placed three orders in January, two ordered in February, and one shows up in both months. Asking for everyone, only the repeat buyers, or only the January-only crowd is the same two SELECT results stacked three different ways.

11 min
04

Aggregation & Grouping

COUNT, SUM, GROUP BY, HAVING, collapsing many rows to one

4/4
#13

Aggregate Functions

Collapse a whole column to one number with COUNT, SUM, AVG, MIN and MAX, predict how each treats NULLs, and read several aggregates from one SELECT as a single summary row.

Six rows sit in the orders table, four carrying a real amount and two left blank. Ask for the total, the average, the largest, and the engine hands back a single row of numbers, the whole column folded into one.

12 min
#14

GROUP BY

Split rows into one group per distinct value, predict how grouping changes the result row count, and apply the rule that every selected column must be grouped or wrapped in an aggregate.

Six rows in orders, two from each of three buyers, and the whole-table total came back as one number: 188.50. Ask for the total per buyer instead, and three numbers come back, one each.

14 min
#15

HAVING vs WHERE

Filter rows with WHERE before grouping and whole groups with HAVING after, route each condition by what it reads, and know why an aggregate is rejected in WHERE but legal in HAVING.

Six orders rows, two of them refunded: drop the refunds and you have filtered rows. Keep only buyers whose remaining total tops 50, though, and the filter waits for a number that does not exist yet.

11 min
#16

COUNT(*) vs COUNT(col)

Pick between COUNT(*), COUNT(col), and COUNT(DISTINCT col), read the gap each leaves when the column holds NULLs or repeats, and ride the same skip-NULL rule to count only the rows that meet a condition.

Six rows sit in orders, two with no amount and one amount repeated. The question 'how many?' has three honest answers here, and which one you get depends on whether you're counting rows, values, or distinct values.

10 min
05

Subqueries & CTEs

Queries inside queries, IN, EXISTS, WITH, recursive walks

3/3
06

Window Functions

Aggregate without collapsing, OVER, PARTITION BY, ranking, running totals

4/4
#20

OVER() & Ranking

Add OVER() to an aggregate so the rows stop collapsing, number rows with ROW_NUMBER, RANK, and DENSE_RANK, and choose among the three when two rows tie at the same value.

Four rows in orders hold amounts 99.00, 42.00, 42.00, 17.50, and totalling them folds the four into one number, 200.50. Total them a second way and all four rows stay, each now carrying that 200.50 beside it.

14 min
#21

PARTITION BY & ORDER BY

Split a window into one partition per group so an aggregate or ranking restarts at each boundary, order rows inside each partition, and watch ORDER BY turn a flat total into one that climbs row by row.

Four orders sit in orders, two from user 1 and two from user 2, and adding every amount gives one number: 246.50. Ask instead for each user's total beside their rows and that 246.50 splits into 141.00 and 105.50.

13 min
#22

LAG, LEAD & Frames

Reach to a row's neighbors with LAG and LEAD, draw a window's edges explicitly with ROWS BETWEEN, and watch the default RANGE frame lump tied rows where ROWS makes them climb.

Five orders from one customer sit in orders, sorted by date. Each row knows its own amount but not what came just before it, so the answer to 'bigger or smaller than last time' is sitting one row up.

14 min
#23

Window vs GROUP BY

Choose window when you need a value beside every row and GROUP BY when you need one row per group, rewrite either form as the other, and wrap a window in an outer query when you must filter on its result.

Four rows in orders, two customers, and the same SUM(amount) asked twice: once it answers with two totals, once it answers with four rows that each carry their customer's total along for the ride.

12 min
07

Writes, Constraints & Transactions

INSERT, UPDATE, DELETE, constraints, ACID, isolation levels, locks

4/4
#24

INSERT, UPDATE, DELETE

Append rows with INSERT (omitted columns fall to default or NULL), rewrite matched rows with UPDATE, remove matched rows with DELETE, and read the affected-row count, then watch a missing WHERE turn one row into the whole table.

A new order lands in the orders table, and correcting the amount on row id = 104 leaves the other three alone. Forget to name the row, and every order changes, with only one number to warn you.

12 min
#25

Constraints

Declare NOT NULL, UNIQUE, CHECK, and foreign-key constraints so the table rejects a bad write itself, then choose an ON DELETE action (CASCADE, SET NULL, RESTRICT) and predict which write each one blocks.

An order arrives carrying amount = -5, and a plain orders table stores it without complaint. Add one rule to that column and the same write bounces back rejected, the bad row never lands.

14 min
#26

Transactions & ACID

Wrap two writes in BEGIN/COMMIT/ROLLBACK so a crash can't strand a transfer half-done, trace the bank-transfer all-or-nothing, then map each of ACID's four guarantees to the failure it stops and see where consistency stops at the rules you actually declared.

An accounts table holds $300 across two rows. Move $100 from one to the other as a debit then a credit, let the machine die between them, and $100 is simply gone: one row charged, the other never paid.

15 min
#27

Isolation Levels & Locks

Set an isolation level per transaction to trade concurrency for protection from dirty reads, non-repeatable reads, and phantoms, lock a row with SELECT FOR UPDATE so a concurrent writer waits, and break a deadlock by retrying the transaction the engine aborts.

Two clerks open the accounts table at once. One reads a balance of 100, the other commits a change to 120, and the first reads that same row again, now seeing a number that wasn't there when its transaction began.

15 min
08

How Queries Run

Indexes, EXPLAIN, join algorithms, the antipatterns that kill performance

4/4
#28

Indexes

Trace how an index turns a full-table scan into a few-step lookup, judge when the engine skips it for a sequential scan, and apply the leftmost-prefix and covering-index rules to decide which columns to index.

An orders table holds a million rows. You ask for the ten that belong to one customer with WHERE user_id = 7, and the engine reads all million, row by row, checking each one, to hand back ten.

14 min
#29

EXPLAIN & the Planner

Read an EXPLAIN plan inside-out, decode each node's cost and row estimate, and use EXPLAIN ANALYZE to catch the bad row estimate behind a slow plan.

You indexed amount, ran SELECT * FROM orders WHERE amount > 0, and it is still slow. The engine decided how to run that query before it touched a row, and it will show you what it chose.

15 min
#30

Join Algorithms

Choose between nested loop, hash, and merge join by row count, index shape, and sort order, watch why each wins a different region, and predict which one the planner will price cheapest.

Four rows come back from a join of users and orders. The engine had three completely different procedures it could have run to find those same four rows, and it picked one by guessing which would be cheapest.

14 min
#31

Query Antipatterns

Spot the per-row loop that fires 1 + N queries, see why a leading wildcard or a function-wrapped column abandons an index, and rewrite each so the engine does only the work the result needs.

Two queries return the exact same rows from orders. One finishes in a single trip to the database; the other quietly fires a hundred and one, and the row counts on screen give you no hint which one you wrote.

13 min
View full 31-topic curriculum