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

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
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
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?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

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 →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer