πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

SQL A to Z: A Structured Tour of the Language

ReferenceReference🟒 Free Lesson
Reference

SQL A to Z: A Structured Tour of the Language

One language, six statement families, a dozen concepts that everything else hangs on. This tour maps the whole surface so nothing feels like a hidden room.

  • Execution anatomy β€” what happens between your keystrokes and a result set
  • The statement families β€” DDL, DML, DCL, TCL, and the query core
  • Concept ladder β€” from grain and keys to windows and transactions
  • Roadmap β€” which deep-dive lesson to open next, by topic Read it once to orient; return whenever you need the map.

Prerequisites

  • !Basic SELECT and WHERE experience
  • !Interest in how the pieces of SQL fit together as a whole

What You'll Learn

  • 1Describe what a database does with a statement from parse to execution
  • 2Navigate the statement families and know what each can change
  • 3Place major concepts β€” keys, joins, CTEs, windows, transactions β€” on one coherent ladder
  • 4Use the roadmap to pick the right deep-dive lesson for any gap you find

What Happens When You Run a Statement

Type a query, press Enter, and a surprising amount of machinery engages. The client sends text over a connection. The server's parser checks syntax and resolves names against the catalog β€” tables, columns, functions, roles. The rewriter expands views and applies rule transformations. The planner generates candidate plans, costs each using statistics, and picks one. The executor walks the plan's operator tree, pulling or pushing rows through scans, joins, sorts, and aggregates. Finally the results travel back through the connection, or for writes, become WAL-logged changes that survive a crash.

Knowing this order explains everyday phenomena. A column alias from SELECT is unavailable in WHERE because WHERE executes earlier. Statistics changes require ANALYZE because the planner reads statistics, not data. A view is not a materialized snapshot β€” it is rewriter sugar that inlines the view's query at plan time, which is why EXPLAIN on a view shows the underlying tables' scans.

For writes, transaction control wraps the same pipeline: changes land in buffers, are written to a write-ahead log, and become durable at commit. Understanding that path β€” parse, rewrite, plan, execute, log, commit β€” gives you the mental model every advanced topic builds on.

The Six Statement Families

SQL's verbs sort into families with distinct privileges and blast radii.

FamilyVerbsChangesTypical grant
Query (DQL)SELECTNothingSELECT on specific tables
Data manipulation (DML)INSERT, UPDATE, DELETE, MERGERowsINSERT/UPDATE/DELETE per table
Data definition (DDL)CREATE, ALTER, DROP, TRUNCATE, RENAMEObjectsOwner or CREATE on schema
Data control (DCL)GRANT, REVOKEPrivilege catalogGrant option on the object
Transaction control (TCL)BEGIN, COMMIT, ROLLBACK, SAVEPOINTTransaction stateImplicit with connection
UtilityANALYZE, VACUUM, COPY, EXPLAINEngine internalsVaries; often superuser-adjacent

A useful discipline: separate schema migrations from data loads from application traffic in your tooling and credentials. The role that runs migrations should not be the one the web app uses; the role that loads nightly data should not be able to grant itself privileges.

-- Every family exercised against one small schema
CREATE TABLE authors (
    author_id BIGSERIAL PRIMARY KEY,
    name TEXT NOT NULL UNIQUE
);

CREATE TABLE books (
    book_id BIGSERIAL PRIMARY KEY,
    author_id BIGINT NOT NULL REFERENCES authors (author_id),
    title TEXT NOT NULL,
    published_on DATE,
    price NUMERIC(10, 2) CHECK (price >= 0)
);

-- DCL
GRANT SELECT, INSERT ON books TO app_writer;

-- TCL with DML
BEGIN;
INSERT INTO authors (name) VALUES ('Ursula K. Le Guin');
INSERT INTO books (author_id, title, published_on, price)
SELECT author_id, 'The Dispossessed', DATE '1974-05-01', 14.99
FROM authors WHERE name = 'Ursula K. Le Guin';
COMMIT;

-- Query core with aggregation and window functions
SELECT
    a.name AS author,
    COUNT(b.book_id) AS books,
    ROUND(AVG(b.price), 2) AS avg_price,
    RANK() OVER (ORDER BY COUNT(b.book_id) DESC, AVG(b.price) DESC) AS popularity_rank
