Career guides · Skill guide

Advanced SQL for
senior data interviews in 2027

Senior data interviews in 2027 test advanced SQL as problem-solving under realistic messiness: window functions (ROW_NUMBER, LAG, running totals), CTEs, deduplication, date and NULL logic, cohort and funnel queries, gaps-and-islands, MERGE/upserts and reading query plans. Practise the recurring patterns on event-style tables, explain edge cases aloud, and prove it with a verified assessment; the skill gates senior analyst roles paying about ₹12.9–14.2 lakh in India.

By , FounderUpdated 9 min read

Share

Quick answer: What advanced SQL do senior data interviews test, and how do I prepare?

  1. Core patterns — top N per group, latest record per key, running totals, period-over-period, sessionisation.
  2. Hard-mode patterns — gaps and islands, cohort retention, funnels with time windows, deduplication.
  3. Engineering SQL — MERGE/upserts, incremental loads, partitioning, transactions.
  4. Performance — indexes, query plans, avoiding fan-out and full scans.
  5. Where it pays — senior data analysts in India typically ₹12.9–14.2 lakh (AmbitionBox, Oct 2026).

Key takeaways

  • Advanced SQL interviews reuse a small set of patterns; recognising them is half the battle.
  • Window functions appear in nearly every senior data SQL round.
  • Explaining grain, ties and NULL behaviour scores as much as getting the output right.
  • Performance questions test whether you understand what the database actually does.
  • AI drafts queries quickly, so senior interviews focus on correctness and design.

Picture a senior analyst interview at a fintech. The question looks simple: "For each user, find their longest streak of consecutive days with a transaction." The candidate who has only practised textbook joins starts writing self-joins and runs out of time. The one who recognises a gaps-and-islands problem writes four lines — a ROW_NUMBER subtracted from the date, a GROUP BY, a MAX — and spends the remaining time discussing duplicate transactions and time zones. Advanced SQL interviews are mostly pattern recognition plus careful reasoning, and both can be practised.

What advanced SQL do senior data interviews test, and how do I prepare? At a glance: Core patterns; Hard-mode patterns; Engineering SQL; Performance; Where it pays.
At a glance: What advanced SQL do senior data interviews test, and how do I prepare?

Who needs advanced SQL, and what it unlocks

Advanced SQL is the gate to senior data analyst, analytics engineer, BI developer and data engineer roles — and to product analytics jobs built on event data. These roles pay more because the SQL sits closer to production data and decisions.

On AmbitionBox in October 2026, senior data analysts in India typically earned ₹12.9–14.2 lakh and data engineers ₹11.5–12.7 lakh, compared with ₹6.5–7.2 lakh for data analysts overall.12 The jump from analyst to senior analyst is, in most loops, a jump in SQL depth.

Typical senior data analyst pay in India (AmbitionBox, Oct 2026)
₹12.9–14.2 lakh
Growth in senior data analyst pay over two years (AmbitionBox)
17%
Typical data engineer pay in India
₹11.5–12.7 lakh
Recurring patterns that cover most advanced SQL rounds
~12

How advanced SQL is tested

FormatWho uses itWhat it checks
Timed assessment (4–6 problems)Product companies, GCCsPattern recognition under time
Live coding on event dataProduct analytics, analytics engineeringReasoning, edge cases, communication
Debug-this-queryIncreasingly commonSpotting fan-out, NULL and window-frame errors
Design discussionData engineeringIncremental logic, MERGE, partitioning, cost
Plan readingSenior and platform rolesIndexes, scans, join strategies

Table: How advanced SQL is tested in senior data hiring (editorial summary)

The patterns that cover most advanced rounds

The patterns that cover most advanced rounds: Top N per group; Latest record per key; Period-over-period; Running totals and moving averages; Gaps and islands; Sessionisation; Cohort retention; Funnels with windows.
The patterns that cover most advanced rounds

Top N per group

ROW_NUMBER/RANK/DENSE_RANK partitioned by group — and choosing how ties behave.

Latest record per key

ROW_NUMBER ordered by updated time descending, keep 1 — the backbone of deduplication.

Period-over-period

LAG/LEAD over months or weeks for growth, churn and change detection.

Running totals and moving averages

Window aggregates with explicit frames (ROWS BETWEEN 6 PRECEDING AND CURRENT ROW).

Gaps and islands

Streaks and consecutive runs via date minus ROW_NUMBER.

Sessionisation

LAG on event time, flag gaps over 30 minutes, cumulative sum of flags to number sessions.

Cohort retention

First-activity cohort per user, joined to later activity by period offset.

