How to Join to First Row in SQL Server
Last Updated :
19 Mar, 2024
Joining the first row in SQL Server can be a common requirement in various scenarios, such as when we need to retrieve specific data associated with the first occurrence of a particular group or when you want to fetch additional details related to the first record in a result set.
In this article, We will learn about How to Join to first row in SQL Server by understanding various approaches along with the examples and so on.
How to Join First Row in SQL Server?
When working with SQL Server, we may encounter situations where we need to join to the first row of a related table. This could be to retrieve the earliest record for each group or to extract initial data for further analysis. To solve this problem, we'll explore three different approaches are as follows:
- Using Subqueries
- Using ROW_NUMBER()
- Using CROSS APPLY
Let's set up an environment
To understand How to Join to first row in SQL Server we need a table on which we will perform various operations and queries. Here we will consider a table called EmployeeReviews which contains EmployeeID, ReviewDate, Rating, and department as Columns.
-- Create EmployeeReviews table
CREATE TABLE EmployeeReviews (
EmployeeID INT,
ReviewDate DATE,
Rating INT,
PRIMARY KEY (EmployeeID, ReviewDate)
);
-- Insert sample data into the EmployeeReviews table
INSERT INTO EmployeeReviews (EmployeeID, ReviewDate, Rating) VALUES
(1, '2024-01-01', 4),
(1, '2024-02-01', 5),
(2, '2024-01-15', 3),
(3, '2024-02-01', 4),
(3, '2024-03-01', 5),
(4, '2024-01-01', 5),
(4, '2024-02-01', 4);
Output:
table1. Using Subqueries
This method uses a subquery to select the first row from the EmployeeReviews
table for each employee. The subquery is joined to the Employee
table using a LEFT JOIN
to ensure that all employees are included in the result, even if they don't have a corresponding row in the EmployeeReviews
table..
SELECT
e.EmployeeID,
e.Name,
e.Salary,
firstSalaryReview.ReviewDate,
firstSalaryReview.Rating
FROM
Employee e
LEFT JOIN (
SELECT TOP 1
r.EmployeeID,
r.ReviewDate,
r.Rating
FROM
EmployeeReviews r
ORDER BY
r.ReviewDate
) firstSalaryReview ON e.EmployeeID = firstSalaryReview.EmployeeID;
Output:

Explanation:
- The subquery selects the first row from the
EmployeeReviews
table without any specific ordering. This can lead to unpredictable results because the database engine may return different rows each time the query is executed.
- The
LEFT JOIN
ensures that all rows from the Employee
table are included in the result, even if there is no matching row in the subquery. However, since the subquery doesn't guarantee a specific row, the result may not always be meaningful.
2. Using ROW_NUMBER()
This method uses the ROW_NUMBER()
window function to assign a unique row number to each row in the EmployeeReviews
table, partitioned by EmployeeID
and ordered by ReviewDate
.
The main query then filters the results to include only rows where the row number is 1, effectively selecting the first row for each employee.
WITH RankedReviews AS (
SELECT
r.EmployeeID,
r.ReviewDate,
r.Rating,
ROW_NUMBER() OVER (PARTITION BY r.EmployeeID ORDER BY r.ReviewDate) AS RowNum
FROM
EmployeeReviews r
)
SELECT
e.EmployeeID,
e.Name,
e.Salary,
rr.ReviewDate,
rr.Rating
FROM
Employee e
LEFT JOIN RankedReviews rr ON e.EmployeeID = rr.EmployeeID AND rr.RowNum = 1;
Output:

Explanation:
- The
ROW_NUMBER()
function assigns a unique row number to each row in the EmployeeReviews
table, partitioned by EmployeeID
and ordered by ReviewDate
. This ensures that the first row for each employee is assigned a row number of 1.
- The main query then left joins the
Employee
table with the RankedReviews
common table expression (CTE) on EmployeeID
and RowNum = 1
. This ensures that only the first row for each employee is included in the result.
3. Using CROSS APPLY
This method uses the CROSS APPLY
operator to apply a table-valued function (in this case, a subquery) to each row from the Employee
table.
The subquery selects the first row from the EmployeeReviews
table for each employee, and the CROSS APPLY
ensures that only the first row is returned for each employee in the result set.
Consider the following example.
SELECT
e.EmployeeID,
e.Name,
e.Salary,
firstSalaryReview.ReviewDate,
firstSalaryReview.Rating
FROM
Employee e
CROSS APPLY (
SELECT TOP 1
r.ReviewDate,
r.Rating
FROM
EmployeeReviews r
WHERE
r.EmployeeID = e.EmployeeID
ORDER BY
r.ReviewDate
) firstSalaryReview;
Output:

