Chapter 20:. Advanced Topics

The grand finale of our SQL journey!

By now you’re already writing solid, production-ready queries. This chapter is where we go pro-level: features that make analysts, data engineers, and backend developers say “wow, that’s elegant!”

We’re covering five advanced topics that appear in almost every serious job interview and real-world project:

  1. Window functions (ROW_NUMBER, RANK, LEAD, LAG, etc.)
  2. Common Table Expressions (CTE)
  3. Pivot / Unpivot
  4. SQL injection and basic security
  5. Performance tuning basics

We’ll use our familiar bookshop database (books and authors tables) and add a bit more data for realistic examples.

1. Window Functions – Analytics Without Grouping

Window functions let you perform calculations across a set of rows (a “window”) related to the current row, without collapsing the result into one row like GROUP BY does.

They are incredibly powerful for rankings, running totals, comparisons with previous/next rows, etc.

Common window functions:

Function What it does Example Use Case
ROW_NUMBER() Assigns unique sequential number Ranking rows uniquely
RANK() Assigns rank (same rank for ties, skips next) Ranking sales with ties
DENSE_RANK() Assigns rank (same rank for ties, no skip) Ranking without gaps
NTILE(n) Divides rows into n buckets Quartiles, deciles
LEAD() Value from the next row Compare current vs next
LAG() Value from the previous row Compare current vs previous
SUM() OVER() Running/cumulative total Running total sales

Syntax:

SQL

Example 1 – Rank books by price within each author

SQL

Result (example):

author title price row_num rank dense_rank
Chetan Bhagat 2 States 299.00 1 1 1
Chetan Bhagat Half Girlfriend 280.00 2 2 2
Ruskin Bond The Room on the Roof 250.00 1 1 1
Ruskin Bond The Blue Umbrella 180.00 2 2 2

Example 2 – Running total stock + compare with previous book

SQL

Result snippet:

title price stock running_total_stock previous_book_stock next_book_stock
The Palace of Illusions 450.00 25 25 NULL 65
The Immortals of Meluha 349.00 65 90 25 399

2. Common Table Expressions (CTE) – Cleaner, Readable Queries

A CTE (WITH clause) is a temporary named result set that you can reference multiple times in the same query.

Syntax:

SQL

Example – Find top 3 authors by total stock value

SQL

Multiple CTEs + recursive (advanced):

SQL

CTE makes complex queries readable, reusable, and debuggable.

3. Pivot / Unpivot – Turning Rows into Columns and Vice Versa

Pivot = turn rows into columns (e.g., sales by month as columns) Unpivot = turn columns into rows

MySQL does not have native PIVOT/UNPIVOT (SQL Server & Oracle do), but we can simulate with CASE + GROUP BY.

Example – Pivot: Books per author as columns

SQL

Result (pivot-style):

category Ruskin Bond Chetan Bhagat Amish Tripathi
Fiction 1 2 0
Children 1 0 0
Fantasy 0 0 1

Unpivot example (reverse):

SQL

Modern way (MySQL 8+): Use JSON_TABLE or tools like dbt for true pivoting.

4. SQL Injection and Security Basics

SQL injection is when an attacker inserts malicious SQL into your query through user input.

Example of vulnerable code (NEVER DO THIS):

PHP

User enters: ‘ OR ‘1’=’1 → query becomes:

SQL

→ Logs in as first user!

Prevention methods:

  1. Prepared statements / parameterized queries (best & safest)
    PHP
  2. Stored procedures (hide SQL from app)
  3. Input validation & escaping (as backup)
  4. Least privilege – DB user should have only needed permissions
  5. Never concatenate user input into SQL

Other security tips:

  • Use LIMIT on public queries
  • Hash passwords (never store plain text)
  • Use HTTPS
  • Audit logs for sensitive tables

5. Performance Tuning Basics – Quick Wins

Technique When to use How to do it
Indexes Frequent WHERE/JOIN/ORDER BY CREATE INDEX on those columns
EXPLAIN / EXPLAIN ANALYZE See how query is executed EXPLAIN SELECT …
**Avoid SELECT *** Only fetch needed columns SELECT title, price …
Use LIMIT Pagination, top-N queries LIMIT 10 OFFSET 20
Filter early Push WHERE before JOIN WHERE before INNER JOIN
Covering index Index includes all columns in SELECT CREATE INDEX ON books (title, price, author_id)
Avoid functions on indexed columns WHERE YEAR(date) = 2025 → slow WHERE date BETWEEN ‘2025-01-01’ AND ‘2025-12-31’
Statistics up to date Database optimizer needs current stats ANALYZE TABLE books;

Quick checklist:

  1. Run EXPLAIN on slow queries
  2. Add missing indexes
  3. Rewrite query to use indexes
  4. Check for full table scans (type: ALL in EXPLAIN)
  5. Consider partitioning for very large tables

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *