SQL Flow Field Guide

Learn SQL Server from the first query

Write your first SELECT, then work through database changes, performance, and recovery.

Learning path

Foundations

Write your first query and explain which rows it returns.

  1. Choose the columns a report needs

    Return a clear result with only the requested columns.

  2. Read values with their data types

    Use explicit casts to make the type of a value clear.

  3. See how NULL changes a filter

    Predict how a comparison with NULL affects rows in a WHERE clause.

  4. Label values with CASE

    Turn a score into a readable label with a searched CASE expression.

  5. Combine filters with AND and OR

    Use parentheses to make a multi-part row filter clear.

  6. Choose whether duplicate values stay

    Use DISTINCT when a result needs each projected value once.

  7. Sort rows with a tie-breaker

    Add a unique tie-breaker so equal sort values have a predictable order.

  8. Read one ordered page

    Use OFFSET and FETCH to return a page after sorting the full result.

  9. Name a row's grain and key

    Describe the row grain and distinguish sample uniqueness from an enforced key.

  10. Match rows with an inner join

    Join two row sources on their shared key and predict the joined grain.

  11. Keep unmatched rows with LEFT JOIN

    Preserve every left-side row when no right-side match exists.

  12. Summarize rows by group

    Use GROUP BY and aggregate functions to report one summary row per team.

  13. Filter groups with HAVING

    Apply a condition to aggregated groups with HAVING.

  14. Combine compatible result sets

    Use UNION to combine compatible row shapes and remove duplicate result rows.

  15. Read an invalid-column error

    Use an error number and message to choose the next check for a failed query.

Practitioner

Build database features and check how changes affect data.

  1. Design related tables with enforceable rules

    Choose keys and constraints that make invalid application data fail at the database boundary.

  2. Keep the intended row grain across joins

    Recognize when a one to many join multiplies rows and aggregate the child data before joining it to a parent result.

  3. Track inserts, updates, and deletes with OUTPUT

    Use inserted and deleted row images to record exactly what a data change changed.

  4. Roll back the whole unit of work on error

    Put related changes in one transaction and use TRY/CATCH to undo partial work when a required row is missing.

  5. Call a reusable module with a bound parameter

    Define a session local stored procedure and pass a typed input value by name.

  6. Bind values in dynamic SQL

    Keep SQL text separate from user supplied values when a query must be executed dynamically.

  7. Read a view as a named query

    Explain how a view exposes a reusable query definition and how an outer query adds its own filter.

  8. Turn a JSON array into typed rows

    Use OPENJSON with an explicit schema to read application JSON as relational columns.

  9. Ask a temporal table for an earlier row version

    Use FOR SYSTEM_TIME AS OF to read the version of a system-versioned row that was valid at a chosen time.

  10. Rank and compare rows without collapsing them

    Use window functions to add per-team rank, running totals, and previous-row comparisons while preserving each input row.

  11. Walk a dependency tree with a recursive CTE

    Separate a recursive CTE's anchor from its recursive member and carry depth and path through each level.

  12. Page with a stable keyset cursor

    Continue an ordered result from the last seen key without relying on an offset that shifts when earlier rows change.

  13. Detect a competing update with rowversion

    Use a rowversion token in an update predicate so an application can detect that another writer changed the row.

  14. Filter a date range with a half-open boundary

    Write a date range that includes the start, excludes the next period, and leaves the filtered column unwrapped in a function.

  15. Review a permission request at object scope

    Connect a least-privilege request to the exact permission, securable, and database principal it affects.

Expert practice

Investigate performance, recover data, and review complex SQL.

  1. Expand a bill of materials without looping

    Trace a recursive CTE through a component graph, multiply quantities along each path, and stop revisiting a node on the same path.

  2. Compare window frames and rank tied results

    Choose explicit window frames, distinguish peer-aware running totals from row-by-row totals, and return the top ranks without losing ties.

  3. Reconcile sets and label subtotal rows

    Compare distinct sets with `EXCEPT` and `INTERSECT`, then use `GROUPING SETS` and `GROUPING_ID` to distinguish detail rows from subtotals.

  4. Test an index with measured plan evidence

    Compare actual plans and logical reads before and after a covering index on a temporary training table.

  5. Explain estimates with skewed data

    Read estimated versus actual rows and connect a cardinality difference to data distribution and statistics.

  6. Find a plan regression in Query Store

    Compare captured plans and runtime measurements over time before recommending a plan correction.

  7. Trace a live blocking chain

    Identify blocked requests, their blocker session, current wait evidence, and the SQL text available for each session.

  8. Read a deadlock graph and explain the victim

    Reproduce a controlled two-session deadlock in a disposable database and use its graph to identify the cycle and victim.

  9. Reproduce a lost update and protect the write

    Observe a read-then-write race at `READ COMMITTED` and compare it with an atomic update and an optimistic concurrency check.

  10. Claim work safely from a shared queue

    Use one atomic update with locking hints and OUTPUT to claim one ordered queue row per worker.

  11. Recover a failed transaction safely

    Use `SET XACT_ABORT`, `TRY...CATCH`, `XACT_STATE`, and rollback to leave a failed unit of work in a known state.

  12. Build and prove a point-in-time restore plan

    Inspect a backup chain, verify file and log sequence evidence, and rehearse a restore to a separate database name.

  13. Audit effective permissions without changing access

    Inspect the caller's login, database principal, and effective database permissions before requesting or reviewing a role change.

  14. Validate and shred a JSON feed

    Check a JSON contract, project typed fields with `OPENJSON`, and preserve parent rows when an array is empty or the payload is invalid.

  15. Capstone: explain a ticket SLA report

    Build an auditable event-to-SLA report with staged CTEs, JSON extraction, `LAG`, window elapsed time, grouped ticket outcomes, and within-team ranking.

  16. Capstone: reconcile a feed with a deduplicated MERGE

    Build a deterministic source with a ranking CTE, update changed target rows, insert missing keys, and audit each action through `OUTPUT $action`.

Quick labs for new joiners

Learn the work from small queries. Follow the rows, check the result, and use the Microsoft reference when a change reaches a real database.

The examples use synthetic values, read-only checks, or local temporary tables. Review each script before running it.

Download the lab SQL

  1. Check the SQL Server version

    Read the engine version before choosing syntax.

  2. Read a small result

    Choose output columns and give each column a clear name.

  3. Filter rows with NULL

    Write a filter that treats missing values as a separate case.

  4. Order a short result

    Use a stable order before limiting rows.

  5. Join related rows

    Match rows by a key and keep unmatched rows when the report needs them.

  6. Group rows into totals

    Return one summary row for each group key.

  7. Name a query step

    Use a common table expression to name a result used by the next query.

  8. Rank rows inside a group

    Add a row number while keeping each source row in the output.

  9. Change a temporary table

    Create, alter, inspect, and remove a local lab table.

  10. Roll back a lab change

    Compare a temporary row before and after a rolled-back update.

  11. Read a backup inventory

    Build a recovery timeline from synthetic backup records.

  12. Check one permission

    Read the current session's permission without changing access.

Command reference

Browse 2,018 references for SQL Server and sqlcmd. Each entry connects syntax to a practice check. See scope and sources.