T-SQL by Example

Welcome to T‑SQL by Example. Each page shows a bite‑sized example with runnable code, output (when helpful), and a few notes & gotchas.

  • Start with Basics, then explore Joins, Aggregation, and more.
  • Code samples target Microsoft SQL Server (2016+ features are noted).

Basics

  1. Hello, SELECT β€” Selecting constants and a first query.
  2. Columns & Aliases β€” Selecting specific columns, aliasing, schema-qualified names.
  3. WHERE Filters β€” Common predicates, BETWEEN/IN/LIKE/IS NULL and sargability notes.
  4. ORDER BY & TOP β€” Sorting, TOP, WITH TIES, NULLS LAST workaround.
  5. CASE Expressions β€” Simple vs searched CASE, default branch, common patterns.
  6. NULLs & 3-Valued Logic β€” NULL behavior, COALESCE/ISNULL, comparisons and pitfalls.

Joins & APPLY

  1. INNER JOIN β€” Join two tables with matching keys; basic patterns.
  2. OUTER JOINs β€” LEFT/RIGHT/FULL joins, handling unmatched rows.
  3. CROSS/OUTER APPLY β€” Per-row subqueries/TVFs; choose CROSS vs OUTER APPLY.

Aggregation

  1. GROUP BY & Aggregates β€” Compute counts and sums; HAVING for post-aggregate filters.