Advanced SQL: Window Functions, CTEs, and Subqueries Questions
Analytical SQL for complex problems: window functions (ranking, running totals, LAG/LEAD, partitioned aggregates), common table expressions including recursive CTEs, and scalar, nested, and correlated subqueries. Covers when each construct is the right tool and how they compose for multi-step analysis. The differentiator between basic and senior SQL competence.
A 12-week retention matrix (one row per signup cohort, one column per week offset, showing percent still active) needs to run nightly against a table of hundreds of millions of users. Beyond just writing the CTE-and-window-function pipeline, propose the performance strategy that makes this feasible: pre-aggregation, partitioning, materialization, or sampling. Then address a related wrinkle: cohort assignment sometimes requires two sequential events (say signup and onboarding-completed) rather than a single timestamp, and events can arrive late and need backfilling without recomputing the whole table.
Sample Answer
Direct answer: Writing the retention common table expression (CTE, a named WITH-clause subquery) and window-function pipeline is the easy 20%. At hundreds of millions of users, running it from raw events every night is the part that doesn't survive contact with production: the fix is to pre-aggregate raw events into a compact per-user-week activity table, partition that table (and the final matrix) by cohort or activity week so a write only ever touches the weeks it affects, and materialize the 12x12 retention matrix as a small table refreshed incrementally rather than recomputed from scratch. The two-sequential-event cohort assignment (signup, then a later onboarding-completed) and late-arriving backfill are really the same design problem in miniature: both require the pipeline to know precisely which slice of the matrix a given late-arriving event can possibly affect, so it only recomputes that slice.
Structured elaboration
Why nightly-from-raw-events doesn't scale: a retention matrix is a slow-moving key performance indicator, or KPI (it changes by a handful of new signups and a week's worth of new activity each night), but a from-scratch pipeline pays for scanning the entire multi-hundred-million-row, multi-week history every single run, more than 99% of which is unchanged from the previous night. The fix is incremental processing on top of a pre-aggregated, partitioned base table, not a faster version of the same full scan.
Performance strategy, in order of impact:
- Pre-aggregate first. Collapse raw events (many rows per user per day) into
user_week_activity(user_id, activity_week)once. This is the single biggest cardinality reduction: bounded by users x weeks, not users x events. - Partition by the dimension that changes. New activity this week affects every past cohort's retention row simultaneously (a user from a 10-week-old cohort being active this week updates that cohort's week-10 column), so partition/cluster
user_week_activitybyactivity_week, and only append this week's slice. The matrix update for a given cohort_week + week_offset cell then follows directly from who was active in the newly-appended activity week and what their cohort_week was, which only requires touching users active that week, not the full user base. - Materialize the matrix as its own small table. 12 cohorts x 12 offsets is at most ~144 rows; refresh it with a MERGE/upsert against the incremental
user_week_activitydelta, and let dashboards read the small table, never the raw events. - Reserve sampling for exploration only. Approximate counts (e.g. HyperLogLog-style distinct estimators, a family of algorithms that trade a small, bounded error for counting distinct users in a fraction of the memory an exact count would need) are fine for an analyst poking at trends, but a nightly authoritative retention number is exactly the kind of metric (often reported externally or to leadership) where "approximately right" silently erodes trust if it doesn't reconcile with billing or engagement counts elsewhere.
Two-sequential-event cohort assignment (signup, then onboarding-completed): a cohort here isn't a single timestamp, it's the resolution of two ordered events for the same user. A LATERAL join expresses this cleanly:
WITH signups AS (
SELECT user_id, MIN(event_time) AS signup_time
FROM events WHERE event_type = 'signup'
GROUP BY user_id
)
SELECT s.user_id, s.signup_time, ob.onboarding_time,
DATE_TRUNC('week', ob.onboarding_time) AS cohort_week
FROM signups s
JOIN LATERAL (
SELECT MIN(e.event_time) AS onboarding_time
FROM events e
WHERE e.user_id = s.user_id
AND e.event_type = 'onboarding_completed'
AND e.event_time >= s.signup_time
) ob ON ob.onboarding_time IS NOT NULL
ORDER BY s.user_id;
The ON ob.onboarding_time IS NOT NULL turns this into an inner-join-like filter: a user who signed up but never completed onboarding gets no cohort assignment at all, which is correct (they can't be placed on a retention matrix keyed by a week they never reached). A plain window-function alternative (e.g. a filtered MIN() OVER, or LEAD with a type filter) works too; LATERAL makes the "find the qualifying later event" condition explicit and lets an index on (user_id, event_type, event_time) serve it directly. This is a meaningfully different, stricter rule than a simpler daily first-touch cohort assignment (cohort_week = the week of a user's very first event of any kind, with no second qualifying event required); first-touch assignment never has an "unassigned" user, while the two-sequential-event rule always will, for anyone who never reaches step two, and that population needs to be tracked and reported on its own, not silently folded into "week 0 retention."
Late-arriving events and backfill without a full recompute: the failure mode to avoid is treating "backfill" as "rerun the whole pipeline." Instead, track which cohort_week partitions a batch of newly-arrived events actually touches, and MERGE only those:
- A late activity event for an existing cohort only dirties one (cohort_week, week_offset) cell: the user's own cohort_week and the offset implied by the late event's own week.
- A late onboarding_completed event is more dangerous, because it can retroactively change which cohort a user belongs to (a user with no prior cohort assignment now gets one, or one assigned to a wrong/placeholder cohort now moves). The dirty set for that user is the union of their old cohort_week (if any) and their new one; recompute both, not just the partition the late event's own timestamp falls in.
- A per-batch "touched cohort_weeks" list (derived from
DATE_TRUNC('week', <the relevant event time>)on just the newly-arrived rows) is cheap to compute and is exactly what should drive the MERGE's WHERE/target-partition scope.
Worked example (executed in DuckDB)
Three events for two users: user 1 signs up 2026-01-01, completes onboarding 2026-01-03; user 2 signs up and completes onboarding both on 2026-01-02; user 3 signs up 2026-01-05 but never completes onboarding. Running the LATERAL cohort query above returns exactly two rows (users 1 and 2, both assigned cohort_week = 2025-12-29, the Monday-starting week containing their onboarding completion), and correctly omits user 3. A late-arriving onboarding event for user 2 at 2026-01-02 20:00 resolves to DATE_TRUNC('week', ...) = 2025-12-29, giving exactly the one dirty partition that a backfill job would need to re-MERGE, not the whole table.
Trade-offs & pitfalls
- Partitioning only by cohort_week (and not also by activity_week) is a common half-measure: it makes backfilling a mis-assigned cohort cheap, but doesn't help the every-night append of new activity, which is naturally keyed by activity_week instead.
- A recursive common table expression (recursive CTE, one that refers to itself to build a result iteratively; Postgres requires the
RECURSIVEkeyword explicitly, SQL Server does not) can generate the 0..11 week-offset series inline instead of a stored numbers/calendar table, but a small reusable calendar table is usually the better production choice: it's index-friendly and shared across every query that needs a week series, where a recursive CTE regenerates the same series from scratch each time it's used. - Forgetting to widen the dirty-partition set to include a user's previous cohort_week when a late onboarding event reassigns them is the single most common backfill bug in this pattern: it leaves a stale, too-high retention count sitting in the old cohort's row.
For a new KPI calculation that will be reused across multiple dashboards, decide between a CTE, a temporary/staging table, and a materialized view. What criteria drive the decision (readability, reuse, performance, indexability, freshness, transactional behavior), and how does your answer differ for: a one-off ad hoc analysis, a repeatedly-used expensive calculation, and a near-real-time dashboard?
Sample Answer
Direct answer: Pick the tool by matching its physical behavior to what the KPI (key performance indicator) actually needs: a common table expression (CTE, a named subquery written with WITH ... AS (...)) for a one-off analysis you'll run once and throw away, a temp or staging table when the calculation is expensive but the reuse window is short (a single session, a single ETL run, meaning extract-transform-load), and a materialized view (a query whose result is physically stored on disk and refreshed on a schedule or trigger, rather than recomputed on every read) once the same expensive logic is read repeatedly by multiple dashboards and can tolerate being slightly stale. Near-real-time dashboards are the one case where none of the "precompute it" options fit cleanly: they usually need a lean, indexable live query instead, or an incrementally-updated summary table rather than a full materialization.
Structured elaboration
| Criterion | CTE | Temp / staging table | Materialized view |
|---|---|---|---|
| Readability | High: named, inline, keeps logic next to the query that uses it | Medium: logic is split across a create step and a query step | High for consumers: they just query it like any table; the transformation logic lives elsewhere |
| Reuse across queries/dashboards | None by default: re-declared and recomputed in every query that needs it (Postgres 12+ inlines a single-reference CTE by the query planner) | Good within one session or job; not visible to other sessions unless persisted | Best: one physical object every dashboard can SELECT from |
| Performance (recompute cost) | Recomputed every time the query runs; cheap for small inputs, expensive if reused often on a large base table | Computed once per session/job; indexable afterward | Computed once per refresh cycle; reads are just a table scan |
| Indexability | None: a CTE has no persistent structure to index | Yes: you can add indexes to a temp table after loading it | Yes: materialized views can carry their own indexes in most engines |
| Freshness | Always current as of the moment the query runs | Current as of whenever it was populated in that session/job | Only as current as the last refresh; staleness is a designed trade-off, not a bug |
| Transactional behavior | Part of the surrounding transaction; nothing persists beyond the query | Local to a session/connection (or transaction, depending on TEMPORARY/##temp semantics); dropped automatically | A separate persisted object with its own refresh transaction, decoupled from any one query's transaction |
Recommendations by scenario:
- One-off ad hoc analysis: a CTE (or a plain subquery). There is no second reader to amortize setup cost against, so the fastest path to an answer wins over any persistence machinery.
- Repeatedly-used expensive calculation: a materialized view (or, where the engine lacks native materialized views, a scheduled job that populates a plain table). The cost of computing it is paid once per refresh instead of once per dashboard load, and it becomes indexable, which a CTE never is.
- Near-real-time dashboard: avoid full materialization; either query the base tables directly with supporting indexes so the planner can push filters down, or maintain an incrementally-updated summary table (updated on write, not recomputed wholesale) if the underlying computation is too heavy to run live on every page load.
When does a CTE pipeline graduate to a materialized view? Three independent signals, any one of which is usually enough on its own: (1) reuse -- the same CTE logic is being copy-pasted into a second, third, or fourth query or dashboard, which is a sign the definition should live in one place instead of many; (2) performance -- the CTE's underlying computation starts showing up as the dominant cost in an EXPLAIN plan across multiple callers, so the aggregate cost of recomputing it everywhere now exceeds the cost of maintaining a refreshed copy; (3) governance -- different query authors start writing slightly different filters around a copy-pasted CTE, so the "same" KPI silently drifts between dashboards. Any of these is the point to promote the logic into a materialized view (or persisted table) with one refresh schedule and one definition that every consumer reads.
Worked example
A KPI like "monthly active accounts" (distinct accounts with at least one qualifying event in the trailing 30 days) is a good stand-in: it is expensive on a large events table because it needs a distinct count over a rolling window, and it is exactly the kind of metric multiple dashboards want to show.
-- (a) one-off exploration: CTE, thrown away after this single query
WITH active_accounts AS (
SELECT DISTINCT account_id
FROM events
WHERE event_time >= CURRENT_DATE - INTERVAL '30 days'
)
SELECT COUNT(*) AS mau FROM active_accounts;
-- (b) repeatedly-used, refresh-tolerant: materialized view, indexed, refreshed nightly
CREATE MATERIALIZED VIEW mv_monthly_active_accounts AS
SELECT account_id, MAX(event_time) AS last_active_at
FROM events
WHERE event_time >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY account_id;
CREATE INDEX idx_mv_maa_account ON mv_monthly_active_accounts(account_id);
-- refreshed on a schedule, e.g. REFRESH MATERIALIZED VIEW mv_monthly_active_accounts;
-- (c) near-real-time: query live, relying on an index on events(account_id, event_time)
-- rather than pre-aggregating, so results are current to the second
SELECT COUNT(DISTINCT account_id) AS mau_live
FROM events
WHERE event_time >= NOW() - INTERVAL '30 days';
ML (machine learning) feature pipeline framing: this exact decision tree also applies when the "dashboard" is actually a model training job reading a feature. A feature explored once in a notebook is a CTE; a feature reused across many training runs (and needing point-in-time correctness, i.e. only using data available as of each label's timestamp) is exactly the "repeatedly-used expensive calculation" case, and belongs in a materialized feature table (or a feature store) that is refreshed on a known cadence, not recomputed inline in every training query. The freshness criterion becomes sharper here: a stale feature table used for training is often fine, but the same staleness at serving/inference time can silently create training-serving skew, so the acceptable staleness window has to be decided per use case, not assumed.
Spark SQL / Catalyst optimizer angle: the reuse math is different in Spark. Spark's Catalyst optimizer treats a WITH clause referenced multiple times by inlining and re-planning the underlying logical plan at each reference site by default, rather than computing it once and sharing the result the way a materialized view would. A CTE joined against three times in one Spark SQL query can trigger the same expensive computation three separate times unless you explicitly force sharing (persisting the intermediate DataFrame with .cache()/.persist(), or writing it out and reading it back). This makes the "graduate to materialization" decision arrive sooner in Spark than in a single-node warehouse: a CTE reused even twice within one query is worth checking for repeated work, not just a CTE reused across many separate queries.
Trade-offs & pitfalls
The common wrong turn is reaching for a materialized view purely because a query is slow, without checking whether the consumer can actually tolerate the staleness that comes with it: a materialized view refreshed hourly is the wrong answer for a dashboard that promises "as of right now." Conversely, leaving an expensive, frequently-reused CTE unmaterialized "for simplicity" quietly multiplies its cost by however many dashboards call it, since nothing about a CTE shares work across separate queries. Temp/staging tables sit in between and are easy to over- or under-use: they are the right tool inside a single multi-step job (build once, query several times, then discard), but reaching for one to serve a dashboard means re-inventing a materialized view's refresh logic by hand, usually worse. Always confirm the actual freshness requirement with the stakeholder before choosing: "near-real-time" and "updated every 15 minutes" are very different engineering problems that get conflated in casual requirements language.
Given a page_views table, write a query to find users who viewed page 'A' and then page 'B' within 10 minutes of each other, using LAG or LEAD to compare consecutive events per user. Then discuss how you'd generalize the same approach to a longer ordered chain, like a 3-step landing-page-to-purchase funnel.
Sample Answer
Direct answer: Order each user's page views by time, use LEAD to look at the next event's page and timestamp, and keep rows where the current page is 'A', the next page is 'B', and the time between them is within 10 minutes. Because LEAD only looks at the immediately following row per user, this only matches A directly followed by B, not A followed eventually by B with other pages in between. Generalizing to a longer chain (a 3-step funnel) means chaining multiple LEAD calls, one per step, each with its own offset.
Structured elaboration
WITH ordered AS (
SELECT user_id, page, viewed_at,
LEAD(page) OVER (PARTITION BY user_id ORDER BY viewed_at) AS next_page,
LEAD(viewed_at) OVER (PARTITION BY user_id ORDER BY viewed_at) AS next_viewed_at
FROM page_views
)
SELECT user_id, viewed_at AS a_time, next_viewed_at AS b_time
FROM ordered
WHERE page = 'A' AND next_page = 'B'
AND next_viewed_at <= viewed_at + INTERVAL '10 minutes';
Worked example (executed in DuckDB). User 1: A at 10:00, B at 10:05 (5-minute gap, qualifies). User 2: A at 11:00, B at 11:25 (25-minute gap, does not qualify).
user_id | a_time | b_time
1 | 10:00:00 | 10:05:00
Only user 1 appears in the result: user 2's A-then-B pair is correctly excluded because 25 minutes exceeds the 10-minute window, even though B genuinely followed A in their event stream.
Generalizing to a longer chain (a 3-step funnel). Two workable shapes:
- Stacked
LEADoffsets in one CTE (common table expression: a named, temporary result set defined withWITH ... AS (...)that the rest of the query can reference like a table).LEAD(page, 1)andLEAD(viewed_at, 1)give the next event,LEAD(page, 2)andLEAD(viewed_at, 2)give the one after that. Filteringpage = 'A' AND LEAD(page,1) = 'B' AND LEAD(page,2) = 'C'(plus a time bound between the first and last step) finds users whose next two events, in order, were exactly B then C. - Chained CTEs, one per step, each filtering down to users who completed the previous step, then joining forward to the next page within the window: a landing-page common table expression, then an add-to-cart one that self-joins to it on
user_idand a time bound, then a purchase one the same way. This is more verbose but scales cleanly to N steps without adding a newLEAD(page, k)term for every step, and it reads closer to how a funnel is usually described ("how many made it from step 2 to step 3").
-- Stacked-LEAD version of a 3-step A -> B -> C funnel within 30 minutes total
WITH ordered AS (
SELECT user_id, page, viewed_at,
LEAD(page,1) OVER (PARTITION BY user_id ORDER BY viewed_at) AS p2,
LEAD(viewed_at,1) OVER (PARTITION BY user_id ORDER BY viewed_at) AS t2,
LEAD(page,2) OVER (PARTITION BY user_id ORDER BY viewed_at) AS p3,
LEAD(viewed_at,2) OVER (PARTITION BY user_id ORDER BY viewed_at) AS t3
FROM page_views
)
SELECT user_id, viewed_at AS a_time, t2 AS b_time, t3 AS c_time
FROM ordered
WHERE page = 'A' AND p2 = 'B' AND p3 = 'C'
AND t3 <= viewed_at + INTERVAL '30 minutes';
Run against a 3-event chain for user 1 (A 10:00, B 10:05, C 10:12), this returns exactly that one row with a_time=10:00, b_time=10:05, c_time=10:12, confirming the offset chain correctly threads through all three steps in order.
Trade-offs & pitfalls
- Requiring the events to be immediately consecutive (via
LEAD(...,1),LEAD(...,2)) is a strict funnel definition: a stray click on an unrelated page between A and B breaks the match. If the real requirement is "A eventually followed by B, other pages allowed in between," you need a different construction: the first B-or-later event after each A, found via a window frame or a self-join with a MIN, not sequential LEAD offsets. - Stacked
LEAD(page, k)terms don't scale gracefully past a handful of steps; a 10-step funnel is more maintainable as chained CTEs or a recursive approach than ten hardcodedLEAD(page, k)columns. - Watch for a user who visits A multiple times in a row before B; this query matches every A immediately followed by B, so a user with A, A, B produces one qualifying pair (the second A to B), not necessarily the one you intended if you wanted "first A to first B" specifically.
A finance team wants monthly customer revenue reported against the customer segment that was valid when each order happened, not the segment the customer has today. Some dimension updates arrive late, and some orders are backfilled after the month closes. How would you structure the SQL transformation so the numbers are reproducible, auditable, and easy to reconcile?
Sample Answer
Approach
I would model the customer segment as a slowly changing dimension, meaning a history table with valid_from and valid_to timestamps. Then I would do an as-of join, which matches each order to the dimension row that was valid when the order happened, not the current row.
SELECT
DATE_TRUNC('month', o.order_ts) AS month,
d.segment,
SUM(o.revenue) AS revenue
FROM orders o
JOIN dim_customer_history d
ON o.customer_id = d.customer_id
AND o.order_ts >= d.valid_from
AND o.order_ts < d.valid_to
GROUP BY 1, 2;
Why this is auditable
- The join is driven by the order timestamp, so reclassifying a customer today does not rewrite history.
- I would keep immutable raw orders, the dimension history, and the monthly mart as separate layers.
- I would store the load batch or snapshot date so finance can reproduce the exact closing report.
Late data handling
If an order is backfilled after month close, I would rerun the affected month from raw facts, but only against the dimension history that was effective at the order time. That keeps the numbers consistent and explainable during reconciliation.
A hierarchy table (employees, categories, or similar) is getting queried with recursive CTEs constantly and it's starting to show up in slow-query logs at millions of rows. Compare recursive CTEs against alternative hierarchical data models (closure table, materialized path, nested sets) for this kind of read-heavy workload: write cost, read cost, and typical maintenance strategy for each, and say which you'd pick and why.
Sample Answer
Recursive CTEs (common table expressions, WITH blocks that reference themselves) walk a hierarchy by re-scanning the base table one level at a time, so cost grows with both the number of rows and the depth of the tree; at millions of rows that shows up as slow-query-log entries because every ancestor or descendant lookup effectively re-derives the whole path instead of reading it. The fix for a read-heavy workload is to precompute the hierarchy into a structure built for lookups: a closure table (every ancestor-descendant pair stored as its own row), a materialized path (the full lineage stored as a string or array on each row), or nested sets (a precomputed traversal order stored as two numbers per row). For most read-heavy reporting hierarchies with occasional structural changes, a closure table is the right default: it gives indexable, single-seek reads for both ancestor and descendant queries while keeping writes bounded to real structural events instead of touching the whole table.
Comparing the options
| Approach | Write cost | Read cost | Typical maintenance |
|---|---|---|---|
Recursive CTE over adjacency list (parent_id) | O(1): insert/update touches one row | O(depth) per query: each level is a fresh join back to the same table; degrades as the table and tree both grow | None; it's the raw representation, no extra structure to keep in sync |
Closure table (ancestor_id, descendant_id, depth) | Inserting a leaf is O(depth) new rows; moving a subtree is O(ancestors × descendants below it), the most expensive of the three on structural changes | O(1) indexed seek: WHERE ancestor_id = ? or WHERE descendant_id = ? returns the full ancestor or descendant set directly, no recursion | Usually populated by a trigger or an ETL (extract, transform, load) batch job on every structural change; needs periodic reconciliation if any write path bypasses it |
Materialized path (e.g. path = '1/4/17/') | Insert is O(1) (copy parent's path, append); moving a subtree means rewriting the path on every descendant | Descendant query is a prefix match (path LIKE '1/4/%'), indexable with the right index type; ancestor query means parsing the string | Path can drift from the adjacency list if both are kept; usually one becomes the source of truth and the other is regenerated from it |
Nested sets (lft, rgt) | Insert/move shifts lft/rgt on every node whose value is greater than the insertion point, which can lock a large fraction of the table | Subtree query is a single range scan (WHERE lft BETWEEN parent.lft AND parent.rgt), the fastest of the four, no join needed | Practical only for hierarchies that change rarely; frequent structural writes make this the most expensive option operationally |
Worked example
Take a 5-node org hierarchy: CEO (1) has VP Eng (2) and VP Sales (3) reporting to them; VP Eng has Eng Manager (4); Eng Manager has one Engineer (5). Computing nested-set bounds via a preorder traversal (verified by walking the tree programmatically) gives:
| node | lft | rgt |
|---|---|---|
| CEO (1) | 1 | 10 |
| VP Eng (2) | 2 | 7 |
| Eng Mgr (4) | 3 | 6 |
| Engineer (5) | 4 | 5 |
| VP Sales (3) | 8 | 9 |
"Everyone under VP Eng" is now WHERE lft BETWEEN 2 AND 7, a single range scan with no join. The equivalent closure table for the same 5 nodes has 12 rows (5 self-pairs at depth 0, plus every real ancestor-descendant pair: CEO has 4 descendants, VP Eng has 2, Eng Mgr has 1), each independently indexable by either ancestor or descendant, at the cost of storing more rows than there are nodes.
Which to pick, and when the answer changes
For a 10-million-row employee-reporting hierarchy with occasional re-orgs but heavy dashboard read traffic, the closure table wins: reorgs are infrequent events, not per-transaction writes, so the O(ancestors × descendants) move cost is paid rarely, while every dashboard query gets an indexed O(1) lookup instead of a recursive walk. Nested sets are the right call only for a genuinely near-static hierarchy (a product-catalog category tree that almost never restructures) where the single-range-scan subtree read matters more than write cost. Materialized path is a reasonable middle ground when the dominant query is "give me everyone under X" and the team is comfortable keeping a string in sync, but it's the weakest of the three at answering "who are this node's ancestors" without string parsing.
At the far end, hundreds of millions of edges (a large product catalog, a permissions graph, a social graph), even a closure table starts to strain a relational engine: the pair count can grow faster than the node count, and the storage and index-maintenance cost of every structural change scale with it. That's the point where the right question stops being "which SQL hierarchy model" and becomes "should this hierarchy live in a graph database" (Neo4j, Amazon Neptune, or similar), which represents adjacency as a first-class edge and doesn't need any of these workarounds. The trade there is real: you now maintain a second system, and you generally lose the ability to join the hierarchy directly against the rest of your relational warehouse without a data-sync layer.
Trade-offs and pitfalls
The recurring mistake is picking nested sets for a hierarchy that turns out to change more often than assumed: the write amplification on every insert/move is easy to underestimate until a re-org locks half the table. The second common mistake is maintaining a closure table or materialized path purely by application code instead of a trigger or a scheduled reconciliation job; any write path that bypasses that logic (a bulk import, a manual UPDATE) silently desyncs the precomputed structure from the adjacency list, and dashboards start returning wrong ancestor/descendant sets with no error to signal it.
Unlock Full Question Bank
Get access to all Advanced SQL: Window Functions, CTEs, and Subqueries interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.