Your dashboard query ran fine in staging. In production, with three months of data, it takes 47 seconds and the page times out. You add an index — it gets slower. You wrap the query in a CTE — still slow. You rewrite the JOIN — no change. What is going on?
The problem is rarely the SQL syntax. It is the mental model: how the planner reads your query, when it can use an index, and why a window function that looks elegant can force a full scan. SQL Mastery is not about memorizing more functions; it is about understanding the machine underneath. This article walks through the mistakes that keep people stuck at intermediate level, using real query patterns and the numbers behind them.
The three walls everyone hits after basic SELECT
Most learners can write a JOIN and a GROUP BY. Then they hit three walls that no amount of Stack Overflow copy-paste will break:
- Window functions feel like magic. You use ROW_NUMBER() OVER (PARTITION BY …) because it works, but you cannot predict its cost or explain why it sometimes spills to disk.
- CTEs look like free abstraction. You break a query into five CTEs for readability, and suddenly the plan is a nest of sequential scans.
- Indexes are added by intuition. You create an index on every column in the WHERE clause, and the write throughput drops while the read latency barely moves.
These are not separate problems. They share one root: you are thinking in terms of syntax, not in terms of data movement. The database does not execute your query as written; it executes a plan derived from statistics, cost estimates, and physical storage. Until you can read that plan, you are guessing.
A real query, step by step: from 47 seconds to 1.2 seconds
Let us take a concrete case. A SaaS company has a events table with 20 million rows. The dashboard needs the latest event per user per day, plus a running count of events per user over the last 30 days. The original query looks like this:
WITH daily AS (
SELECT user_id, DATE(created_at) AS day, COUNT(*) AS cnt
FROM events
WHERE created_at >= NOW() - INTERVAL '30 days'
GROUP BY user_id, DATE(created_at)
)
SELECT user_id, day, cnt,
SUM(cnt) OVER (PARTITION BY user_id ORDER BY day) AS running_total
FROM daily;
It runs in 47 seconds. The developer suspects the window function and tries to replace it with a self-join. That makes it worse — 3 minutes. Why?
Step 1: read the plan. EXPLAIN (ANALYZE, BUFFERS) shows a sequential scan on events with 20 million rows, then a hash aggregate, then a window aggregate. The filter created_at >= NOW() - INTERVAL '30 days' is not using an index because there is no index on created_at. More on the topic: “Your Index Guess Is a Coin Flip: Prompts That Make an LLM Read EXPLAIN ANALYZE and Name the Bottleneck First”.
Step 2: add the right index. A B-tree index on (created_at) reduces the scan to about 1.5 million rows (30 days of data). The query drops to 8 seconds. But the window function still sorts 1.5 million rows by user_id, day — that is the next bottleneck.
Step 3: push the aggregation down. The window function operates on the result of the CTE, which is already aggregated by user and day. That is correct. But the planner materializes the CTE because it is referenced only once — in PostgreSQL 12 and later, CTEs are inlined by default unless they are recursive or have side effects. So the real issue is the sort for the window.
Step 4: index for the window. The window needs rows ordered by (user_id, day). If we create an index on (user_id, created_at), the planner can use an index-only scan for the aggregation and avoid the sort. But the filter is on created_at alone. Two indexes? Better: a composite index on (created_at, user_id). That serves the filter and provides the order for the window (though the window still needs a sort by user_id, day — the index order is created_at, user_id, which does not match).
So we accept the sort, but we reduce its size. With the index on created_at, the sort operates on 1.5 million rows instead of 20 million. The query runs in 1.2 seconds.
Step 5: verify with EXPLAIN ANALYZE. The plan now shows an index scan, a hash aggregate, and a window aggregate with a sort. The buffers read dropped from 180,000 to 14,000. That is the number that matters.
Why CTEs are not always your friend
Common Table Expressions (CTEs) make queries readable. But readability has a cost, and the cost depends on the database engine and version.
In PostgreSQL before version 12, CTEs were always materialized — the result was written to a temporary table and read back. That meant a CTE filtering 20 million rows down to 100 rows would still scan all 20 million. In PostgreSQL 12 and later, non-recursive CTEs are inlined by default, so the planner can push predicates into them. But if you use MATERIALIZED explicitly, or if the CTE is recursive, you pay the materialization cost. More on the topic: “PostgreSQL Row-Level Security for Multi-Tenant Apps: How RLS Policies Actually Work and Where Tenant Isolation Quietly Fails”.
In MySQL 8.0, CTEs are always materialized or merged depending on the optimizer. In SQL Server, CTEs are not materialized by default but can be. The lesson: know your engine's behavior. A query that is fast in PostgreSQL 14 might be slow in PostgreSQL 10.
A common mistake: using a CTE to filter early, assuming it reduces the data before the join. In engines that materialize, that filter happens after the CTE is built. The fix is often to use a subquery in the FROM clause or to rewrite as a JOIN with the filter in the ON clause.
Window functions: the cost you do not see
Window functions are powerful because they let you compute running totals, ranks, and moving averages without self-joins. But they have a hidden cost: they require the data to be sorted by the partitioning and ordering columns. If the data is not already sorted, the database sorts it — and that sort can spill to disk.
Consider this: you want the top 3 events per user by timestamp. You write:
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn
FROM events
) t WHERE rn <= 3;
If there is no index on (user_id, created_at), the database sorts all 20 million rows. That is expensive. With an index on (user_id, created_at), the planner can use an index scan to provide the order, and the window function becomes a streaming operation. The difference can be 10x or more.
But here is the trap: adding that index might slow down inserts. If the events table is write-heavy, you need to weigh the read benefit against the write cost. There is no free lunch.
Indexes: the types and when they fail
Most developers know B-tree indexes. They are the default and they work for equality and range queries on scalar types. But they are not universal.
- B-tree: good for
=,<,>,BETWEEN,IN, and prefixLIKE 'abc%'. Not good forLIKE '%abc'or full-text search. - GIN: good for
jsonb, arrays, and full-text search (tsvector). Slower to update, faster for containment queries. - GiST: good for geometric data, ranges, and nearest-neighbor searches.
- BRIN: good for very large tables with naturally ordered data (like time-series). Tiny index size, but only effective if the data is physically ordered.
A common mistake: creating a B-tree index on a column with low cardinality (e.g., status with values 'active', 'inactive'). The index is rarely used because the planner decides a sequential scan is cheaper for returning many rows. A partial index (WHERE status = 'active') can help if you query that subset often.
Another mistake: indexing every column in a WHERE clause. Each index adds write overhead. A composite index on (a, b, c) can serve queries on a, (a, b), and (a, b, c), but not on b alone. The order matters.
PL/pgSQL: when to use it and when to avoid it
PL/pgSQL is PostgreSQL's procedural language. It is useful for complex business logic that would require multiple round trips from the application. But it is not a silver bullet.
A common pattern: a developer writes a function that loops over rows and performs an UPDATE for each. That is slow because each UPDATE is a separate statement. Better: use a single UPDATE with a FROM clause, or a CTE with a data-modifying statement.
PL/pgSQL functions can also be inlined by the planner if they are simple (SQL language, not PL/pgSQL, and not volatile). If you need performance, consider writing the logic as a SQL function or using a set-based approach.
How to learn this without breaking production
The gap between intermediate and advanced SQL is not knowledge of syntax; it is the ability to diagnose and fix performance problems under constraints. That requires practice with real plans, real data volumes, and real trade-offs.
Self-study works if you have a production-like environment and the discipline to break things. Reading blog posts helps, but they rarely cover the edge cases. Courses can provide structure, but many focus on syntax rather than diagnostics.
A more effective path: take a query that is slow in your own project, run EXPLAIN ANALYZE, and try to improve it. Compare the plans before and after. Measure the time. That feedback loop is what builds intuition.
If you want a structured path that includes window functions, CTEs, indexes, and PL/pgSQL, with hands-on tasks and an AI tutor to check your reasoning, SQL Mastery offers exactly that. The course adapts to your level: if you score high on a module, it goes deeper; if you struggle, it reinforces the basics. More on the topic: “SQL Mastery (Window Functions, Indexes): How to Reach Expert Level Without Stepping on the Rakes of Optimization”.
But the course is not the only way. You can also:
- Read the PostgreSQL documentation on
EXPLAINand window functions. - Use
pg_stat_statementsto find your slowest queries. - Practice on a local copy of a large dataset (e.g., the Stack Overflow dataset or a generated time-series).
The trade-off: self-study is free but slower and less structured; a course costs money but provides a sequence and feedback. Choose based on how much time you have and how much guidance you need.
Who this is for and who it is not
This path suits data analysts, data engineers, and backend developers who already write SQL daily and want to move from “it works” to “it works at scale.” It also suits scientists who need to process large datasets without waiting for a DBA.
It does not suit absolute beginners who have never written a JOIN. They should start with a basics course or a book like “SQL in 10 Minutes.” It also does not suit people who want a quick certification — there is no certificate here, just skill.
If you are tired of guessing why your query is slow, start by opening EXPLAIN on your worst-performing query. The plan will tell you more than any tutorial.