Funnels with windows

Ordered steps completed within a time window, per user.

PostgreSQL's documentation explains window functions and frames precisely;3 the same concepts apply in BigQuery, Snowflake and SQL Server with small syntax differences.

Engineering SQL: what data roles add

Analytics engineering and data engineering interviews add SQL that changes data, not just reads it:

  • MERGE / upserts — insert new rows and update changed ones in one statement.5
  • Incremental models — process only new or changed data, with a safe lookback for late arrivals; dbt's incremental models are the common pattern.7
  • Slowly changing dimensions — closing old rows and inserting new versions.
  • Partitioning and clustering — so queries scan less data; BigQuery's partitioned tables are a typical example.6
  • Transactions and locking — why two jobs updating the same table can collide.

Performance: what interviewers expect you to know

Performance questions test whether you understand what the database does. Know how to read a basic plan with EXPLAIN,4 why a function on an indexed column can prevent index use, how filtering early reduces work, why SELECT * on a wide warehouse table costs money, and how join order and fan-out explode row counts.

Advanced SQL interview questions, with how to answer them

"Longest streak of consecutive active days per user."

Deduplicate to one row per user-day, compute date minus ROW_NUMBER() OVER (PARTITION BY user ORDER BY day) as an island key, group by user and key, take the MAX length. Mention time zones and duplicate events.

"Day-30 retention by signup cohort."

CTE for each user's signup date, CTE for activity days, join on activity date = signup + 30 (or within a window, per definition), aggregate by cohort week. State the definition first.

"Deduplicate a table keeping the latest version of each record."

ROW_NUMBER() OVER (PARTITION BY id ORDER BY updated_at DESC, ingested_at DESC) and keep 1. Discuss tie-breakers.

"Seven-day moving average of revenue."

Aggregate to one row per day (filling missing days with a calendar table), then AVG() OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW).

"Why does this query return more revenue than finance?"

Look for join fan-out (summing at the wrong grain), duplicate events and missing filters for refunds or test orders.

"Write an upsert for a daily customer snapshot."

MERGE INTO target USING staging ON key — WHEN MATCHED AND values differ THEN UPDATE, WHEN NOT MATCHED THEN INSERT. Mention idempotency and deleted records.

"This query got slow after data doubled. What do you check?"

The plan: full scans, missing partition filters, non-sargable predicates, exploding joins and sort or spill steps. Then fix the biggest cost first.

"RANK vs DENSE_RANK vs ROW_NUMBER?"

ROW_NUMBER gives unique numbers; RANK leaves gaps after ties; DENSE_RANK doesn't. Choose by how ties should be treated.

How advanced SQL expectations have changed

PeriodWhat happenedWhat senior SQL meant
2005–2012On-premise databasesStored procedures, cursors, tuning by DBAs
2013–2018Window functions widely supported; analytics growsAnalytical SQL for analysts
2019–2022Cloud warehouses, dbtModelled, tested, incremental SQL
2023–2024Cost focus in warehousesEfficient SQL, partition pruning
2025–2027AI drafts SQLVerification, debugging and design

Table: How advanced SQL expectations have changed (editorial summary)

Readiness check · SOA-ASQL

Could you pass the Advanced SQL Assessment today?

Hiring managers test judgement with scenarios like this one. Answer it before you open the explanation — the test has 20 of them, 20 minutes, 70% to pass.

Which clause defines a window's partition?

  1. PARTITION BY
  2. GROUP BY
  3. SPLIT BY
  4. WINDOW ON
Show the answer

A. PARTITION BY — PARTITION BY splits rows for window functions.

  1. 01Advanced querying
  2. 02Correctness and performance
  3. 03Analytical SQL patterns
  4. 04Data modelling and engineering SQL
Difficulty: Advanced

Free, no sign-up. Pass and you become a Advanced SQL, with a credential ID employers can verify. Every answer is explained either way.

Prove it

Checklist: Prove it — A verified advanced SQL score; Three pattern write-ups; One incremental model; A performance before/after.
Prove it
  • A verified advanced SQL score — timed, with explanations reviewed.
  • Three pattern write-ups — gaps and islands, cohort retention and a funnel, on public data.
  • One incremental model — with a test proving it's idempotent.
  • A performance before/after — a query you made faster and why.

A six-week plan for advanced SQL

