Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: Find position of a specific row within a resultset?

I'm trying to figure out how to get the relative position of a single item in a query relative to all the items returned from the query.

For example,the long hand way of getting the answer would be:

single_item = SELECT * FROM table WHERE id=65
result = SELECT * FROM table WHERE published_date < date_value
x=1
foreach(result as item):
    if(item.id == single_item.id):
        required_value = x
    endif
    x++
endforeach

Is there a simple way of getting required_value just through a single postgres query?

like image 637
Steerpike Avatar asked Sep 05 '10 01:09

Steerpike


People also ask

How do I select a specific row in PostgreSQL?

A Simple SELECT Use the following syntax to retrieve all rows and columns from a table: SELECT * FROM table_name; The asterisk ( * ) character, as mentioned in the explanation of SELECT 's syntax, is short-hand for all non-system columns.

Which method used to retrieve data from specific columns for each row returned by the query *?

The method for retrieving a value of SQL type VARCHAR is getString . The second column in each row stores a value of SQL type INTEGER , and the method for retrieving values of that type is getInt .

How do I find the Postgres row number?

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, …] )

How do I select distinct in PostgreSQL?

Removing duplicate rows from a query result set in PostgreSQL can be done using the SELECT statement with the DISTINCT clause. It keeps one row for each group of duplicates. The DISTINCT clause can be used for a single column or for a list of columns.


1 Answers

Use analytic/ranking/windowing functionality - 8.4 documentation link:

WITH summary AS (
   SELECT t.*,
          ROW_NUMBER() OVER(ORDER BY t.published_date) AS position
     FROM TABLE t)
SELECT s.*
  FROM summary s
 WHERE s.id = 65

Alternate without the WITH syntax:

SELECT s.*
  FROM (SELECT t.*,
               ROW_NUMBER() OVER(ORDER BY t.published_date) AS position
          FROM TABLE t) s
 WHERE s.id = 65

The position column will be an integer value representing the location of the record where the id value is 65, based on the published_date column in ascending order. If you want the position value to be duplicated when there are ties, replace ROW_NUMBER() with RANK()

like image 189
OMG Ponies Avatar answered Oct 24 '22 18:10

OMG Ponies