EN
PostgreSQL - get row position with SELECT query
3 points
In this article, we would like to show you how to get row number with each row in PostgreSQL.
Quick solution:
xxxxxxxxxx
1
SELECT
2
row_number() OVER(ORDER BY "id"),
3
t.*
4
FROM table_name AS t;

Note:
At the end of this article you can find database preparation SQL queries.
Query:
xxxxxxxxxx
1
SELECT
2
row_number() OVER(ORDER BY "id"),
3
"name",
4
"surname"
5
FROM users;
Output:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL PRIMARY KEY,
3
"name" VARCHAR(100) NOT NULL,
4
"email" VARCHAR(100) NOT NULL,
5
"country" VARCHAR(15) NOT NULL
6
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "users"
2
("name", "email", "country")
3
VALUES
4
('Tom', 'tom@email.com', 'Poland'),
5
('Chris','chris@email.com', 'Spain'),
6
('Jack','jack@email.com', 'Spain'),
7
('Kim','kim@email.com', 'Vietnam'),
8
('Marco','marco@email.com', 'Italy'),
9
('Kate','kate@email.com', 'Spain'),
10
('Nam','nam@email.com', 'Vietnam');