Diagram of 6 steps for a six-week plan for advanced sql: 1. Week 1: Windows; 2. Week 2: Analytical patterns; 3. Week 3: Data quality patterns; 4. Week 4: Engineering SQL; 5. Week 5: Performance; 6. Week 6: Timed practice.
A six-week plan for advanced SQL
  1. Week 1: Windows — ROW_NUMBER, RANK, LAG, frames. Fifteen problems.
  2. Week 2: Analytical patterns — Cohorts, funnels, sessionisation, gaps and islands.
  3. Week 3: Data quality patterns — Deduplication, late data, NULL and date edge cases.
  4. Week 4: Engineering SQL — MERGE, incremental logic, SCD type 2.
  5. Week 5: Performance — EXPLAIN, indexes, partitions; take the Advanced SQL Assessment.
  6. Week 6: Timed practice — Four-problem sets under time, explaining aloud.

Pair it with the Data Engineering Fundamentals test for engineering roles or the Product Analytics certification for product roles; our product analyst guide shows how these patterns appear in that loop.

Worked example: longest login streak

The question: "For each user, find their longest run of consecutive active days."

WITH days AS (
  SELECT DISTINCT user_id, CAST(event_time AT TIME ZONE 'Asia/Kolkata' AS DATE) AS d
  FROM events
),
grouped AS (
  SELECT user_id, d,
         d - CAST(ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY d) AS INT) AS island
  FROM days
)
SELECT user_id, MAX(streak) AS longest_streak
FROM (SELECT user_id, island, COUNT(*) AS streak FROM grouped GROUP BY user_id, island) s
GROUP BY user_id;

The DISTINCT removes duplicate events on the same day, the time-zone conversion decides which day an event belongs to, and subtracting the row number from the date gives consecutive days the same "island" value. Mention that the syntax for date arithmetic differs by database, and you've covered the edge cases interviewers probe.

