Brainbotox · Lessons · Exams

Advanced SQL: Query Optimization, Execution Plans, Concurrency

by lazizanie · Programming · Data & AI · SQL · English

Advanced SQL for senior developers: the query optimizer and execution plans, index design, recursive CTEs and keyset pagination, MVCC and locking, partitioning, replication and security.

Study this lesson with its quizzes on Brainbotox →

The SQL query optimizer and execution plans

The query optimizer turns a declarative SQL statement into an execution plan, choosing among many equivalent strategies the one with the lowest estimated cost. Reading plans is the central skill of SQL tuning.

Cost-based optimisation

  1. The query is parsed and rewritten (views expanded, subqueries flattened, predicates pushed down).
  2. The optimizer enumerates access paths, join orders and join algorithms.
  3. Each candidate is given a cost from statistics: row counts, distinct values, histograms of column values.
  4. The cheapest plan is executed.
The key estimate is cardinality: how many rows each step returns. When the estimate is far from reality, because statistics are stale or columns are correlated, the optimizer picks a bad plan. Refresh statistics with ANALYZE (PostgreSQL) or UPDATE STATISTICS (SQL Server).

Access paths

OperationReadsGood when
Sequential (full table) scanEvery rowA large share of the table is needed
Index scanIndex, then matching table rowsFew rows match (selective filter)
Index-only scanThe index aloneThe index covers all needed columns
Bitmap scanIndex to build a row map, then the table in physical orderA medium share, or several indexes combined

An index scan on millions of rows is slower than a full scan: random access costs more than sequential reading.

Join algorithms

AlgorithmHowBest for
Nested loopFor each outer row, look up matching inner rowsSmall outer input with an index on the inner side
Hash joinBuild a hash table on the smaller input, probe with the otherLarge unsorted inputs, equality joins
Merge joinWalk two sorted inputs togetherInputs already sorted on the join key

Reading a plan

EXPLAIN (ANALYZE, BUFFERS)
SELECT c.name, SUM(o.total)
FROM customers c JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= '2026-01-01'
GROUP BY c.name;
  • EXPLAIN shows the estimated plan. EXPLAIN ANALYZE runs the query and adds actual rows and times.
  • Read from the innermost node outward.
  • Compare estimated rows with actual rows: a large gap marks the origin of a bad plan.
  • Look for scans of big tables, sorts and hashes that spill to disk, and nested loops over many rows.

Check yourself

  1. What does a cost-based optimizer rely on to estimate plan costs?
  2. What is cardinality estimation?
  3. Which join algorithm suits two large unsorted inputs joined on equality?
  4. When is a full table scan the better choice?
  5. What does EXPLAIN ANALYZE do that EXPLAIN does not?
  6. In a plan, what does a large gap between estimated and actual rows suggest?

Take the quiz on Brainbotox

Advanced SQL index design: covering, partial and composite indexes

Good index design means building the fewest indexes that serve the most important queries, with columns in the right order.

How a B-tree is used

A B-tree keeps keys sorted in pages, a few levels deep even for hundreds of millions of rows. A lookup descends from the root to a leaf, then follows leaf pages for a range.

Clustered and non-clustered

Clustered indexNon-clustered (secondary) index
StoresThe table rows themselves, in key orderKeys plus a pointer to the row
Per tableOneMany
ExamplesSQL Server clustered index; InnoDB primary keyAny other index

In InnoDB every secondary index stores the primary key as its row pointer, so a wide primary key makes all indexes bigger. PostgreSQL tables are heaps: all its indexes are secondary.

Column order in a composite index

Put columns tested with equality first, then the column used for a range or sort. For WHERE status = 'paid' AND created_at > ... ORDER BY created_at, index (status, created_at).

Once a range condition is applied to a column, the columns after it in the index can no longer narrow the search.

Specialised indexes

-- covering: extra columns stored in the leaf
CREATE INDEX idx_orders_cust ON orders (customer_id) INCLUDE (total, status);
-- partial (PostgreSQL) or filtered (SQL Server): only some rows
CREATE INDEX idx_orders_open ON orders (created_at) WHERE status = 'open';
-- expression index
CREATE INDEX idx_users_lower_email ON users (LOWER(email));
Index typeUse
HashEquality only
GIN / invertedFull-text search, arrays, JSON documents
GiST / spatialGeometry, ranges, nearest neighbour
BRINHuge tables naturally ordered, such as time-series logs

Maintenance and pitfalls

  • Over-indexing slows every write. Remove unused and redundant indexes: (a) is redundant when (a, b) exists.
  • Random keys such as UUID v4 scatter inserts across the tree and cause page splits; time-ordered identifiers insert at the end.
  • Building an index can lock writes. Use CREATE INDEX CONCURRENTLY (PostgreSQL) or online index builds.
  • Indexes bloat or fragment under heavy updates and sometimes need rebuilding.

