X-Original-To: pgsql-performance-postgresql.org@postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id 2C2EF9FA5FC for ; Fri, 30 Jun 2006 02:56:38 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 38752-07 for ; Fri, 30 Jun 2006 02:56:34 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from moonunit2.moonview.localnet (wsip-70-167-125-69.sd.sd.cox.net [70.167.125.69]) by postgresql.org (Postfix) with ESMTP id D24579FA0EC for ; Fri, 30 Jun 2006 02:56:33 -0300 (ADT) Received: from [192.168.0.3] (moonunit3.moonview.localnet [192.168.0.3]) by moonunit2.moonview.localnet (8.13.1/8.13.1) with ESMTP id k5U6AVsh027696 for ; Thu, 29 Jun 2006 23:10:31 -0700 Message-ID: <44A4AEAE.8070809@modgraph-usa.com> Date: Thu, 29 Jun 2006 21:55:10 -0700 From: "Craig A. James" User-Agent: Thunderbird 1.5.0.4 (X11/20060516) MIME-Version: 1.0 To: pgsql-performance@postgresql.org Subject: Sort order in sub-select Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200606/489 X-Sequence-Number: 19846 Here is a question about SQL. I have a one-to-many pair of tables (call them "P" and "C" for parent and child). For each row of P, there are many rows in C with data, and I want to sort P on the min(c.data). The basic query is simple: select p_id, min(data) as m from c group by p_id order by m; Now the problem: I also want to store this, in sorted order, as a "hitlist", so I have a table like this: create table hitlist(p_id integer, sortorder integer); and a sequence to go with it. The first thing I tried doesn't work: insert into hitlist(p_id, sortorder) (select p_id, nextval('hitlist_seq') from (select p_id, min(data) as m from c group by p_id order by m); Apparently, the sort order returned by the innermost select is NOT maintained as you go through the next select statement -- the rows seem to come out in random order. This surprised me. But in thinking about the definition of SQL itself, I guess there's no guarantee that sort order is maintained across sub-selects. I was caught by this because in Oracle, this same query works "correctly" (i.e. the hitlist ends up in sorted order), but I suspect that was just the luck of their implementation. Can anyone confirm this, that the sort order is NOT guaranteed to be maintained through layers of SELECT statements? The apparent solution is to make the hitlist.sortorder column have nextval() as its default and eliminate the first sub-select. But I thought the two would be equivalent. Thanks, Craig