Practice tasks that build advanced SQL

  1. Build an events table — Generate or download app event data (Google's public GA4 sample e-commerce dataset in BigQuery works well) and keep one table of user, event, timestamp and properties.
  2. Five patterns on it — Write sessionisation, day-7 retention by cohort, a three-step funnel within 24 hours, top three products per category and a seven-day moving average.
  3. Gaps and islands — Find each user's longest streak of active days; then break your own query with duplicate events and time zones and fix it.
  4. Incremental model — Write a MERGE that loads only new or changed rows, run it twice and prove the result is identical.
  5. Plan reading — Take a slow query, run EXPLAIN, change one thing (a filter, an index or partition pruning) and record the before and after.

Where advanced SQL takes your career

Advanced SQL is the most common gate between junior and senior data roles. Typical pay on AmbitionBox in October 2026:

RoleTypical pay (India)Advanced SQL used for
Senior data analyst₹12.9–14.2 lakhComplex analysis on event and transactional data
Analytics engineer₹10.6–11.9 lakhTested, incremental warehouse models
Data engineer₹11.5–12.7 lakhPipelines, merges and performance
Product analyst₹11.5–12.8 lakhFunnels, cohorts and experiment analysis
Data scientist₹15.2–16.8 lakhFeature tables and analysis at scale
Bar chart: Where advanced SQL takes your career — Senior data analyst: ₹12.9–14.2 lakh; Analytics engineer: ₹10.6–11.9 lakh; Data engineer: ₹11.5–12.7 lakh; Product analyst: ₹11.5–12.8 lakh; Data scientist: ₹15.2–16.8 lakh.
Where advanced SQL takes your career

Table: Roles that test advanced SQL and their typical pay in India (AmbitionBox, October 2026; indicative)

Mistakes that cost senior SQL rounds

  • Losing the grain halfway through a multi-CTE query.
  • Default window frames producing wrong running totals with duplicate dates.
  • Ignoring ties in top-N problems.
  • Fixing fan-out with DISTINCT instead of aggregating at the right level.
  • Optimising blindly without reading the plan.

How we know

Pay figures come from AmbitionBox's senior data analyst and data engineer pages (read October 2026). SQL references are PostgreSQL's documentation (window functions, EXPLAIN, MERGE), Google Cloud's BigQuery documentation and dbt's documentation. Test formats, the pattern list and the history table are editorial summaries. Science of Apps publishes the free assessment linked here. Last reviewed October 2026.

Key terms, defined

  • Window function — a function computed over a set of related rows while keeping each row.
  • Frame — the subset of rows a window function uses, such as the previous seven rows.
  • CTE — a named subquery defined with WITH, which can be recursive.
  • Gaps and islands — the problem of finding consecutive runs in ordered data.
  • Upsert / MERGE — inserting new rows and updating existing ones in one operation.
  • Query plan — the database's step-by-step strategy for running a query.
  • Partition pruning — skipping partitions that can't contain matching rows.

Frequently asked questions

What counts as advanced SQL?

Beyond SELECT, joins and GROUP BY: window functions, CTEs (including recursive ones), complex joins and deduplication, date and time logic, analytical patterns such as cohorts, funnels and gaps-and-islands, MERGE and upserts, transactions, indexing and reading query plans.

Which window functions are asked most in interviews?

ROW_NUMBER, RANK and DENSE_RANK for top-N and deduplication; LAG and LEAD for period-over-period changes and sessionisation; SUM and AVG with frames for running totals and moving averages; and FIRST_VALUE or LAST_VALUE for the first or latest value in a group.

What is the gaps-and-islands problem?

It's finding runs of consecutive values — for example, streaks of consecutive login days. A common solution subtracts a ROW_NUMBER from the date so consecutive dates share the same group key, then groups by that key to get each island's start, end and length.

How is advanced SQL tested for analytics engineers?

Expect window-function problems on event data, incremental model logic (only process new or changed rows), MERGE/upsert patterns, slowly changing dimensions, and questions about testing models, query cost and performance in a cloud warehouse.

How do I prepare for advanced SQL interviews?

Learn the dozen recurring patterns, practise each on realistic schemas until you can write them without notes, time yourself, and practise explaining edge cases aloud. Reading your database's documentation on window functions, EXPLAIN and MERGE is worth more than random puzzle sites.

Do I need to know query optimisation for a data analyst role?

For senior analyst and analytics engineering roles, yes, at a practical level: why a query is slow, how filters and joins affect scans, what indexes and partitions do and how to read a basic query plan. Entry-level analyst roles rarely go deep.

Sources

  1. AmbitionBox — Senior Data Analyst salaries in India (updated 25 Oct 2026)
  2. AmbitionBox — Data Engineer salaries in India (updated 24 Oct 2026)
  3. PostgreSQL Documentation — Window Functions (tutorial)
  4. PostgreSQL Documentation — Using EXPLAIN
  5. PostgreSQL Documentation — MERGE
  6. Google Cloud — Introduction to partitioned tables (BigQuery)
  7. dbt Labs — Incremental models (documentation)
  8. Checked October 28, 2026. Figures that change — fees, salaries, prices — are reviewed every six months; if something is out of date, tell us.
Pass it on

Know someone who'd enjoy this?

Send it to them — one tap, no sign-up. Good ideas travel best between friends.

Keep exploring

Certifications to take next

Keep exploring

Career guides for related roles

Join free

Get the ideas, not the noise.

Sign up with Google and we’ll send you short UX psychology tips by email — why people tap, stall and leave, and what to do about it. Unsubscribe anytime. Prefer something to keep? Get the free Laws of UX guide as a PDF.

Get the free Laws of UX PDFFree · no spam · unsubscribe anytime
Prove you're ready

You've read the playbook. Now prove it.

Take the free Advanced SQL Assessment and earn Advanced SQL (SOA-ASQL). Free, test-based certifications graded on our server. Pass and you get a founder-signed certificate with a credential ID and QR code employers can verify.

Free · SOA-ASQL

Become a Advanced SQL.

Tests advanced SQL — window functions, CTEs, subqueries, complex joins, deduplication, date logic, query performance and indexing. Graded on our server, with a founder-signed certificate, a credential ID and a QR code anyone can verify.

  • Credential ID
  • QR verification
  • LinkedIn-ready
Free PDF · 74 pages · 2 editions

The Laws of UX, in one field guide

60 research-backed principles in 6 categories — what each one means, why it works on the human brain and how to use it on your own screens. Written by Sushant Singh, founder of Science of Apps, who has scaled consumer apps to lacs of users and spent 10+ years leading product across startups and digital businesses in the US, EU & India.

Pick your edition
Free. No card, no paywall — just your email.
Free PDF · 74 pages

Get Laws of UX by email

Choose your edition

You’ll also get occasional UX psychology tips. Unsubscribe anytime. Privacy policy

Free PDF · 90 pages · 2 editions

100+ Subscription Paywalls, decoded

110 real paywalls from top apps, taken apart, rated out of 5 and decoded with the Laws of UX — plus the frameworks, copy and checklists to ship your own. By Sushant Singh, founder of Science of Apps.

  • 110 paywalls rated
  • 34 Laws of UX
  • 12 frameworks

Which paywall scored 4.8 out of 5, and which scored 2.6? It’s all inside.

Pick your edition
Free. No card, no paywall — just your email.
Free PDF · 90 pages

Get 100+ Paywalls, Decoded by email

Choose your edition

You’ll also get occasional UX psychology tips. Unsubscribe anytime. Privacy policy