FROM authors a
LEFT JOIN books b ON b.author_id = a.author_id
GROUP BY a.author_id, a.name
HAVING COUNT(b.book_id) > 0
ORDER BY popularity_rank, author;

The Concept Ladder

Progress in SQL is less about memorizing verbs and more about climbing a ladder of concepts, each unlocking the next.

Keys and grain. Primary keys identify rows; foreign keys express relationships; candidate keys are alternatives for uniqueness. Grain β€” what one row means β€” is the concept that prevents most metric bugs. Fix grain in your head before joining tables.

Filtering and predicates. Three-valued logic, NULL semantics, sargability. Small surface, endless footguns: NOT IN with NULLs, <> comparisons that drop NULLs, functions on indexed columns that defeat indexes.

Joins. Inner, outer, self, lateral. Cardinality checks β€” does this join fan out my measures? β€” belong in every analytical query review.

Aggregation. GROUP BY collapses rows; HAVING filters groups; aggregates skip or include NULLs in specific ways. The grain of a grouped query is its GROUP BY list; remember that and most aggregation bugs shrink.

Subqueries and CTEs. Scalar, correlated, and non-correlated subqueries; CTEs for readability and, in some engines, materialization control. Recursion unlocks hierarchies.

Window functions. Ranking, value, and aggregate window functions over partitions with explicit frames. The single biggest lever for analytics after GROUP BY.

Sets. UNION, INTERSECT, EXCEPT with their ALL variants β€” duplicates semantics included.

Transactions and isolation. Atomicity, locking, deadlock avoidance, isolation levels, MVCC visibility.

Types and storage. Numeric precision, text encodings, temporal types and time zones, JSON documents, arrays, indexes and their many flavors.

Security and performance. Privileges, row-level policies, injection defense; then plans, statistics, and the tuning loop.

Each rung has a lesson in this course dedicated to it; the roadmap below points you there.

Dialect Divergences You Will Meet

The core of SQL is portable; the edges are not. Knowing where engines diverge saves an afternoon of confusing syntax errors when you switch tools, take an interview in an unfamiliar dialect, or write a migration script.

AreaPostgreSQLMySQLSQL Server
String concatenationa || bCONCAT(a, b)a + b or CONCAT
Current timestampnow()NOW()GETDATE() or SYSDATETIME()
Limiting rowsLIMIT n OFFSET mLIMIT n OFFSET mTOP n or OFFSET ... FETCH
Boolean typetrue BOOLEANTINYINT(1) historicallyBIT
UpsertON CONFLICT ... DO UPDATEON DUPLICATE KEY UPDATEMERGE
Row numberROW_NUMBER() OVERROW_NUMBER() OVERROW_NUMBER() OVER
Date truncationDATE_TRUNCDATE_FORMAT patternsDATETRUNC (2022+)
Identifier quotingdouble quotesbackticks (or ANSI mode)brackets or double quotes

Window functions, CTEs, and the aggregate set are common ground across all three as of their current major versions, which is why the concept ladder β€” not any single dialect's syntax β€” is the durable investment. When portability matters, favor the standard core, isolate engine-specific expressions in views, and keep a per-dialect snippet file so the differences are looked up rather than rediscovered under deadline pressure.

Query Anatomy: One Statement, Annotated

Putting the ladder together, a production-grade query layers concerns in a predictable order. The version below is deliberately expanded β€” CTEs instead of nested subqueries, explicit columns, sargable filter, and a window function for ranking β€” so every concept from the ladder is visible in one place.

-- Annotated production-style query: filter, shape, rank, limit
WITH qualifying_orders AS (                     -- scope: reduce rows early
    SELECT
        o.order_id,
        o.customer_id,
        o.order_date,
        o.total
    FROM orders o
    WHERE o.order_date >= DATE '2024-01-01'      -- sargable range predicate
      AND o.status = 'paid'
),
customer_totals AS (                            -- aggregate: one row per customer
    SELECT
        q.customer_id,
        COUNT(*) AS order_count,
        SUM(q.total) AS lifetime_value,
        MAX(q.order_date) AS last_order_on
    FROM qualifying_orders q
    GROUP BY q.customer_id
),
scored AS (                                     -- window: rank across customers
    SELECT
        ct.*,
        NTILE(4) OVER (ORDER BY ct.lifetime_value DESC) AS value_quartile,
        LAG(ct.lifetime_value) OVER (
            ORDER BY ct.lifetime_value DESC, ct.customer_id
        ) AS prev_customer_value
    FROM customer_totals ct
)
SELECT
    s.customer_id,
    s.order_count,
    ROUND(s.lifetime_value, 2) AS lifetime_value,
    s.last_order_on,
    s.value_quartile,
    ROUND(100.0 * s.lifetime_value / NULLIF(SUM(s.lifetime_value) OVER (), 0), 2)
        AS pct_of_revenue
