X-Original-To: pgsql-sql@postgresql.org Received: from spampd.localdomain (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 6F3744758F1 for ; Thu, 17 Apr 2003 15:35:41 -0400 (EDT) Received: from sss.pgh.pa.us (unknown [192.204.191.242]) by postgresql.org (Postfix) with ESMTP id 9F0BD475458 for ; Thu, 17 Apr 2003 15:35:40 -0400 (EDT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.12.9/8.12.9) with ESMTP id h3HJZfU6016895; Thu, 17 Apr 2003 15:35:41 -0400 (EDT) To: Randall Lucas Cc: pgsql-sql@postgresql.org Subject: Re: Ordinal value of row within set returned by a query? In-reply-to: <9AE98E9A-70FE-11D7-9BCD-000A957653D6@tercent.net> References: <9AE98E9A-70FE-11D7-9BCD-000A957653D6@tercent.net> Comments: In-reply-to Randall Lucas message dated "Thu, 17 Apr 2003 14:01:25 -0400" Date: Thu, 17 Apr 2003 15:35:41 -0400 Message-ID: <16894.1050608141@sss.pgh.pa.us> From: Tom Lane X-Spam-Status: No, hits=-32.5 required=5.0 tests=BAYES_01,EMAIL_ATTRIBUTION,IN_REP_TO,QUOTED_EMAIL_TEXT, REFERENCES,REPLY_WITH_QUOTES autolearn=ham version=2.50 X-Spam-Level: X-Spam-Checker-Version: SpamAssassin 2.50 (1.173-2003-02-20-exp) X-Archive-Number: 200304/287 X-Sequence-Number: 12988 Randall Lucas writes: > I'm puzzling over whether it is possible within SQL alone to determine > the ordinal position of a row within the set returned by a query. It > seems clear to me that pgsql "knows" what position in a set a > particular tuple holds, since one can OFFSET, ORDER BY, and LIMIT; > however, I can't seem to find a function or "hidden field" that will > return this. That's because there isn't one. The traditional hack for this has been along the lines of create temp sequence foo; select nextval('foo'), * from (select ... whatever ... order by something) ss; drop sequence foo; which is illegal per the SQL spec (you can't ORDER BY in a subselect according to spec), but it's the only way that you can do computation after a sort pass. In a single-level SELECT, ORDER BY happens after the computation of the SELECT output values. Usually it's a lot easier to plaster on the row numbers on the client side, though. > What I would like is something along these lines: I wish to ORDER BY > an ordinal field that is likely to be present, but may not be present, > and then by a unique value to ensure stability of ordering. Why don't you order by the ordinal field, then the table's primary key? (If it hasn't got a primary key, maybe it should.) regards, tom lane