Quick answer: What advanced SQL do senior data interviews test, and how do I prepare?
- Core patterns — top N per group, latest record per key, running totals, period-over-period, sessionisation.
- Hard-mode patterns — gaps and islands, cohort retention, funnels with time windows, deduplication.
- Engineering SQL — MERGE/upserts, incremental loads, partitioning, transactions.
- Performance — indexes, query plans, avoiding fan-out and full scans.
- 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.

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
| Format | Who uses it | What it checks |
|---|---|---|
| Timed assessment (4–6 problems) | Product companies, GCCs | Pattern recognition under time |
| Live coding on event data | Product analytics, analytics engineering | Reasoning, edge cases, communication |
| Debug-this-query | Increasingly common | Spotting fan-out, NULL and window-frame errors |
| Design discussion | Data engineering | Incremental logic, MERGE, partitioning, cost |
| Plan reading | Senior and platform roles | Indexes, scans, join strategies |
Table: How advanced SQL is tested in senior data hiring (editorial summary)
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
| Period | What happened | What senior SQL meant |
|---|---|---|
| 2005–2012 | On-premise databases | Stored procedures, cursors, tuning by DBAs |
| 2013–2018 | Window functions widely supported; analytics grows | Analytical SQL for analysts |
| 2019–2022 | Cloud warehouses, dbt | Modelled, tested, incremental SQL |
| 2023–2024 | Cost focus in warehouses | Efficient SQL, partition pruning |
| 2025–2027 | AI drafts SQL | Verification, debugging and design |
Table: How advanced SQL expectations have changed (editorial summary)
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?
- PARTITION BY
- GROUP BY
- SPLIT BY
- WINDOW ON
Show the answer
A. PARTITION BY — PARTITION BY splits rows for window functions.
- 01Advanced querying
- 02Correctness and performance
- 03Analytical SQL patterns
- 04Data modelling and engineering SQL
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

- 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

- Week 1: Windows — ROW_NUMBER, RANK, LAG, frames. Fifteen problems.
- Week 2: Analytical patterns — Cohorts, funnels, sessionisation, gaps and islands.
- Week 3: Data quality patterns — Deduplication, late data, NULL and date edge cases.
- Week 4: Engineering SQL — MERGE, incremental logic, SCD type 2.
- Week 5: Performance — EXPLAIN, indexes, partitions; take the Advanced SQL Assessment.
- 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
- 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.
- 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.
- 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.
- Incremental model — Write a MERGE that loads only new or changed rows, run it twice and prove the result is identical.
- 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:
| Role | Typical pay (India) | Advanced SQL used for |
|---|---|---|
| Senior data analyst | ₹12.9–14.2 lakh | Complex analysis on event and transactional data |
| Analytics engineer | ₹10.6–11.9 lakh | Tested, incremental warehouse models |
| Data engineer | ₹11.5–12.7 lakh | Pipelines, merges and performance |
| Product analyst | ₹11.5–12.8 lakh | Funnels, cohorts and experiment analysis |
| Data scientist | ₹15.2–16.8 lakh | Feature tables and analysis at scale |

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
- AmbitionBox — Senior Data Analyst salaries in India (updated 25 Oct 2026)
- AmbitionBox — Data Engineer salaries in India (updated 24 Oct 2026)
- PostgreSQL Documentation — Window Functions (tutorial)
- PostgreSQL Documentation — Using EXPLAIN
- PostgreSQL Documentation — MERGE
- Google Cloud — Introduction to partitioned tables (BigQuery)
- dbt Labs — Incremental models (documentation)
- Checked October 28, 2026. Figures that change — fees, salaries, prices — are reviewed every six months; if something is out of date, tell us.
Certifications to take next
- 14 AI skills for data analysts — copy-paste prompts for this job, one tap into ChatGPT or Claude
- Advanced SQL Assessment — the free 20-minute test on windows, CTEs, performance and modelling SQL
- SQL for data analyst jobs — the fundamentals every advanced pattern builds on
- How to get a data engineer job — where engineering-grade SQL is tested hardest
- Free skill test · 10 minSQL Fundamentals CertificationTests core SQL — SELECT, WHERE, ORDER BY, aggregates and GROUP BY, HAVING, joins, NULL handling and basic data modification.
- Free skill test · 15 minTableau Data Visualization CertificationTests Tableau — dimensions and measures, discrete vs continuous fields, calculated fields, LOD expressions, filters and their order, dashboards and performance.
- Free skill test · 15 minPower BI Analyst AssessmentTests Power BI — Power Query, star schema data models, relationships, DAX measures and CALCULATE, visuals, row-level security and publishing in the Power BI service.
- Free skill test · 15 minData Engineering Fundamentals CertificationTests data engineering basics — batch and streaming pipelines, ETL/ELT, data modelling, orchestration, file formats, data quality tests and cloud warehouses.
- Free skill test · 15 minAdvanced Excel and Formulas CertificationTests advanced Excel — XLOOKUP and INDEX/MATCH, dynamic arrays such as FILTER and UNIQUE, LET and LAMBDA, error handling, Power Query and data modelling.
- Free skill test · 20 minAI and Machine Learning Model Evaluation CertificationTests how to evaluate ML models — precision, recall, F1, ROC-AUC, calibration, cross-validation, regression metrics, fairness slices and production monitoring.
Career guides for related roles
- Career guidesSQL for data analyst jobs in 2027: what employers test, the questions they ask and how to prove you're readySQL for data analyst jobs in 2027: which roles need it, how employers test it, real interview questions with answers, the traps that fail candidates and a plan.
- Career guidesAdvanced Excel test for jobs in 2027: XLOOKUP, dynamic arrays, Power Query and what analyst interviews really checkHow to pass an advanced Excel test for analyst jobs in 2027: XLOOKUP, dynamic arrays, LET, Power Query, data models, real test tasks with answers and a plan.
- Career guidesHow to get a product analyst job in 2027: the metrics, SQL and experiment skills that get you hiredHow to get a product analyst job in 2027: what hiring managers test (SQL, metrics, experiments), the interview loop, India and global pay, and a 12-week plan.
- Career guidesHow to get a data engineer job in 2027: pipelines, modelling and the system-design round that decides itHow to get a data engineer job in 2027: the SQL, Python and pipeline-design skills employers test, the interview loop, India and global pay, and a 12-week plan.
- Career guidesGoogle Sheets skills for jobs in 2027: QUERY, IMPORTRANGE, shared trackers and what startups actually testGoogle Sheets skills for jobs in 2027: which roles use Sheets, how startups test it, QUERY, ARRAYFORMULA and IMPORTRANGE questions with answers, and a plan.
- Career guidesML model evaluation interview questions in 2027: metrics, validation and the judgement that separates senior data scientistsML model evaluation interview questions for data science jobs in 2027: precision, recall, ROC-AUC, calibration, cross-validation, fairness, monitoring.
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.
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.






