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?
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.
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, …] )
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.
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.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With