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 891499F931A for ; Sun, 25 Jun 2006 15:36:14 -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 37123-06-2 for ; Sun, 25 Jun 2006 15:36:10 -0300 (ADT) X-Greylist: delayed 00:20:50.57189 by SQLgrey- Received: from svr4.postgresql.org (svr4.postgresql.org [66.98.251.159]) by postgresql.org (Postfix) with ESMTP id 69A769FA68D for ; Sun, 25 Jun 2006 15:36:03 -0300 (ADT) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.3 Received: from moonunit2.moonview.localnet (wsip-70-167-125-69.sd.sd.cox.net [70.167.125.69]) by svr4.postgresql.org (Postfix) with ESMTP id DEBC05AF176 for ; Sun, 25 Jun 2006 18:15:06 +0000 (GMT) Received: from [127.0.0.1] (moonunit2.moonview.localnet [192.168.0.2]) by moonunit2.moonview.localnet (8.13.1/8.13.1) with ESMTP id k5PISLiH018689 for ; Sun, 25 Jun 2006 11:28:24 -0700 Message-ID: <449ED2A6.4090107@emolecules.com> Date: Sun, 25 Jun 2006 11:15:02 -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: 200607/4 X-Sequence-Number: 19864 Here is a subtle 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 obvious solution is to make the hitlist.sortorder column have the nextval() as its default and eliminate the first sub-select. But I thought the two would be equivalent. Thanks, Craig