How to Select the Last Records in a One to Many Relationship using SQL Server
In database management, handling one-to-many relationships is common, where a record in one table relates to multiple records in another. For instance, a parent table may have one record linked to multiple child records in a related table. Retrieving the latest record from the "many" side for each record on the "one" side requires specific SQL techniques. Below, we explain several methods with examples.
In this article, we will explain how to achieve this using different approaches and their examples too. These techniques will help us efficiently retrieve the latest records in a one-to-many relationship scenario
How to Select the Last Records in a One-to-Many Relationship?
One-to-many relationships signify that each record in one table can correspond to multiple records in another table. For instance, consider two tables A and B, where the Primary key column of A is referenced as a Foreign key in B. To efficiently select the last records from such relationships, we employ SQL Server joins. Below is the method that helps to select the last records in a one-to-many relationship using SQL Server as follows.
- Using Subquery with LIMIT and ORDER BY
- Using Subquery with Max Aggregate Function and GROUP BY
- Using o-related Subquery
- Using Left Join Logic
Let's set up an environment to select the last records
To understand How to select the last records in a one-to-many relationship using SQL Server we need a 2 table on which we will perform various operations and queries. Here we will consider a table called Table A and Table B which contains. Here Table A contains Primary Key, Column 2, Column 3 and Table B contains Primary Key, Column 1, Foreign Key as Columns.
Query:
--create Table A
create table [Table A](
[Primary Key] varchar(10) Primary Key,
[Column 2] varchar(10),
[Column 3] varchar(10)
)
--create Table B
create table [Table B](
[Primary Key] varchar(10) Primary Key,
[Column 1] varchar(10),
[Foreign Key] varchar(10) Foreign Key references [Table A](Primary Key)
)
--insert into the Table A
insert into [Table A] values ('Key 1', 'D1', 'D4'), ('Key 2', 'D2', 'D5'), ('Key 3', 'D3', 'D6');
--insert into the Table B
insert into [Table B] values ('1', '...', 'Key 1'), ('2', '...', 'Key 2'), ('3', '...', 'Key 1'), ('4', '...', 'Key 1'), ('5', '...', 'Key 2'), ('6', '...', 'Key 3');
Table A

Table B

Methods to Select the Last Records
1. Using Subquery with LIMIT and ORDER BY
Fetch the last record from Table B for each record in Table A by ordering the child records in descending order and limiting the result. Here we will add a subquery that will look for the last record match in Table B for every record in Table A with ORDER BY Descending and LIMIT options
Query:
SELECT *
FROM [Table A] A
JOIN [Table B] B ON A.PrimaryKey = B.ForeignKey
WHERE B.PrimaryKey = (
SELECT PrimaryKey
FROM [Table B]
WHERE ForeignKey = A.PrimaryKey
ORDER BY PrimaryKey DESC
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
);
Output
Primary Key (A) | Column 2 | Column 3 | Primary Key (B) | Column 1 | Foreign Key |
---|---|---|---|---|---|
Key 1 | D1 | D4 | 4 | ... | Key 1 |
Key 2 | D2 | D5 | 5 | ... | Key 2 |
Key 3 | D3 | D6 | 6 | ... | Key 3 |
Explanation:
- The subquery retrieves the latest record (highest primary key) for each foreign key.
- The
TOP 1
ensures only the latest record is selected.
2. Using Subquery with Max Aggregate Function and GROUP BY
In this method, we use the GROUP BY
clause on Table A.
PrimaryKey
to group records based on the primary keys from Table A
. Within each group, the MAX
aggregate function is used to identify the record in Table B
with the highest Primary Key
value for the corresponding Foreign Key
Query:
SELECT MAX(A.PrimaryKey) as PrimaryKey, MAX(A.[Column 2]) as [Column 2], ...
FROM [Table A] A
JOIN [Table B] B ON A.[PrimaryKey] = B.[ForeignKey]
GROUP BY A.PrimaryKey;
Output
Primary Key (A) | Column 2 | Column 3 | Primary Key (B) | Column 1 | Foreign Key |
---|---|---|---|---|---|
Key 1 | D1 | D4 | 4 | ... | Key 1 |
Key 2 | D2 | D5 | 5 | ... | Key 2 |
Key 3 | D3 | D6 | 6 | ... | Key 3 |
Explanation:
- The
GROUP BY
groups child records by the foreign key. - The
MAX()
retrieves the highest (latest) record for each group.
3. Using Co-related Sub Query
In this approach, a correlated subquery is used to dynamically determine the maximum PrimaryKey from Table B
for each corresponding record in Table A
. The main query fetches only the records from Table B
where the PrimaryKey
matches the maximum value returned by the subquery for each ForeignKey
.
Query:
SELECT A.*, B.*
FROM [Table A] A
JOIN [Table B] B on A.[PrimaryKey] = B.[ForeignKey]
WHERE B.PrimaryKey = (
SELECT MAX(PrimaryKey)
FROM [Table B]
WHERE ForeignKey = A.PrimaryKey
);
Output
Primary Key (A) | Column 2 | Column 3 | Primary Key (B) | Column 1 | Foreign Key |
---|---|---|---|---|---|
Key 1 | D1 | D4 | 4 | ... | Key 1 |
Key 2 | D2 | D5 | 5 | ... | Key 2 |
Key 3 | D3 | D6 | 6 | ... | Key 3 |
Explanation:
- The correlated subquery ensures only the latest record is selected for each group.
- The
MAX()
function identifies the last record.
4. Using Left Join Logic
Here we will use Left join Table with 2 Table B and for second left join we will add an extra condition as records with PrimaryKey Column in 3rd table of Join sequence should be greater than PrimaryKey Column of 2nd Table ie. Table B. This create some NULL records in 3rd used table which becomes our output.
Query:
SELECT A.*, B.*
FROM [Table A] A
LEFT JOIN [Table B] B ON A.PrimaryKey = B.ForeignKey
LEFT JOIN [Table B] C ON A.PrimaryKey = C.ForeignKey AND B.PrimaryKey < C.PrimaryKey
WHERE C.PrimaryKey IS NULL;
Output
Primary Key (A) | Column 2 | Column 3 | Primary Key (B) | Column 1 | Foreign Key |
---|---|---|---|---|---|
Key 1 | D1 | D4 | 4 | ... | Key 1 |
Key 2 | D2 | D5 | 5 | ... | Key 2 |
Key 3 | D3 | D6 | 6 | ... | Key 3 |
Explanation:
- The second left join creates a NULL match for non-latest records.
- The
WHERE C.PrimaryKey IS NULL
filters out all but the last record.
Conclusion
In conclusion, SQL Server offers several methods to select the last records in a one-to-many relationship. Whether using subqueries, aggregate functions, or left join logic, these approaches provide flexibility and efficiency in fetching the desired data. Understanding these techniques enables database managers to effectively handle such relationships and retrieve the most relevant information for their needs.