First clarify whether “second highest” means the second distinct salary or simply the second row after sorting. Interviewers usually mean the second distinct salary, so duplicate top salaries should count once.
```csharp
decimal? secondHighest = employees
.Select(employee => employee.Salary)
.Distinct()
.OrderByDescending(salary => salary)
.Skip(1)
.Cast<decimal?>()
.FirstOrDefault();
```
For EF Core, keep the query as `IQueryable` so filtering, distinct, ordering, and limiting are translated to SQL:
```csharp
decimal? secondHighest = await db.Employees
.Select(employee => employee.Salary)
.Distinct()
.OrderByDescending(salary => salary)
.Skip(1)
.Select(salary => (decimal?)salary)
.FirstOrDefaultAsync(ct);
```
The nullable result represents fewer than two distinct salaries. To return every employee earning that amount, compute the value first and then issue a second filtered query, or use an appropriate window-function query where supported.
Krishna Yadav · · 0 likes
"Second highest salary" usually means the second highest distinct value, so duplicates of the top salary must be removed.
LINQ (method syntax):
decimal? secondHighest = employees
.Select(e => e.Salary)
.Distinct()
.OrderByDescending(s => s)
.Skip(1)
.Select(s => (decimal?)s)
.FirstOrDefault(); // null if there is no second distinct salary
Query syntax:
var secondHighest2 = (from salary in employees.Select(e => e.Salary).Distinct()
orderby salary descending
select (decimal?)salary).Skip(1).FirstOrDefault();
Employees who earn the second highest salary:
var topEarners = employees.Where(e => e.Salary == secondHighest).ToList();
Alternative using Max (single pass after max, no full sort):
var max = employees.Max(e => e.Salary);
decimal? second = employees.Where(e => e.Salary < max).Select(e => (decimal?)e.Salary).Max();
Using EF Core (translated to SQL OFFSET/FETCH):
var second3 = await db.Employees
.Select(e => (decimal?)e.Salary)
.Distinct()
.OrderByDescending(s => s)
.Skip(1)
.FirstOrDefaultAsync(ct);
Second highest per department:
var byDept = employees
.GroupBy(e => e.Department)
.Select(g => new
{
Department = g.Key,
SecondHighest = g.Select(e => e.Salary).Distinct()
.OrderByDescending(s => s).Skip(1)
.Select(s => (decimal?)s).FirstOrDefault()
});
Edge cases to discuss
- Only one employee, or all employees with the same salary: return null rather than a misleading 0.
- Duplicate highest salaries: Distinct handles them (input 50k, 50k, 40k gives 40k).
- Null salaries in the database: filter them out first.
SQL equivalent worth knowing: SELECT MAX(Salary) FROM Employees WHERE Salary < (SELECT MAX(Salary) FROM Employees), or DENSE_RANK() OVER (ORDER BY Salary DESC) = 2.