pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Karsten Hilbert <Karsten.Hilbert@gmx.net>
Cc: pgsql-sql@postgresql.org
Subject: Re: how to "enumerate" rows ?
Date: Mon, 26 Jan 2004 20:08:27 -0500
Message-ID: <7528.1075165707@sss.pgh.pa.us> (raw)
In-Reply-To: <20040127011505.H606@hermes.hilbert.loc>
References: <20040127011505.H606@hermes.hilbert.loc>

Karsten Hilbert <Karsten.Hilbert@gmx.net> 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



view thread (2+ messages)

Message-ID: <7528.1075165707@sss.pgh.pa.us>
Permalink:  ../7528.1075165707@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/7528.1075165707@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: tgl@sss.pgh.pa.us, Karsten.Hilbert@gmx.net
  Subject: Re: how to "enumerate" rows ?
  In-Reply-To: <7528.1075165707@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox