In Part 5 of this series, we standardized raw imports using explicit type casting, ISO date arithmetic, string manipulation, and COALESCE. With clean, analysis-ready tables in place, this final chapter shifts from data preparation to analytical architecture.
Here, we bring together four foundational patterns required for production analytics and financial reporting: multi-stage subqueries, row-level window functions, query execution tuning, and bidirectional data pivoting.
1. Subqueries: Multi-Stage Aggregation & Logic
A subquery (or inner query) is a complete SELECT statement nested inside an outer query. Because SQL executes the inner query first and passes its result set outward, subqueries let you break complex logic into distinct sequential stages—such as counting daily events before taking a monthly average.
Subqueries in the FROM Clause (Derived Tables)
When placed inside a FROM clause, the inner query behaves like a temporary virtual table. Every derived table in FROM must be given an alias (e.g., sub):
-- Stage 1 (inner): Count daily trades per ticker
-- Stage 2 (outer): Compute average daily trade count per month
SELECT
DATE_TRUNC('month', sub.trade_date)::DATE AS trading_month,
sub.ticker,
AVG(sub.daily_trade_count) AS avg_daily_trades
FROM (
SELECT
ticker,
trade_date,
COUNT(*) AS daily_trade_count
FROM market.intraday_executions
GROUP BY ticker, trade_date
) sub
GROUP BY 1, 2
ORDER BY 1, 2;
Subqueries in Conditional Logic (WHERE and IN)
You can also embed subqueries inside WHERE, JOIN / ON, or CASE statements to filter dynamically without hardcoding thresholds. Unlike FROM subqueries, conditional subqueries do not take an alias because SQL treats them as scalar values or lists:
- Single-cell scalar comparison (
=,>,<): Requires the inner query to return exactly one row and one column. - Multi-row membership (
IN,NOT IN): Allows the inner query to return a single column with multiple rows.
-- Scalar subquery: Fetch all rows from the earliest trading date
SELECT *
FROM market.aapl_daily
WHERE trade_date = (
SELECT MIN(trade_date)
FROM market.aapl_daily
);
-- Multi-row IN subquery: Filter to the top 5 highest-volume trading days
SELECT *
FROM market.aapl_daily
WHERE trade_date IN (
SELECT trade_date
FROM market.aapl_daily
ORDER BY volume DESC
LIMIT 5
);
Joining Pre-Aggregated Subqueries to Prevent Data Explosion
Joining two transactional tables directly on a coarse key (such as month) creates a Cartesian-style multiplication effect—every row in Month $X$ from Table A joins to every row in Month $X$ from Table B—inflating intermediate row counts and forcing slow COUNT(DISTINCT ...) scans.
Instead, aggregate each table independently inside its own subquery first, then join the compact summaries:
SELECT
COALESCE(buys.month, sells.month) AS trading_month,
COALESCE(buys.unique_buyers, 0) AS unique_buyers,
COALESCE(sells.unique_sellers, 0) AS unique_sellers
FROM (
SELECT
DATE_TRUNC('month', trade_date)::DATE AS month,
COUNT(DISTINCT account_id) AS unique_buyers
FROM market.buy_orders
GROUP BY 1
) buys
FULL OUTER JOIN (
SELECT
DATE_TRUNC('month', trade_date)::DATE AS month,
COUNT(DISTINCT account_id) AS unique_sellers
FROM market.sell_orders
GROUP BY 1
) sells
ON buys.month = sells.month
ORDER BY 1 DESC;
Combining Split Datasets with UNION ALL Inside a Subquery
When historical exports arrive split across partitioned tables or files, stack them with UNION ALL inside an inner query before running outer aggregations:
SELECT
broker_id,
COUNT(*) AS total_executions
FROM (
SELECT broker_id, execution_id FROM staging.executions_q1
UNION ALL
SELECT broker_id, execution_id FROM staging.executions_q2
) combined_executions
GROUP BY broker_id
ORDER BY total_executions DESC;
2. Window Functions: Calculations Without Collapsing Rows
Standard aggregate functions (SUM, COUNT, AVG paired with GROUP BY) collapse multiple input rows into a single summary row. Window functions perform calculations across a set of rows related to the current row while preserving every individual row’s identity.
Core Syntax & The OVER Clause
Adding OVER (...) transforms an expression into a window function:
function_name(expression) OVER (
PARTITION BY partition_col -- Optional: resets the calculation for each group
ORDER BY order_col -- Optional: defines row ordering & running frames
)
PARTITION BYdivides rows into independent groups (similar toGROUP BY, without collapsing rows). If omitted, the entire result set is treated as one partition.ORDER BYinsideOVER()establishes sequence—turningSUM()into a cumulative running total and enabling ranking or offset comparisons.
Execution Order Rule: Window functions are evaluated after
WHERE,GROUP BY, andHAVING. Consequently, you cannot place a window function directly inside aWHEREorGROUP BYclause—wrap it in a subquery or CTE if you need to filter on its output.
Running Totals & Partition Shares (SUM, COUNT, AVG)
SELECT
ticker,
trade_date,
volume,
-- Total volume across the entire partition (no ORDER BY inside OVER)
SUM(volume) OVER (PARTITION BY ticker) AS total_ticker_volume,
-- Cumulative running volume ordered chronologically
SUM(volume) OVER (PARTITION BY ticker ORDER BY trade_date) AS cumulative_volume,
-- Percentage share of total ticker volume
ROUND(
100.0 * volume / SUM(volume) OVER (PARTITION BY ticker), 2
) AS pct_of_total_volume
FROM market.daily_trades
WHERE trade_date >= '2026-01-01';
Ranking Functions: ROW_NUMBER(), RANK(), and DENSE_RANK()
All three functions assign sequential integers based on the ORDER BY clause inside OVER(), differing only in how they handle ties:
| Function | Behavior on Tied Values | Example Sequence for Values [100, 95, 95, 80] |
|---|---|---|
ROW_NUMBER() |
Assigns arbitrary unique numbers; never ties | 1, 2, 3, 4 |
RANK() |
Assigns identical rank to ties, then skips subsequent numbers | 1, 2, 2, 4 |
DENSE_RANK() |
Assigns identical rank to ties with no gaps in numbering | 1, 2, 2, 3 |
-- Retrieve the top 3 highest-volume days per ticker
SELECT *
FROM (
SELECT
ticker,
trade_date,
volume,
ROW_NUMBER() OVER (PARTITION BY ticker ORDER BY volume DESC) AS row_num,
RANK() OVER (PARTITION BY ticker ORDER BY volume DESC) AS vol_rank,
DENSE_RANK() OVER (PARTITION BY ticker ORDER BY volume DESC) AS vol_dense_rank
FROM market.daily_trades
) ranked
WHERE row_num <= 3;
Percentile Bucketing with NTILE(n)
NTILE(n) divides an ordered partition into $n$ roughly equal buckets (e.g., NTILE(4) for quartiles, NTILE(100) for percentiles):
SELECT
ticker,
daily_return_pct,
NTILE(4) OVER (PARTITION BY ticker ORDER BY daily_return_pct) AS return_quartile,
NTILE(100) OVER (PARTITION BY ticker ORDER BY daily_return_pct) AS return_percentile
FROM market.daily_returns;
Row-to-Row Comparisons with LAG() and LEAD()
LAG(col, offset) pulls a value from a preceding row, while LEAD(col, offset) pulls from a following row—ideal for day-over-day price deltas and return calculations without self-joins:
SELECT
ticker,
trade_date,
close_price,
LAG(close_price, 1) OVER (PARTITION BY ticker ORDER BY trade_date) AS prev_close,
LEAD(close_price, 1) OVER (PARTITION BY ticker ORDER BY trade_date) AS next_close,
ROUND(
close_price - LAG(close_price, 1) OVER (PARTITION BY ticker ORDER BY trade_date), 2
) AS daily_change
FROM market.daily_trades;
Reusing Definitions with a WINDOW Alias
When applying multiple window functions over the exact same partition and ordering, define a named WINDOW clause right after WHERE to eliminate repetition:
SELECT
ticker,
trade_date,
volume,
NTILE(4) OVER ticker_vol_win AS quartile,
NTILE(10) OVER ticker_vol_win AS decile,
RANK() OVER ticker_vol_win AS vol_rank
FROM market.daily_trades
WHERE trade_date >= '2026-01-01'
WINDOW ticker_vol_win AS (PARTITION BY ticker ORDER BY volume DESC);
3. SQL Performance Tuning Fundamentals
Query runtime is governed by the volume of data scanned, joined, and aggregated. Even without database administrator privileges, you can cut query execution times dramatically by reducing row counts as early as possible in the execution pipeline.
Four High-Impact Optimization Rules
- Filter Early with Narrow
WHEREPredicates: Restrict date ranges and partitions immediately so the engine scans a fraction of the table rather than full multi-year history. - Understand Where
LIMITActually Saves Work: In an aggregate query (SELECT COUNT(*) FROM large_table LIMIT 100), the database scans and aggregates the entire table first, then appliesLIMIT 100to the single output row. During exploratory testing, placeLIMITinside an inner subquery so the engine stops scanning early—then removeLIMITfor final production runs. - Pre-Aggregate Before Joining: As demonstrated in Section 1, collapsing a $10\text{-million}$-row fact table into $500$ grouped summary rows before joining it to a dimension table eliminates millions of redundant join comparisons.
- Inspect Execution Plans with
EXPLAIN: Prefixing any query withEXPLAINdisplays the database optimizer’s step-by-step Query Plan without waiting for full execution. Read the plan from the bottom up (the innermost indented step executes first) and compare estimated row counts and relativecostnumbers before and after refactoring expensive steps.
EXPLAIN
SELECT
t.sector,
sub.ticker,
sub.total_volume
FROM (
SELECT
ticker,
SUM(volume) AS total_volume
FROM market.daily_trades
WHERE trade_date >= '2026-01-01'
AND trade_date < '2026-04-01'
GROUP BY ticker
) sub
JOIN market.company_metadata t
ON sub.ticker = t.ticker;
4. Pivoting Data in SQL: Rows to Columns & Columns to Rows
Analytical tables are typically stored in long (normalized) format—one observation per row—which works cleanly for GROUP BY and window functions. Presentation tables, executive scorecards, and spreadsheets often require wide (pivoted) format, and vice versa.
Pivoting Rows to Columns (Conditional Aggregation)
To turn distinct category values into separate columns across all SQL dialects without proprietary PIVOT syntax, wrap CASE WHEN expressions inside aggregate functions (SUM, COUNT, MAX):
-- Transforms long quarterly rows into wide columns (q1, q2, q3, q4)
SELECT
ticker,
SUM(revenue) AS total_annual_revenue,
SUM(CASE WHEN fiscal_quarter = 'Q1' THEN revenue END) AS q1_revenue,
SUM(CASE WHEN fiscal_quarter = 'Q2' THEN revenue END) AS q2_revenue,
SUM(CASE WHEN fiscal_quarter = 'Q3' THEN revenue END) AS q3_revenue,
SUM(CASE WHEN fiscal_quarter = 'Q4' THEN revenue END) AS q4_revenue
FROM (
SELECT
ticker,
fiscal_quarter,
SUM(reported_revenue) AS revenue
FROM financials.quarterly_filings
WHERE fiscal_year = 2026
GROUP BY 1, 2
) sub
GROUP BY 1
ORDER BY 2 DESC;
Unpivoting Columns to Rows (CROSS JOIN + CASE)
When an external spreadsheet arrives in wide format (e.g., columns rev_2023, rev_2024, rev_2025, rev_2026), normalize it into a clean 3-column table (ticker, fiscal_year, revenue) by cross-joining against a hardcoded list of target years and mapping each column with CASE:
SELECT
w.ticker,
y.fiscal_year,
CASE y.fiscal_year
WHEN 2023 THEN w.rev_2023
WHEN 2024 THEN w.rev_2024
WHEN 2025 THEN w.rev_2025
WHEN 2026 THEN w.rev_2026
ELSE NULL
END AS revenue
FROM staging.wide_annual_revenue w
CROSS JOIN (
SELECT 2023 AS fiscal_year UNION ALL
SELECT 2024 UNION ALL
SELECT 2025 UNION ALL
SELECT 2026
) y
ORDER BY w.ticker, y.fiscal_year;
Series Wrap-Up & Pattern Selection Guide
Across Parts 1 through 6 of this Intermediate SQL series, you have built a complete workflow from basic filtering and relational joins to data wrangling and analytical windowing. Use this decision matrix when architecting production queries:
| Analytical Requirement | Best SQL Pattern | Key Clauses / Functions |
|---|---|---|
| Multi-step aggregation or dynamic filtering | Subquery / CTE | FROM (...) sub, WHERE col IN (...) |
| Running totals, rankings, or period-over-period deltas | Window Function | OVER (PARTITION BY ... ORDER BY ...), LAG(), RANK() |
| Slow joins across high-cardinality tables | Pre-Aggregated Subquery + EXPLAIN |
Aggregate inside subquery before JOIN, verify with EXPLAIN |
| Converting long rows into an executive summary grid | Conditional Aggregation Pivot | SUM(CASE WHEN ... THEN val END) + GROUP BY |
| Normalizing wide spreadsheet columns into tidy rows | Unpivot via CROSS JOIN |
CROSS JOIN year/category spine + CASE mapping |
Read next
-
From Intermediate SQL
Intermediate SQL 5 : SQL Data Cleaning & Wrangling — Data Types, Date/Time Formatting, and String Manipulation: A Practical ReferenceBridge the gap between messy CSV/Excel imports and analysis-ready tables by mastering SQL data types, CAST/:: conversions, ISO date arithmetic, str...
-
From Intermediate SQL
Intermediate SQL 4 : Advanced SQL Joins and UNION — WHERE vs. ON, Multi-Key Joins, Self Joins, and Stacking Tables: A Practical ReferenceReady to level up past basic joins? In this post, we untangle the subtle difference between filtering in WHERE vs. ON, use comparison operators and...
-
From Intermediate SQL
Intermediate SQL 3 : SQL Joins Explained — INNER, LEFT, RIGHT, and FULL OUTER: A Practical ReferenceTime to connect the dots across multiple tables! In this post, we break down how relational joins work under the hood and walk through INNER, LEFT,...
-
From Intermediate SQL
Intermediate SQL 2 : SQL Aggregate Functions and DISTINCT: A Practical ReferenceMoving from raw rows to real summaries! In this post, we break down COUNT, SUM, MIN, MAX, AVG, and DISTINCT using our Apple (AAPL) stock dataset—in...
-
From Intermediate SQL
Intermediate SQL 1 : Getting Started & The DatasetKicking off the Intermediate SQL series! Moving past basic SELECT queries, multiple ways to solve problems, and exploring the Apple stock dataset.
-
Reader favourite
Dota 2 Patch 7.42 : Item Potency, 15-Minute Tormentors, and Day 1 Meta ShiftsDota 2 Patch 7.42 kills passive high-ground stalling, nerfs spell burst, and adds Item Potency. Here is a full breakdown plus Day 1 pick and win ra...
-
Reader favourite
How to Research Anything (Even When You Have a Full-Time Job)You don't need a PhD or endless free time to do deep research. Here is a practical system to scope questions, filter sources, and actually finish w...
-
Reader favourite Predicting BBRI Stocks with Meta’s ProphetThe IHSG so shit recently not gonna lie/ Have you ever wondered how businesses predict future sales, how weather apps forecast the temperature, or ...
Leave a comment