Check yourself

  1. How many clustered indexes can a table have?
  2. For WHERE status = 'paid' AND created_at > X ORDER BY created_at, which index is best?
  3. What is a partial (filtered) index?
  4. In InnoDB, why does a wide primary key enlarge every secondary index?
  5. Which index type is designed for full-text search and JSON containment in PostgreSQL?
  6. If an index on (a, b) exists, an additional index on (a) alone is usually:

Take the quiz on Brainbotox

Advanced SQL queries: recursive CTEs, LATERAL, keyset pagination

Advanced SQL solves in one statement problems that otherwise need application loops: walking hierarchies, top N per group, multi-level totals, efficient paging and upserts.

Recursive CTEs

WITH RECURSIVE tree AS (
    SELECT id, name, manager_id, 1 AS depth      -- anchor
    FROM employees WHERE manager_id IS NULL
    UNION ALL
    SELECT e.id, e.name, e.manager_id, t.depth + 1   -- recursive step
    FROM employees e JOIN tree t ON e.manager_id = t.id
)
SELECT * FROM tree ORDER BY depth;

The anchor runs once. The recursive member runs repeatedly on the rows produced by the previous step, until it returns nothing. Guard against cycles with a depth limit or a visited path.

LATERAL joins

SELECT c.name, o.id, o.total
FROM customers c
CROSS JOIN LATERAL (
    SELECT id, total FROM orders
    WHERE customer_id = c.id
    ORDER BY created_at DESC
    LIMIT 3
) o;

A LATERAL subquery may refer to tables that precede it in FROM, like a for-each loop. SQL Server writes it CROSS APPLY and OUTER APPLY.

GROUPING SETS, ROLLUP and CUBE

SELECT region, product, SUM(amount)
FROM sales
GROUP BY ROLLUP (region, product);   -- per product, per region, and grand total

Keyset pagination

-- OFFSET: reads and discards 100,000 rows
SELECT * FROM posts ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET 100000;
-- keyset: jumps straight to the position through the index
SELECT * FROM posts
WHERE (created_at, id) < ('2026-11-01 10:00', 98765)
ORDER BY created_at DESC, id DESC
LIMIT 20;
OFFSET gets slower with every page and can skip or repeat rows when data changes. Keyset (seek) pagination stays fast and stable, but needs a unique sort key and cannot jump to an arbitrary page number.

Upserts

DatabaseSyntax
PostgreSQL, SQLiteINSERT ... ON CONFLICT (key) DO UPDATE SET ...
MySQLINSERT ... ON DUPLICATE KEY UPDATE ...
SQL Server, Oracle, standardMERGE INTO target USING source ON ... WHEN MATCHED ... WHEN NOT MATCHED ...

Gaps and islands

To group consecutive rows (streaks of days, runs of the same status), subtract a ROW_NUMBER() from the ordered value: rows of the same run share the same difference, which becomes the group key.

Check yourself

  1. What are the two parts of a recursive CTE?
  2. When does a recursive CTE stop?
  3. What can a LATERAL subquery do that an ordinary derived table cannot?
  4. Why is LIMIT 20 OFFSET 100000 slow?
  5. What does keyset pagination require?
  6. What does GROUP BY ROLLUP (region, product) add?

Take the quiz on Brainbotox

SQL concurrency control: MVCC, locking and deadlocks

Databases let many transactions run at once using multi-version concurrency control (MVCC) and locks, so that readers and writers interfere as little as possible while data stays correct.

MVCC

An update does not overwrite a row in place. It creates a new version, and each transaction reads from a consistent snapshot of committed data.

With MVCC, readers do not block writers and writers do not block readers. Only two writers of the same row wait for each other.

Old versions must be cleaned up once no snapshot needs them: VACUUM in PostgreSQL, the undo log purge in InnoDB. A long-running transaction keeps old versions alive and bloats the tables.

Locks

LockCompatible with
Shared (read)Other shared locks
Exclusive (write)Nothing

Locks exist at row, page and table level. DDL statements such as ALTER TABLE often take strong table locks.

The lost update problem

-- two sessions both run:
SELECT qty FROM stock WHERE id = 7;      -- both read 10
UPDATE stock SET qty = 9 WHERE id = 7;   -- both write 9: one sale is lost

Three fixes

-- 1. atomic update
UPDATE stock SET qty = qty - 1 WHERE id = 7 AND qty > 0;
-- 2. pessimistic locking
BEGIN;
SELECT qty FROM stock WHERE id = 7 FOR UPDATE;   -- others wait
UPDATE stock SET qty = qty - 1 WHERE id = 7;
COMMIT;
-- 3. optimistic locking with a version column
UPDATE stock SET qty = 9, version = version + 1
WHERE id = 7 AND version = 12;    -- 0 rows affected: someone else changed it, retry
PessimisticOptimistic
IdeaLock firstDetect conflict at write time
Best whenConflicts are frequentConflicts are rare; no long-held locks

Deadlocks

