EN
MS SQL Server - select last N rows
0 points
In this article, we would like to show you how to select the last N rows from a table in MS SQL Server.
Ascending order:
xxxxxxxxxx
1
SELECT * FROM (
2
SELECT TOP N *
3
FROM [table_name]
4
ORDER BY [column_name] DESC
5
) subquery
6
ORDER BY [column_name] ASC;
Descending order:
xxxxxxxxxx
1
SELECT TOP N *
2
FROM [table_name]
3
ORDER BY [column_name] DESC;
To show how to select the last N rows from a table, we will use the following table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we will select the last three users from the users
table in ascending order.
Query:
xxxxxxxxxx
1
SELECT * FROM (
2
SELECT TOP 3 *
3
FROM [users]
4
ORDER BY [id] DESC
5
) subquery
6
ORDER BY [id] ASC;
Output:

In this example, we will select the last three users from the users
table in descending order.
Query:
xxxxxxxxxx
1
SELECT * FROM [users] ORDER BY [id] DESC LIMIT 3;
Output:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE [users] (
2
[id] INT IDENTITY(1,1),
3
[name] VARCHAR(100) NOT NULL,
4
[country] VARCHAR(15) NOT NULL,
5
PRIMARY KEY ([id])
6
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO [users]
2
([name], [country])
3
VALUES
4
('Tom', 'Poland'),
5
('Chris', 'Spain'),
6
('Jack', 'Spain'),
7
('Kim', 'Vietnam'),
8
('Marco', 'Italy'),
9
('Kate', 'Spain'),
10
('Nam', 'Vietnam');