🍪

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/SQL/Find each student's previous year's scores using the LAG function.

Find each student's previous year's scores using the LAG function.

SQLmedium2 min read

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

To find each student's previous year's score, use the LAG window function with PARTITION BY student id and ORDER BY year . This calculates the score from the preceding row within each student's…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
487
questions in SQL
Difficulty Split
130E|271M|86H
in this category
Total Bank
1,863
across 7 categories
Part of the SQL Query Optimization & Indexing Interview Preparation Hub
Explore SQL Query Optimization & Indexing Hub→
Reported in Interview Loops AtClick to view company-specific questions
🏢 Deolite Interview Hub→
Key Concepts Tested
partition

Why This Question Matters

This medium-level SQL question appears frequently in data engineering interviews at companies like Deolite. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (partition) 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
340 wordsIncludes code

To find each student's previous year's score, use the LAG window function with PARTITION BY student_id and ORDER BY year. This calculates the score from the preceding row within each student's ordered set of records.

Mechanics and "Why"

The LAG function retrieves a value from a row at a given physical offset before the current row within its partition. Its full syntax is LAG(expression, offset, default).
* expression: The column whose value you want to retrieve (e.g., score).
* offset: An integer indicating how many rows back to look. The default is 1. To find the score from two years back, you would use LAG(score, 2).
* default: The value to return if the offset goes beyond the start of the partition. The default is NULL. This means the first record for each student will have a NULL prev_year_score. You can use COALESCE(LAG(score), 0) to replace NULL with 0, for example.

The OVER clause is crucial for defining the window:
PARTITION BY student_id: This divides the dataset into independent groups, ensuring the LAG calculation only considers scores for the same* student. Without this, LAG would look at the previous row in the entire dataset, potentially a different student.
* ORDER BY year: This defines the logical order within each student's partition, so "previous year" is correctly identified by the chronological sequence of years.

Example and Trade-offs

SELECT
    student_id,
    year,
    score,
    LAG(score, 1, 0) OVER (PARTITION BY student_id ORDER BY year) AS prev_year_score
FROM
    student_scores;

Window functions, especially those with PARTITION BY on large datasets, can be computationally intensive. In distributed systems like Spark or Snowflake, they often require data to be grouped and sorted across nodes (known as a data shuffle), which can significantly impact query performance. Optimizing the PARTITION BY key and ensuring efficient data distribution are key considerations for performance.

In the interview, also mention…

Discuss related window functions like LEAD (for subsequent values), ROW_NUMBER, RANK, or NTH_VALUE to demonstrate a broader understanding of analytical functions and their applications in data engineering.

⚡
Pro Tip

Red Flag: Missing ORDER BY in LAG—undefined order. Pro-Move: 'We used LAG(score, 1, 0) to default first year to 0 for YoY growth calculation.'

Want all answers as a PDF for offline study?
7-Volume Data Engineering Answer Vault (750+ Answers) or Complete Master Vault →
Instant PDF

Related SQL Questions

mediumWrite an SQL query to find the second-highest salary from an employee table.FreemediumDemonstrate the difference between DENSE_RANK() and RANK()FreemediumDiscuss differences between ROW_NUMBER(), RANK(), and DENSE_RANK(), and provide examples from your projects.FreemediumExplain the differences between Data Warehouse, Data Lake, and Delta LakeFreemediumExplain the differences between Repartition and Coalesce. When would you use each?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 SQL 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 SQL 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