wasAsked.

LINQ Query: How do you write a LINQ query to get the second highest salary from a table?

QBurst · Role not specified · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

The key detail is handling duplicate salaries: "second highest" usually means the second highest distinct salary. In-memory collection (LINQ to Objects): var secondHighest = employees .Select(e => e.Salary) .Distinct() .OrderByDescending(s => s) .Skip(1) .FirstOrDefault(); // 0 (or null for decimal?) if there is no second value Return the employees who earn it: var people = employees.Where(e => e.Salary == secondHighest).ToList(); With Entity Framework Core (translated to SQL): decimal? second = await db.Employees .Select(e => (decimal?)e.Salary) .Distinct() .OrderByDescending(s => s) .Skip(1) .FirstOrDefaultAsync(ct); Casting to decimal? makes "no second salary" come back as null instead of 0, which is clearer. EF generates SQL similar to: SELECT DISTINCT Salary FROM Employees ORDER BY Salary DESC OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY Alternative without sorting everything: var max = employees.Max(e => e.Salary); var second = employees.Where(e => e.Salary < max).Max(e => (decimal?)e.Salary); This makes two passes, O(n), and handles duplicates naturally — useful to mention for large in-memory lists. Nth highest generalisation: static decimal? NthHighest(IEnumerable<decimal> salaries, int n) => salaries.Distinct().OrderByDescending(s => s).Skip(n - 1).Cast<decimal?>().FirstOrDefault(); Per-department second highest (a common follow-up): var perDept = employees .GroupBy(e => e.DepartmentId) .Select(g => new { Department = g.Key, Second = g.Select(e => e.Salary).Distinct().OrderByDescending(s => s).Skip(1).Cast<decimal?>().FirstOrDefault() }); Edge cases to mention: empty list, only one distinct salary, all salaries equal, and null salaries in the database. The equivalent SQL using DENSE_RANK() OVER (ORDER BY Salary DESC) = 2 is also good to know.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics