🍪

Essential cookies keep authentication working. With your permission, we also use analytics to improve the product. Privacy Policy

DDataEngPrep.tech
Home
PricingBlog
Sign InStart Free→
Home/Questions/General/Other/Calculate a 7-day moving average of orders for each city in the Swiggy database.

Calculate a 7-day moving average of orders for each city in the Swiggy database.

General/Othermedium2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-08-08

To calculate a 7 day moving average of orders for each city, use a SQL window function. This involves partitioning the data by city id , ordering it by order date , and defining a window that includes…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
243
questions in General/Other
Difficulty Split
151E|43M|49H
in this category
Total Bank
1,863
across 7 categories
Part of the Apache Spark Interview Preparation Hub
Explore Apache Spark Hub→
Reported in Interview Loops AtClick to view company-specific questions
🏢 Swiggy Interview Hub→
Interview Pro Tip

Pro-Move: 'We partition by city_id and use ROWS—city-level aggregation is dense; RANGE adds overhead.' Red Flag: Forgetting PARTITION BY city_id—mixing cities in one average.

Key Concepts Tested
partitionsparksqlwindow

Why This Question Matters

This medium-level General/Other question appears frequently in data engineering interviews at companies like Swiggy. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (partition, spark, sql) will help you answer variations of this question confidently.

How to Approach This

Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
315 wordsIncludes code

To calculate a 7-day moving average of orders for each city, use a SQL window function. This involves partitioning the data by city_id, ordering it by order_date, and defining a window that includes the current row and the six preceding rows.

Mechanics and Why
A moving average helps smooth out daily fluctuations, revealing underlying trends. The PARTITION BY city_id clause is crucial as it ensures the moving average is calculated independently for each city, preventing data from one city from influencing another. The ORDER BY order_date clause establishes the chronological sequence necessary for a time-series calculation. Finally, ROWS BETWEEN 6 PRECEDING AND CURRENT ROW defines the 7-day window, encompassing the current day's order count and the six previous days' counts to compute the average.

Example and Considerations
This pattern is fundamental for time-series analysis. For large datasets, window functions can be computationally intensive. In distributed systems like Spark, PARTITION BY often triggers a shuffle operation, which can be a significant performance bottleneck. Therefore, it's a best practice to materialize such calculations, perhaps in a dbt model, to optimize downstream queries and dashboard performance.

SELECT
    city_id,
    order_date,
    order_count,
    AVG(order_count) OVER (
        PARTITION BY city_id
        ORDER BY order_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS ma_7d
FROM
    daily_orders;

A key consideration is how data gaps (days with no orders) are handled. The ROWS clause operates on rows, not calendar days. If a city has missing dates, the "7-day" average will technically be an average over the last 7 available order days, not necessarily 7 calendar days.

In the interview, also mention:
Discuss how to handle true calendar-day averages by LEFT JOINing with a complete calendar table and imputing zero order counts for missing dates before applying the window function. This demonstrates a robust understanding of real-world data challenges. You could also briefly touch on the difference between ROWS and RANGE in window definitions.

⚡
Pro Tip

Pro-Move: 'We partition by city_id and use ROWS—city-level aggregation is dense; RANGE adds overhead.' Red Flag: Forgetting PARTITION BY city_id—mixing cities in one average.

Get The Complete 2026 FDE, AI & DE Master Vault (All 9 PDF Volumes)
FDE Interview Guide, FastMCP & RAG Playbook, and 7-Volume DE Vault with 1,863+ answers →
⭐ Save 45%

Related General/Other Questions

hardHave you worked on Data Warehousing projects?FreemediumHow would you read data from a web API? What steps would you follow after reading the data?FreehardRetrieve the most recent sale_timestamp for each product (Latest Transaction).FreehardWhat is the difference between OLTP and OLAP?FreemediumWhat is the difference between SQL and NoSQL databases?Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked General/Other interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore General/Other questions →
Topic Hubs
All Topic Hubs (12 Competencies) →All 1,863+ QuestionsSQL Interview QuestionsApache Spark QuestionsPySpark QuestionsPython for Data EngineersSystem Design InterviewData Modeling & WarehousingStreaming (Kafka/Flink)SQL Window FunctionsETL Pipeline Design
Company Hubs
All Company Hubs (100+ Companies) →AmazonGoogleMetaDatabricksSnowflakeNetflixUberStripeMicrosoftAppleGoldman SachsAWS Engineering
Academies & Guides
All Guides & ArticlesData Engineering AcademyForward Deployed AI AcademyClient Simulation StudioApache Airflow QuestionsAzure Data EngineerBehavioral & STAR MethodCloud & Distributed Tools
AI Tools & Products
Answer Analyzer (Free)AI Mock InterviewsSQL PlaygroundATS Resume AnalyzerOffline PDF Answer VaultsMembership & Pricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer