EN
PostgreSQL - select last N rows
0 points
In this article, we would like to show you how to select last N rows from a table in PostgreSQL.
Ascending order:
xxxxxxxxxx
1
SELECT * FROM (
2
SELECT * FROM "table_name"
3
ORDER BY "column_name" DESC
4
LIMIT N
5
) subquery
6
ORDER BY "column_name" ASC;
Descending order:
xxxxxxxxxx
1
SELECT * FROM "table_name"
2
ORDER BY "column_name" DESC
3
LIMIT N;
To show how to select 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 last three users from the users
table in ascending order.
Query:
xxxxxxxxxx
1
SELECT * FROM (
2
SELECT * FROM "users"
3
ORDER BY "id" DESC
4
LIMIT 3
5
) subquery
6
ORDER BY "id" ASC;
Output:

In this example, we will select 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" SERIAL PRIMARY KEY,
3
"name" VARCHAR(100) NOT NULL,
4
"country" VARCHAR(15) NOT NULL
5
);
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');