Transaction A locks row 1 then wants row 2, while B locks row 2 then wants row 1. The database detects the cycle and aborts one victim.

  • Lock rows in a consistent order.
  • Keep transactions short.
  • Make the application retry on deadlock and serialization errors.
For job queues, SELECT ... FOR UPDATE SKIP LOCKED lets each worker take a different unlocked row without waiting.

Check yourself

  1. What does MVCC do on an update?
  2. Under MVCC, does a reader block a writer?
  3. Why are long-running transactions harmful in an MVCC database?
  4. How does optimistic locking detect a conflict?
  5. What does SELECT ... FOR UPDATE do?
  6. What is SKIP LOCKED useful for?

Take the quiz on Brainbotox

Scaling SQL databases: partitioning, replication and sharding

When one table or one server is no longer enough, the main techniques are partitioning a table into pieces, replicating data to other servers, and sharding data across independent databases.

Table partitioning

CREATE TABLE events (
    id BIGINT, created_at TIMESTAMP, payload TEXT
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_11 PARTITION OF events
    FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
StrategySplits byTypical use
RangeIntervals of a valueTime-series data by month
ListExplicit valuesBy country or tenant
HashA hash of the keyEven distribution
Partition pruning: when the query filters on the partition key, the database reads only the relevant partitions. Old data is removed by dropping a partition, which is instant compared with a huge DELETE.

A query that does not filter on the partition key must visit every partition.

Replication

SynchronousAsynchronous
Commit waits for the replicaYesNo
Data loss on primary failureNoneThe last transactions may be lost
Write latencyHigherLower

Read replicas scale reads and provide failover. They do not scale writes. With asynchronous replication, a replica can be behind the primary (replication lag): a user may not see what they just wrote. Send read-after-write queries to the primary.

Sharding

Sharding stores different rows on different database servers, chosen by a shard key such as the tenant id. It scales writes, but joins and transactions across shards become hard, and rebalancing is costly. Exhaust simpler options first: indexing, query tuning, caching, a bigger server, read replicas, partitioning.

Other tools

  • Materialized view: stores the result of a query on disk. Fast to read, but must be refreshed.
  • Connection pooling: opening a connection is expensive and each one uses server memory. A pool (in the application, or a proxy such as PgBouncer) reuses a small number of connections.
  • Caching frequent results outside the database, with a clear invalidation rule.
  • CAP theorem: during a network partition, a distributed system must choose between consistency and availability.

Check yourself

  1. What is partition pruning?
  2. What is the fastest way to remove a month of old data from a range-partitioned table?
  3. What do read replicas scale?
  4. What is replication lag?
  5. What is a major drawback of sharding?
  6. What is a materialized view?

Take the quiz on Brainbotox

SQL security, stored procedures and application pitfalls

A production database must be protected against SQL injection and excessive privileges, and the application must avoid access patterns that no index can fix.

SQL injection

-- vulnerable: user input concatenated into the statement
query = "SELECT * FROM users WHERE name = '" + input + "'"
-- input:  ' OR '1'='1     returns every user
-- safe: parameterized query
SELECT * FROM users WHERE name = ?     -- the value is sent separately
With a parameterized query (prepared statement), the SQL text and the values travel separately, so a value can never be interpreted as SQL. This is the defence against injection. Escaping by hand is not.

Identifiers such as table or column names cannot be parameters. Validate them against an allow-list.

Least privilege

CREATE ROLE app_reader;
GRANT SELECT ON orders, customers TO app_reader;
REVOKE ALL ON payroll FROM app_reader;
  • The application account should not own the schema or be a superuser.
  • Group permissions in roles.
  • Row-level security policies restrict which rows a user can see, useful for multi-tenant data.
  • Views can expose only some columns.
  • Encrypt connections, and hash passwords with a slow salted algorithm; never store them in clear text.

Stored procedures, functions and triggers

AdvantagesDrawbacks
Stored proceduresFewer network round trips; logic close to data; permission on the procedure onlyHarder to version, test and debug; vendor-specific language
TriggersRules enforced whatever the clientHidden side effects; slower writes; hard to reason about

Plan caching and parameter sniffing

A prepared statement lets the database reuse an execution plan. The plan may be built for the first parameter values seen. If those are unusual (a customer with millions of rows), the cached plan is poor for everyone else. This is parameter sniffing. Remedies include recompiling, plan hints, or separate queries for skewed cases.

Application pitfalls

  • N+1 queries: one query for a list, then one query per item. Replace with a join or a single IN query. ORMs cause this through lazy loading.
  • SELECT *: transfers unused columns and prevents index-only scans.
  • Missing pagination on lists that grow.
  • Long transactions that hold locks during external calls.
  • Storing everything in one JSON column: flexible, but harder to constrain, index and query than proper columns.

Check yourself

  1. What is the correct defence against SQL injection?
  2. What does the principle of least privilege mean for an application's database account?
  3. What is the N+1 query problem?
  4. What is a drawback of triggers?
  5. What is parameter sniffing?
  6. What does row-level security provide?

Take the quiz on Brainbotox