Advanced SQL: Query Optimization, Execution Plans, Concurrency
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
- The query is parsed and rewritten (views expanded, subqueries flattened, predicates pushed down).
- The optimizer enumerates access paths, join orders and join algorithms.
- Each candidate is given a cost from statistics: row counts, distinct values, histograms of column values.
- The cheapest plan is executed.
ANALYZE (PostgreSQL) or UPDATE STATISTICS (SQL Server).Access paths
| Operation | Reads | Good when |
|---|---|---|
| Sequential (full table) scan | Every row | A large share of the table is needed |
| Index scan | Index, then matching table rows | Few rows match (selective filter) |
| Index-only scan | The index alone | The index covers all needed columns |
| Bitmap scan | Index to build a row map, then the table in physical order | A 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
| Algorithm | How | Best for |
|---|---|---|
| Nested loop | For each outer row, look up matching inner rows | Small outer input with an index on the inner side |
| Hash join | Build a hash table on the smaller input, probe with the other | Large unsorted inputs, equality joins |
| Merge join | Walk two sorted inputs together | Inputs 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;
EXPLAINshows the estimated plan.EXPLAIN ANALYZEruns 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
- What does a cost-based optimizer rely on to estimate plan costs?
- What is cardinality estimation?
- Which join algorithm suits two large unsorted inputs joined on equality?
- When is a full table scan the better choice?
- What does EXPLAIN ANALYZE do that EXPLAIN does not?
- In a plan, what does a large gap between estimated and actual rows suggest?
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 index | Non-clustered (secondary) index | |
|---|---|---|
| Stores | The table rows themselves, in key order | Keys plus a pointer to the row |
| Per table | One | Many |
| Examples | SQL Server clustered index; InnoDB primary key | Any 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
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 type | Use |
|---|---|
| Hash | Equality only |
| GIN / inverted | Full-text search, arrays, JSON documents |
| GiST / spatial | Geometry, ranges, nearest neighbour |
| BRIN | Huge 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
- How many clustered indexes can a table have?
- For WHERE status = 'paid' AND created_at > X ORDER BY created_at, which index is best?
- What is a partial (filtered) index?
- In InnoDB, why does a wide primary key enlarge every secondary index?
- Which index type is designed for full-text search and JSON containment in PostgreSQL?
- If an index on (a, b) exists, an additional index on (a) alone is usually:
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
| Database | Syntax |
|---|---|
| PostgreSQL, SQLite | INSERT ... ON CONFLICT (key) DO UPDATE SET ... |
| MySQL | INSERT ... ON DUPLICATE KEY UPDATE ... |
| SQL Server, Oracle, standard | MERGE 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
- What are the two parts of a recursive CTE?
- When does a recursive CTE stop?
- What can a LATERAL subquery do that an ordinary derived table cannot?
- Why is LIMIT 20 OFFSET 100000 slow?
- What does keyset pagination require?
- What does GROUP BY ROLLUP (region, product) add?
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.
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
| Lock | Compatible 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
| Pessimistic | Optimistic | |
|---|---|---|
| Idea | Lock first | Detect conflict at write time |
| Best when | Conflicts are frequent | Conflicts 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.
SELECT ... FOR UPDATE SKIP LOCKED lets each worker take a different unlocked row without waiting.Check yourself
- What does MVCC do on an update?
- Under MVCC, does a reader block a writer?
- Why are long-running transactions harmful in an MVCC database?
- How does optimistic locking detect a conflict?
- What does SELECT ... FOR UPDATE do?
- What is SKIP LOCKED useful for?
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');| Strategy | Splits by | Typical use |
|---|---|---|
| Range | Intervals of a value | Time-series data by month |
| List | Explicit values | By country or tenant |
| Hash | A hash of the key | Even distribution |
DELETE.A query that does not filter on the partition key must visit every partition.
Replication
| Synchronous | Asynchronous | |
|---|---|---|
| Commit waits for the replica | Yes | No |
| Data loss on primary failure | None | The last transactions may be lost |
| Write latency | Higher | Lower |
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
- What is partition pruning?
- What is the fastest way to remove a month of old data from a range-partitioned table?
- What do read replicas scale?
- What is replication lag?
- What is a major drawback of sharding?
- What is a materialized view?
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
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
| Advantages | Drawbacks | |
|---|---|---|
| Stored procedures | Fewer network round trips; logic close to data; permission on the procedure only | Harder to version, test and debug; vendor-specific language |
| Triggers | Rules enforced whatever the client | Hidden 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
INquery. 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
- What is the correct defence against SQL injection?
- What does the principle of least privilege mean for an application's database account?
- What is the N+1 query problem?
- What is a drawback of triggers?
- What is parameter sniffing?
- What does row-level security provide?