X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (neptune.hub.org [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id BB7D4D1E156 for ; Tue, 27 Jan 2004 01:09:01 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (neptune.hub.org [200.46.204.2]) (amavisd-new, port 10024) with ESMTP id 13349-08 for ; Mon, 26 Jan 2004 21:08:33 -0400 (AST) Received: from sss.pgh.pa.us (unknown [192.204.191.242]) by svr1.postgresql.org (Postfix) with ESMTP id 93341D1E0EE for ; Mon, 26 Jan 2004 21:08:26 -0400 (AST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.12.10/8.12.10) with ESMTP id i0R18SnX007529; Mon, 26 Jan 2004 20:08:28 -0500 (EST) To: Karsten Hilbert Cc: pgsql-sql@postgresql.org Subject: Re: how to "enumerate" rows ? In-reply-to: <20040127011505.H606@hermes.hilbert.loc> References: <20040127011505.H606@hermes.hilbert.loc> Comments: In-reply-to Karsten Hilbert message dated "Tue, 27 Jan 2004 01:15:05 +0100" Date: Mon, 26 Jan 2004 20:08:27 -0500 Message-ID: <7528.1075165707@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200401/218 X-Sequence-Number: 16611 Karsten Hilbert writes: >> Now, I need to enumerate the vaccinations per patient per >> disease. They are intrinsically ordered by their date of >> vaccination but I need to attach a number to them ... The best, recommended way to do this is to plaster on the row numbers in your client-side code. AFAIK there just isn't any way to do it in standard SQL. If you feel you really gotta have a server-side solution, the easiest way is CREATE TEMP SEQUENCE myseq; SELECT nextval('myseq'), * FROM (SELECT ... ORDER BY date_given) ss; DROP SEQUENCE myseq; (Alternatively, you can create a temp sequence once per session and just reset it with setval() for each query.) Note that you can *not* simplify this to SELECT nextval('myseq'), ... ORDER BY date_given; because if you do, the nextval() values may get computed before the ORDER BY sorting occurs. Putting the ORDER BY into a sub-select makes it work reliably. This is not real portable since neither sequences nor ORDER BY in a subselect are SQL-standard. It's also probably a good deal slower than a simple client-side counter, because nextval() does a lot more than just add one to a variable. But if you have to have it, there it is. regards, tom lane