all-about-database
SQL syntax lessons, a hands-on SQL tuning sandbox and a Wiki, all in one place. Run SQL on Oracle, PostgreSQL, SQL Server and KDBS in the browser and compare execution plans Before/After.
- 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.
- Expressions and Functions: CASE, CAST, Strings, Dates — Pick values by condition with CASE, convert types with CAST, and use string and date functions. Many function names differ by DB.
- 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.
- 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: 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: 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.
- 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 — 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 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 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 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.
Tuning
- Transformed index columns and implicit conversion — A query that is slow despite an index. Transforming the column widens the index search range or prevents index use entirely.
- Top-N partial range processing (sort elimination) — When the index order matches the ORDER BY, the query reads only the N rows it needs and stops. The sort operation disappears too.
- Paging deep pages → keyset pagination — ROWNUM paging gets slower toward later pages; change it to read from the last key of the previous page.
- Scalar subquery → join (understanding the caching effect) — Replace scalar subqueries that run once per row with aggregate-then-join. Also see when caching pays off and how it interacts with partial range processing.
- Driving set and join order — An NL join repeats once per row of the side read first. Compare the two orders directly with the LEADING hint.
- NL join vs hash join — See random access explode in an NL join during a large aggregation, and switch it to a hash join.
- Subquery unnesting: FILTER vs semi join — The cost of an EXISTS subquery depends on whether it runs repeatedly as a FILTER or is unnested into a semi join. The join-then-DISTINCT anti-pattern is covered too.
- The NULL trap of NOT IN → NOT EXISTS — If a NOT IN subquery contains even one NULL, the result becomes 0 rows. This is a correctness problem before it is a performance one.
- Splitting OR conditions and optional search conditions — Split OR-combined conditions and the search-screen pattern "apply the condition if a value is given" so the optimizer uses a different execution plan for each branch.
- Existence check: COUNT(*) → stop at the first row — A query that only needs to know whether a row exists counts every row. Change it to stop as soon as it finds the first row, and look at how partial range processing works.
- Range (non-equi) join: NL vs sort merge — A join connected by BETWEEN, such as an amount band table, cannot use a hash join. Solve the problem of an NL join reading a large table once per band by using a sort merge join.
- Outer join direction and HASH JOIN RIGHT OUTER — It is easy to assume an outer join must read the preserved table first. Instead of an NL join driven by a large preserved table, switch the build side of a hash join (SWAP_JOIN_INPUTS) and load the smaller side into memory.
- Top-N join: hash join vs NL join in index order — A screen shows the latest 20 orders with customer names. A hash join must join and sort everything before the first row comes out. An NL join that reads in index order stops at 20 rows.
- INDEX vs FULL hint: clustering over selectivity — The rule "use an index below some percent" is only half right. At the same 3%, the index can win or lose. What decides it is how closely the rows found through the index sit together in the table (clustering).
- INDEX_FFS and covering: not reading the table — If every needed column is in the index, the table need not be read. Look at INDEX_FFS, which reads the whole index instead of the table, and at building a covering query by reducing SELECT * to the needed columns.
- Why hints are ignored: aliases, inline views, global hints — A hint with a mistake raises no error; it is silently ignored. Look at why an alias must be used instead of the table name, at global hints that point from outside to a table inside an inline view, and at checking with the Hint Report.
- Filling the leading index column with an IN list — With a condition only on the second index column, the index cannot be searched by range. If the leading column has only a few values, fill them in with an IN list and turn a FULL SCAN into a few range scans.
- Join predicate pushdown: computing an aggregate view only for the needed customers — A join with a GROUP BY inline view tends to compute the whole view first. Pushing the join condition into the view (JPPD) aggregates only the 1,000 needed customers through the index.
- Computing MIN and MAX together prevents reading only the index ends — Computing only MIN or only MAX reads a few blocks at one end of the index. Computing both in one SELECT reads the whole index. Split them with UNION ALL so each reads only its end.
- Memoize: caching NL join inner results — When the inner side of an NL join is looked up repeatedly with the same key, a Memoize node remembers the results from PostgreSQL 14 on. Joining 20,000 orders of 100 heavy customers to customers cuts customer lookups from 20,000 to 100.
- nvarchar Comparison and CONVERT_IMPLICIT: When a Seek Becomes a Scan — Comparing a varchar column with a Unicode value (N'…', an nvarchar parameter) makes SQL Server convert the column side, and the Index Seek becomes an Index Scan. Finding one order by order number reads 7,478 pages.
- IN condition and Top-N: cut per value, then merge — The 20 latest orders whose status is PAID or CANCELED. With an IN list, the (status, ord_dt) index order differs from ord_dt order, so the sort cannot be skipped. Getting the Top-20 per value and merging with Merge Append reads 40 rows instead of 200,000.
- Groupwise Top-N: ROW_NUMBER() vs LATERAL + LIMIT — The 3 most recent orders for each of 1,000 VIP customers. Written with ROW_NUMBER(), the query joins and sorts all 20,000 customer orders and then keeps 3 per customer. Reading only 3 entries backward from the index for each customer inside LATERAL applies partial range processing per customer. The scenario also shows the conclusion reversing when the number of groups grows.
- Page and total count: COUNT(*) OVER () breaks partial range processing — Adding COUNT(*) OVER () to fetch the first 20-row page of a list and the "N total" in one statement makes the NL join that stopped at 20 rows join all 37,000 rows. Counting separately, and dropping the join the count does not need, cuts Buffers from 92,000 to 256. The scenario also examines when dropping the join is allowed.
- Two 1:N joins: fan-out and conditional aggregation — Computing VIP customers' 2024 and 2025 sales by joining the same orders table twice produces (2024 orders × 2025 orders) rows per customer. One high-volume customer makes the intermediate result 430,000 rows, and the totals inflate by hundreds of times and become wrong. The fix is conditional aggregation that reads the orders only once.
- Transformed join columns: join conditions that keep the NL join inner index usable — Joining 10 numeric order numbers sent by the settlement system with varchar order numbers while converting the orders-side column makes the inner index unusable, so 2 million rows are hash-joined. The same happens when a calendar is joined to orders with date_trunc. Moving the conversion to the outer value, or rewriting it as a range join, lets the NL join use the index.
- Finding the previous row: non-equi self join (triangular join) → LATERAL, LAG — To get the time of the same customer's previous order for each order, a self join with "orders earlier than this one" followed by MAX produces rows proportional to the square of each customer's order count. The 5,428 orders of 10 high-volume customers blow up to 1.47 million rows. The fix is LATERAL, which finds only the one previous row, or LAG, which reads once and is done.
- Rows discarded inside an NL join: data skew and a filter index — A join fetches the 2025 canceled orders of 100 high-volume customers. The optimizer assumes one order per customer and picks an NL join, but the inner side actually reads 54,257 orders all the way to the table and discards 97%. Filtering orders first with an index that holds the filter conditions, then hash joining, cuts Buffers from 54,570 to 3,833.
- OR across two tables: filter after the join → UNION ALL — When one side of an OR is a customer column and the other an order column, as in "orders of VIP customers or canceled orders", neither table can filter first, so all 14,000 orders from the last 7 days are joined before 546 rows are picked. Splitting the OR into two UNION ALL branches and removing overlapping rows with LNNVL lets each branch drive from its own condition, and Buffers drop from 14,527 to 3,408.
- Cut the Top-N first, then attach the aggregate — Attach each customer's total order count and cumulative amount to the 20 most recent paid orders. Joining a per-customer aggregate view first aggregates 2 million orders and joins 140,000 rows before picking 20. Cutting the 20 rows first and aggregating only those 20 customers drops Buffers from 27,900 to 4,461.
- One row from the index end per value: GROUP BY MAX → skipping with recursive WITH — Getting the latest order time per status with GROUP BY status reads all 2 million index entries. There are only three status values, so finding the next status value in the index once at a time with recursive WITH, and reading only one row from the index end for each value's MAX, drops Buffers from 8,304 to 19.
- The ORDER BY index trap: reading 2 million rows to skip a sort — To pick the 20 canceled orders from January 2023 with the largest order IDs, the optimizer reads the PK backward to skip the sort and passes 1.94 million rows before the first matching row appears. It does not know that the matching rows are packed at the opposite end of the PK order. Reading 1,879 rows through the condition index and sorting them drops Buffers from 17,708 to 433.
- Two words, NULLS LAST, block the sort skip — After changing the 20 most recent paid orders to ORDER BY ord_dt DESC NULLS LAST, the backward index scan disappears and the whole table is read and sorted. A descending index scan returns NULLs first. Splitting non-NULL rows and NULL rows with UNION ALL brings Buffers back from 13,950 to 9.
- Case study: branch execution inquiry screen (13 tables, Top-N) — The "today's executions for our branch" screen used by brokerage branch staff. It joins 13 tables to show the latest 20 rows, but a transformed date column, an optional search condition (NVL), tie handling in the sort key, and a structure that attaches dimension tables first combine to read all 2.05 million orders and 50,000 executions. Untangling them one at a time cuts Buffers from 32,130 to 5,406 and CPU from 0.47 s to 0.02 s.
- Case study: daily per-account trade settlement batch (9 tables, 5 scalar subqueries) — A "per-account trade settlement" batch that runs per region after market close. For each account with trades, five separate scalar subqueries compute the execution count, buy and sell amounts, commission, and transaction tax, and because those subqueries filter only on the execution date, each one rereads 41 days of the account's orders every time. Reading the day's executions once and switching to conditional aggregation cuts Buffers from 901,350 to 4,904 and CPU from 0.80 s to 0.05 s.