FROM scored s
WHERE s.order_count >= 3                        -- HAVING-equivalent via filtered CTE
ORDER BY s.lifetime_value DESC
LIMIT 100;

Read the query top to bottom: each CTE answers one question, the window layer adds analytical context, and the outermost select formats and limits the result. That shape β€” narrow early, aggregate deliberately, enrich with windows, present last β€” is worth internalizing as your default structure for analytical SQL.

Roadmap: Where to Go Deep Next

This page is the map; these lessons are the territories.

If you want to learn…Open this lesson
Tables, types, and constraintsSQL Data Types, CREATE TABLE, Constraints
Filtering, NULLs, and pattern matchingWHERE, IN and BETWEEN, LIKE, IS NULL
Join strategies and anti-joinsInner/Left/Right/Full/Self/Cross Join lessons
GROUP BY and HAVINGGROUP BY, HAVING
CASE and conditional logicCASE Expression, COALESCE and NULLIF
Subqueries and CTEsSubqueries, Correlated Subqueries, CTE Intro, Recursive CTE
Indexes and plansIndexes, Query Performance, EXPLAIN and ANALYZE
Transactions and lockingTransactions, Triggers, Stored Procedures
Windows and rankingWindow Functions Intro, ROW_NUMBER/RANK, LEAD/LAG, Advanced Frames
Analytics recipesSQL for Data Analysis
JSON, search, reshapingJSON in SQL, Full-Text Search, PIVOT and UNPIVOT
Pipelines and securitySQL ETL Pipelines, SQL Security
Style and referenceSQL Coding Standards, Glossary, Cheatsheet

A study order that works for most people: foundations (types, DDL, filters) β†’ joins β†’ aggregation β†’ subqueries and CTEs β†’ windows β†’ indexes and EXPLAIN β†’ transactions β†’ analytics and pipelines. Each stage uses the previous ones, so skipping ahead usually produces confusion that looks like the material being harder than it is.

Common Mistakes

Memorizing syntax without the concept ladder

Fix: When a query confuses you, identify which rung β€” grain, NULLs, cardinality, frame β€” is the actual blocker

Writing long nested subqueries where named CTEs would clarify

Fix: Flatten into CTEs with verb-first names so each step is reviewable

Treating EXPLAIN as an advanced topic you will learn later

Fix: Run EXPLAIN on your next ten queries; familiarity compounds quickly

Using one application role for migrations, loads, and traffic

Fix: Split credentials per purpose so each role's blast radius stays small

Best Practices

  • Return to this map whenever a new SQL area feels disorienting
  • Practice each ladder rung with a small dataset before moving up
  • Structure analytical queries as CTE pipelines with explicit columns
  • Pair every index or rewrite with an EXPLAIN check
  • Keep a personal list of dialect differences as you touch new engines

Interview Questions

Q1: In what order does the database execute the clauses of a SELECT?

Roughly FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, and finally LIMIT or OFFSET. Aliases defined in SELECT are therefore unavailable in WHERE.

Q2: How do views and materialized views differ?

A view is stored query text expanded at plan time, always current but paying query cost each use. A materialized view stores computed results, fast to read but requiring a refresh strategy to stay current.

Q3: What does ANALYZE do and when do you need it?

It refreshes the planner's statistics β€” row counts, histograms, correlations β€” by sampling tables. Run it after bulk loads or significant data shifts so the planner stops choosing plans based on stale estimates.

Key Takeaways

  • Statements travel through parse, rewrite, plan, execute, and log β€” the path explains alias and statistic behavior
  • The six statement families carry different privileges; split credentials accordingly
  • The concept ladder β€” grain, predicates, joins, aggregation, CTEs, windows, transactions, types β€” orders your learning
  • Build analytical queries as CTE pipelines: narrow early, aggregate deliberately, enrich with windows
  • This lesson is the map; the linked deep-dives are the territories to explore in order
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement