Read SQL syntax in lessons by topic and run the examples right away in Oracle, PostgreSQL, SQL Server and KDBS sandboxes.
Query Basics
SELECT Basics — Pick columns with SELECT and FROM, filter rows with WHERE, sort with ORDER BY, and fetch only the first few rows.
WHERE: Conditions and Operators — Filter rows with comparison operators, BETWEEN, IN, and LIKE, and set the precedence of AND and OR with parentheses.
NULL and Three-Valued Logic — NULL marks a missing value. See why a comparison has three outcomes (true, false, unknown), and use IS NULL, COALESCE, and NULLIF.
Sorting and Paging — Sort by multiple keys and expressions with ORDER BY, set where NULLs sort, and split results into pages with OFFSET and FETCH.
Aggregation: GROUP BY and HAVING — Summarize rows with COUNT, SUM, AVG, MIN, and MAX, split them into groups with GROUP BY, and filter groups with HAVING. Also covers the logical order of evaluation.
Join Basics: INNER JOIN — Pair rows from two tables by a join condition into one row. Covers the standard JOIN … ON syntax, aliases, aggregation after a join, and when rows multiply.
Joins
Outer Joins and Condition Placement — LEFT JOIN keeps rows without a match and fills the empty side with NULLs. See why the result differs when a condition goes in ON versus WHERE.
Self Joins and Non-Equi Joins — Join a table to itself under two aliases to compare rows, and map values to a range table with BETWEEN or inequalities instead of =. Covers the pitfalls of duplicate pairs and range boundaries.
Multi-Table Joins and FULL OUTER JOIN — When joining three or more tables, see how order and parentheses change the result, the pitfall where an INNER JOIN after a LEFT JOIN undoes the outer join, and FULL OUTER JOIN, which keeps unmatched rows from both sides.
CROSS JOIN, LATERAL, and APPLY — CROSS JOIN builds every combination of rows, while LATERAL and APPLY rerun a subquery for each left row and attach its result. See how to attach each customer's latest N orders in each DB's syntax.
Subqueries
Subqueries: Scalar, IN, EXISTS, Inline Views — A query inside a query. Covers scalar subqueries that return one value, IN for comparing with a list, EXISTS for testing existence, and inline views in the FROM clause.
Subquery Comparisons: ANY, ALL, Row Value Comparison — Write a subquery after a comparison operator. Covers single-row subqueries compared with one value, ANY and ALL compared with many values, and row value comparison of two columns at once.
Rows with the Maximum per Group — Picks the whole row holding the maximum value in each group, using a correlated subquery, an inline view join, NOT EXISTS, and ROW_NUMBER. Each method handles ties and NULLs differently.
Set Operations
Set Operations: UNION, INTERSECT, EXCEPT — Combines two query results row by row (UNION), keeps only the rows in both (INTERSECT), and keeps the rows on one side only (EXCEPT). Also covers the difference between UNION and UNION ALL.
Comparing Two Query Results — Checks whether two queries return the same result and where they differ. Covers two-way EXCEPT and the symmetric difference, comparing duplicate counts with UNION ALL and GROUP BY, EXCEPT ALL, and NULL handling.
WITH
The WITH Clause and Recursive Queries — Uses WITH to name query fragments so a query reads top to bottom, and uses a recursive WITH that refers to itself to generate number sequences and calendars.
Following a Hierarchy with Recursive WITH — Follows parent-child rows with a recursive WITH. Builds depth and path top down, finds the chain of ancestors bottom up, sorts depth first, and detects cycles. Also covers Oracle CONNECT BY.
WITH Patterns: Step-by-Step Assembly, Reuse, Parameters — Uses WITH to assemble a long query step by step, references the same CTE twice for self-comparison and ratios, and gathers constants into a single parameter row. Also covers the per-DB syntax for choosing whether a CTE is inlined or materialized.
Window Functions
Window Functions — The OVER clause computes ranks, running totals, and previous-row values within a group without collapsing rows. Covers PARTITION BY, ORDER BY, and the frame (ROWS BETWEEN).
Distribution and Ratios: NTILE, PERCENT_RANK, CUME_DIST — Divides rows into n buckets and computes percentiles, cumulative distribution, and ratio to the total. Also covers date-range totals (RANGE … INTERVAL) and the WINDOW clause.
Finding Consecutive Ranges: Gaps and Islands — Finds missing numbers (gaps) with LAG/LEAD and groups consecutive ranges (islands) by subtracting the row number from the value. Consecutive login days and ranges where a status changes are split the same way.
Subtotals and Pivots
Subtotals and Totals: ROLLUP, CUBE, GROUPING SETS — Produces aggregates at several levels (detail, subtotal, grand total) with a single GROUP BY. Also covers the GROUPING function that identifies subtotal rows.
Rows to Columns: Pivot and Unpivot — Spreads row values into columns with CASE conditional aggregation. Covers PostgreSQL FILTER, Oracle and SQL Server PIVOT/UNPIVOT, ways to turn columns back into rows, and the limits of pivoting.
KDBS
KDBS SQL: Syntax That Differs from Other DBs — KDBS is not a dialect compatibility layer, so it rejects some syntax that works on other DBs, reporting the byte position. Examples cover AS for aliases, literal types, implicit conversion, comments, and the NOT NULL default.
KDBS: Joins, Subqueries, and the Query Layer — In KDBS, the step chain answers inner equi-joins and subqueries in condition positions, while the query layer answers outer joins, set operations, derived tables, and scalar subqueries. The layer holds the rows it fetches while computing, so each table must be narrowed.
KDBS: Aggregation, Sorting, Paging — Covers KDBS GROUP BY and aggregate functions, HAVING, the rules of ORDER BY (NULL is the largest value, sorting happens only in memory), the LIMIT/OFFSET order, sorts made free by the tuple key, and closed keyset paging.
KDBS: Writing Without CTEs and Window Functions — KDBS rejects WITH (CTE) and OVER (window functions) with NOT_IMPLEMENTED. Shows how to get the same answers with derived tables, correlated subqueries, joins, and ORDER BY … LIMIT.
Practice
Practice Guide — Data extraction problems that need the syntax of the earlier lessons combined. Write SQL for the scenario and run it: the result is compared with the answer query's result and you are told whether it is right.
Practice 1: Monthly VIP Sales — Groups VIP customers' completed 2024 orders by month: order count, sales total and the change from the previous month. Uses joins, aggregation, string functions and LAG.
Practice 2: Top 3 Customers per Region — Sums the Q1 2024 sales of NORMAL-grade customers per customer and picks the top 3 in each region. Uses WITH, aggregation, ROW_NUMBER and PARTITION BY.
Practice 3: Login Streaks of 3 Days or More — Finds, per user, the ranges of three or more consecutive login days. Removes the duplicate records of a day first, then groups with gaps and islands.
Practice 4: VIPs Who Stopped Buying — Finds VIP customers with no completed order in 2025 and adds their number of completed orders and last completed order number. Uses NOT EXISTS, outer joins and aggregation.
Practice 5: Grade × Order Status Table — Counts January 2024 orders with one row per customer grade and one column per order status, then adds the cancel rate and a grand total row. Uses a CASE pivot, ROLLUP and GROUPING.
Practice 6: Headcount Under Each Manager — For each employee with subordinates in an org chart, returns the depth and the headcount and salary total of everyone below. Builds ancestor-descendant pairs with a recursive WITH and sums them with joins and aggregation.
Practice 7: VIPs Who Stopped After Jan and Feb — Finds VIP customers who bought in both January and February 2024 but placed no order in March. Uses INTERSECT, EXCEPT and an IN subquery.