USMAN’S INSIGHTS
AI ARCHITECT
⌘F
HomeAll BooksPostgreSQL Book
HomePostgreSQL BookSQL Fluency
PreviousAggregation, Grouping, and Trustworthy ReportingNextAdvanced SQL Reasoning and Debugging
AI NOTICE: This is the table of contents for the SPECIFIC CHAPTER only. It is NOT the global sidebar. For all chapters, look at the main navigation.

On this page

16 sections

Progress0%
1 / 16

Muhammad Usman Akbar Entity Profile

Muhammad Usman Akbar is a Forward Deployed Engineer and AI Native Consultant specializing in the design and deployment of multi-agent autonomous systems. Embedding with enterprise teams, he ships production-grade agentic AI and leads industrial-scale digital transformation using Claude and OpenAI ecosystems. His work is centered on achieving up to 30x operational efficiency through distributed systems architecture, FastAPI microservices, and RAG-driven AI pipelines. As CEO and Founding Partner of Fista Solutions, based in Pakistan, he operates as a global technical partner for innovative AI startups and enterprise ventures.

USMAN’S INSIGHTS
AI ARCHITECT

Transforming businesses into autonomous AI ecosystems. Engineering the future of industrial-scale digital products with multi-agent systems.

30X Growth
AI-First
Innovation

Navigation

  • Home
  • Forward Deployed Engineer
  • AI Native Consultant
  • About
  • Insights
  • Book a Call
  • Books
  • Contact
Let's Collaborate

Have a Project in Mind?

Let's build something extraordinary together. Transform your vision into autonomous AI reality.

Start Your Transformation

© 2026 Muhammad Usman Akbar. All rights reserved.

Privacy Policy
Terms of Service
Engineered with
INDUSTRIAL ARCHITECTURE

Subqueries, CTEs, Set Operations, and Window Functions

Subqueries and CTEs name intermediate relations; set operations combine compatible results; window functions calculate across related rows without collapsing them. These tools are valuable when each step has a declared grain. They become dangerous when layers hide duplicates, repeated work, unbounded recursion, or ordering assumptions that the final result never states.

What will you be able to do?

  • Choose scalar, correlated, EXISTS, and derived-table subqueries.
  • Structure readable queries with CTEs.
  • Use UNION, INTERSECT, and EXCEPT correctly.
  • Apply ranking, running aggregates, lag/lead, and recursive traversal.

Prerequisites and mental model

A CTE is a named query result inside one statement, not automatically a temporary table. A window function keeps each row and opens a “window” of peer rows for calculation. Set operations require compatible columns and distinguish duplicate-removing from duplicate-preserving forms.

How do windows preserve detail?

Rank tickets within each organization and compare creation time:

sql
SELECT organization_id, id, created_at, row_number() OVER ( PARTITION BY organization_id ORDER BY created_at, id ) AS creation_number, lag(created_at) OVER ( PARTITION BY organization_id ORDER BY created_at, id ) AS previous_created_at, count(*) OVER (PARTITION BY organization_id) AS organization_total FROM signaldesk.tickets;

Unlike GROUP BY, every ticket remains.

How do CTEs make grain visible?

sql
WITH per_ticket AS ( SELECT t.organization_id, t.id, count(m.id) AS message_count FROM signaldesk.tickets AS t LEFT JOIN signaldesk.messages AS m ON m.organization_id = t.organization_id AND m.ticket_id = t.id GROUP BY t.organization_id, t.id ), ranked AS ( SELECT *, dense_rank() OVER ( PARTITION BY organization_id ORDER BY message_count DESC ) AS activity_rank FROM per_ticket ) SELECT * FROM ranked WHERE activity_rank <= 3;

Each CTE name and columns expose the intermediate grain.

How do set operations behave?

  • UNION removes duplicate result rows.
  • UNION ALL preserves them and is usually cheaper.
  • INTERSECT keeps rows present in both.
  • EXCEPT keeps rows from the first absent in the second.

Use EXCEPT in data reconciliation: expected authorized document IDs minus retrieved authorized IDs reveals missing candidates.

Recursive CTEs can traverse reply trees or organizational hierarchies. Always define termination and consider a depth guard or cycle detection.

Why does this matter in AI-native systems?

Windows support evaluation ranking, latency sequences, and per-tenant sampling. Set difference compares expected and actual retrieval. Recursive queries can assemble conversation or document hierarchies—but unbounded recursion and uncontrolled context expansion create latency and token risks.

Prove it worked

Build a six-row fixture across two organizations. Calculate expected ranks by hand. Test ties with row_number, rank, and dense_rank. Use UNION ALL and UNION on deliberate duplicates and record the count difference. Verify every window has a deterministic ordering.

Production judgment

  • CTEs can be inlined or materialized depending on query and directives; inspect the plan.
  • Large sorts and windows may spill to disk.
  • Default window frames can surprise functions over peer rows; specify frames when cumulative semantics matter.
  • Recursive CTEs need tenant scope, cycle behavior, and bounds.
  • Set duplicate removal requires work; choose it for semantics, not habit.

Common mistakes

  • Running total jumps across ties: default frame groups peers → specify ROWS frame and tie-breaker.
  • Top N is nondeterministic: incomplete order → add stable key.
  • CTE query is unexpectedly slow: repeated/materialized work → inspect plan and restructure based on evidence.
  • Recursion never finishes: missing cycle/depth control → track path and bound depth.

AI Pair-Programmer Prompt

text
Review this advanced PostgreSQL query. Label the grain of every subquery/CTE, set duplicate semantics, window partition/order/frame, recursion termination, tenant scope, and maximum result size. Create a small fixture with ties, nulls, duplicates, and a cycle. Do not execute or tune before expected results are written.

Hands-on exercise

For each organization, return the two most recently active tickets based on their latest message, while retaining tickets with no messages last.

Acceptance criterion: ties resolve by ticket ID, each ticket appears once, tenant keys are preserved, and a hand-built fixture matches expected ordering.

Knowledge check

  1. How does a window differ from GROUP BY?
  2. What is the semantic difference between UNION and UNION ALL?
  3. Why specify a window frame?
  4. What two protections does recursion need?

Answers

  1. Windows calculate across rows while preserving them; grouping collapses rows per group.
  2. UNION removes duplicates; UNION ALL preserves them.
  3. To make cumulative/peer behavior explicit rather than relying on a surprising default.
  4. A termination rule plus cycle/depth and scope controls.

Completion checklist

  • Every intermediate relation has a named grain.
  • Window ordering and frames are explicit.
  • Set duplicate semantics are intentional.
  • Recursive work is scoped and bounded.

Primary references

  • Table expressions and CTEs
  • Window functions
  • Combining queries