Explanation:
- The
CROSS APPLY
operator is used to apply a table-valued function (in this case, a subquery) to each row from the Employee
table. This allows us to join each employee with their first review from the EmployeeReviews
table.
- The subquery selects the first row from the
EmployeeReviews
table for each employee, ordered by ReviewDate
. The WHERE
clause ensures that only rows for the current employee are considered.
CONCLUSION
Partitioning into first row of SQL Server can be implemented by different methods, including subqueries with ROW_NUMBER (), cross apply with TOP or Common Table Expressions (CTE). Different procedures will be good for various purposes and might be more appropriate depending on the particularities of your choosing and the difficulty of your information. As you learn these methods, you can appropriately apply them to your queries in order to easily get the necessary data from your SQL Server database.
Similar Reads
How to Join First Row in SQL?
SQL (Structured Query Language) is a powerful tool used to manage and manipulate data in relational databases. A common requirement when dealing with data relationships is to fetch only the first row from a table based on specific conditions or criteria. This can be particularly useful when joining
6 min read
How to Limit Rows in a SQL Server?
To limit rows in SQL Server, use the TOP clause in the SELECT statement. Using the TOP clause in SQL Server, users can limit the number of rows in the results set. Here, we will understand how to limit rows in SQL Server with the help of different examples. Steps to Limit Rows in SQL ServerLet's che
3 min read
How to Select the First Row of Each GROUP BY in SQL?
Selecting the first row of each group in SQL is a common requirement in database queries, especially when working with grouped data. SQL GROUP BY queries are highly effective for organizing data into logical groups, and additional techniques like window functions help to isolate the first row from e
5 min read
How to SELECT Top N Rows For Each Group in SQL Server
SQL Serverâs ROW_Number() window function is often used to get the top number of rows in a group. In this article, weâll look at how to get the top N Row Counts in SQL Server using this function. Weâll provide step-by-step instructions, syntax examples, and examples to help you get the results you n
4 min read
How to Return Random Rows Efficiently in SQL Server?
In this article, we are going to learn an SQL Query to return random rows efficiently. To execute the query, we are going to first create a table and add data into it. We will then sort the data according to randomly created IDs(using the NEWID() method) and return the top rows after the sorting ope
2 min read
How to Remove Prefix From Field in SQL Server?
In SQL, certain words are reserved. These are called Keywords or Reserved Words. These words cannot be used as identifiers i.e. as column names in SQL. But, there is an exception to this rule too. In this article, we will discuss how to use Reserved Words as column names in SQL and how to remove pre
2 min read
How to Concatenate Text From Multiple Rows in SQL Server
When we fetch data from a table, there may be requirements to concatenate the text value of a table column in multiple rows into a single row. There are many ways we can concatenate multiple rows into single row SQL Server. We can use different ways based on need and convenience. In this article, we
6 min read
How to SELECT FROM Stored Procedure in SQL
Stored procedures are precompiled SQL queries stored in the database that encapsulate logic and can accept parameters, perform operations and return results. They are widely used in SQL for encapsulating reusable logic, improving performance and enhancing security. In this article, weâll explore how
4 min read
How to Select Row With Max Value in SQL Server
In SQL Server, retrieving rows that contain the maximum value for a specific column for each distinct value in another column can be a common and challenging task. This process is done by identifying the maximum value for each group and then selecting the corresponding rows. In this article, we'll e
6 min read
How to Select the nth Row in a SQL Server Database Table?
In SQL Server databases, it's common to encounter scenarios where we need to retrieve a specific row, such as the nth row, from a table efficiently. Whether you're building a pagination feature for a web application or analyzing data, having the ability to select a particular row based on its positi
3 min read