Skip to main content

Query Explanation - 1: Retrieving the Top 5 Highest-Paid Employees for Each Department

 

In this blog, we will break down how to retrieve the top 5 highest-paid employees from each department using SQL. This is a common query when working with databases that store information about employees and departments, and it involves ranking employees by their salary and returning the top earners for each department.

Problem Statement:

We want to retrieve the top 5 highest-paid employees in each department, sorted by salary in descending order. This means for each department, we need to rank employees by their salary, then limit the results to the top 5 for that department.

Example Schema:

Assume we have the following two tables:

  1. Employee:

    • EmployeeID (Primary Key)
    • FirstName
    • LastName
    • Salary
    • DepartmentID (Foreign Key)
  2. Department:

    • DepartmentID (Primary Key)
    • DepartmentName

SQL Query:

To solve this, we can use Common Table Expressions (CTEs) or Window Functions to rank employees by their salary within each department. The ROW_NUMBER() window function is particularly useful for this case, as it can assign a unique rank to each employee within a department, based on their salary.

Here’s how we can approach it:

WITH RankedEmployees AS (
    SELECT 
        e.EmployeeID,
        e.FirstName,
        e.LastName,
        e.Salary,
        d.DepartmentName,
        ROW_NUMBER() OVER (PARTITION BY e.DepartmentID ORDER BY e.Salary DESC) AS rank
    FROM 
        Employee e
    JOIN 
        Department d ON e.DepartmentID = d.DepartmentID
)
SELECT 
    EmployeeID,
    FirstName,
    LastName,
    Salary,
    DepartmentName
FROM 
    RankedEmployees
WHERE 
    rank <= 5
ORDER BY 
    DepartmentName,
    Salary DESC;

Detailed Breakdown:

  1. Common Table Expression (CTE):

    • The WITH clause is used to define a temporary result set named RankedEmployees. This CTE allows us to simplify the query and avoid duplicating logic in the SELECT statement.
  2. ROW_NUMBER() Function:

    • ROW_NUMBER() is a window function that assigns a unique row number to each row within a partition. Here, we partition the results by DepartmentID using the PARTITION BY clause. This means the row numbers will reset for each department.
    • The ORDER BY e.Salary DESC ensures that the highest salary gets the row number 1, the second highest salary gets 2, and so on.
  3. Partitioning by Department:

    • The PARTITION BY e.DepartmentID groups the rows by department, so that the row numbers are applied separately for each department. This ensures that each department’s employees are ranked based on their salary, independent of other departments.
  4. Filtering Top 5 Employees:

    • In the final SELECT query, we filter the results to only include employees where rank <= 5. This limits the result to the top 5 employees in each department.
  5. Sorting the Results:

    • The results are sorted by DepartmentName and then by Salary in descending order, which makes it easier to see the top-paid employees in each department in a structured format.

Example Output:

Let's say we have the following data in the Employee and Department tables:



After executing the query, we will retrieve the top 5 highest-paid employees in each department, based on their salary, ordered by the department and salary.

Key Takeaways:

  • Window Functions like ROW_NUMBER() are powerful for ranking and partitioning data without needing subqueries or multiple JOIN operations.
  • The use of PARTITION BY allows you to rank data within specific groups (in this case, departments) while applying ranking logic across all rows.
  • This type of query is often used in real-world scenarios where businesses need to retrieve the top performers, highest-paid employees, or best-selling products by category.

Feel free to try this query in your own environment and see how the ROW_NUMBER() function can simplify complex ranking tasks in SQL.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...