Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return row position - Postgres

Tags:

sql

postgresql

I return a table with position:

select * 
from (
    select *, row_number() over() as position 
    from organization
) result 
where data1 = 'Hello';

Gives back this, which is correct:

data1 | Hello
data2 | Joe
position | 5

But when I do:

select position 
from (
   select *, row_number() over() as position 
   from organization
) result 
where data1 = 'Hello';

It returns:

position | 25

What am missing here? How can I modify this query to return 5?

like image 529
Anton Kim Avatar asked Mar 27 '17 17:03

Anton Kim


People also ask

How do you get a specific row in PostgreSQL?

The heart of all SQL queries is the SELECT command. SELECT is used to build queries (also known as SELECT statements). Queries are the only SQL instructions by which your data can be retrieved from tables and views.

What is Row_number () in PostgreSQL?

In PostgreSQL, the ROW_NUMBER() function is used to assign a unique integer to every row that is returned by a query. Syntax: ROW_NUMBER() OVER( [PARTITION BY column_1, column_2, …] [ORDER BY column_3, column_4, …] )

Is there a Rowid in Postgres?

ROWID is an indicator in Oracle of the order of rows on disk for a given table. In PostgreSQL, this is implemented with a page and leaf identifier. The identifier is visible in a query as a pseudo column with the name of “ctid”. You can call this column in a query explicitly by name.

How do I find the Postgres row number?

Since PostgreSQL 8.4, you can easily show row number in PostgreSQL using ROW_NUMBER() function. Here's the SQL query to get row id in PostgreSQL. In the above SQL query, we use row_number() window function to generate row number for each row.


1 Answers

A table in RDBMS is an unordered set of rows. Without an order by clause in the row_number, it will assign row numbers arbitrarily.

Use proper order by clause to get consistent results:

select position 
from (
   select *,
        row_number() over(
           order by ??   -- add column(s) here
        ) as position 
   from organization
) result 
where data1 = 'Hello';
like image 65
Gurwinder Singh Avatar answered Sep 30 '22 01:09

Gurwinder Singh