Quy Vu Xuan
Quy Vu Xuan

Reputation: 189

Add Index to postgreSQL query result

My query result looks like this:

| A | B |
|-------|
| 1 | 2 |
| 1 | 4 |
| 1 | 6 |
| 1 | 9 |
| 1 | 1 |
| 1 | 6 |
| 1 | 9 |

Now I want to increase column A by the index of the result table, so the result would become like this:

| A | B |
|-------|
| 2 | 2 |
| 3 | 4 |
| 4 | 6 |
| 5 | 9 |
| 6 | 1 |
| 7 | 6 |
| 8 | 9 |

How can I do it? Thanks!

Upvotes: 0

Views: 221

Answers (2)

Thiago Virgilio
Thiago Virgilio

Reputation: 1

Maybe something like that:

SELECT 
    (row_number() OVER (ORDER BY A) + A) AS columnAIndex, 
     columnB
FROM ... 

I don't have a PostgreSQL client installed here, therefore, i don't tested this query.

Upvotes: 0

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

You want row_number()

select (row_number() over (order by a) + 1) as A, b
from table t;

Upvotes: 2

Related Questions