X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (neptune.hub.org [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id 98962D1EAC2 for ; Wed, 21 Jan 2004 17:18:26 +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 88343-07 for ; Wed, 21 Jan 2004 13:17:56 -0400 (AST) Received: from silmaril.syscor.priv (h24-108-208-253.sbm.shawcable.net [24.108.208.253]) by svr1.postgresql.org (Postfix) with ESMTP id E782CD1D52B for ; Wed, 21 Jan 2004 13:16:34 -0400 (AST) Received: from syscor.com (strider.syscor.priv [192.168.1.3]) by silmaril.syscor.priv (8.12.8/8.12.8) with ESMTP id i0LHGano005129 for ; Wed, 21 Jan 2004 09:16:36 -0800 Message-ID: <400EB45A.40309@syscor.com> Date: Wed, 21 Jan 2004 09:18:18 -0800 From: Ron St-Pierre User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 X-Accept-Language: en-us, en MIME-Version: 1.0 To: pgsql-performance@postgresql.org Subject: ORDER BY and LIMIT with SubSelects Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200401/209 X-Sequence-Number: 5383 I need to get 200 sets of the most recent data from a table for further processing, ordered by payDate. My current solution is to use subselects to: 1 - get a list of unique data 2 - get the 200 most recent records (first 200 rows, sorted descending) 3 - sort them in ascending order SELECT SSS.* FROM (SELECT SS.* FROM (SELECT DISTINCT ON (nonUniqField) first, second, third, cost, payDate, nonUniqField FROM histdata WHERE userID = 19048 AND cost IS NOT NULL ) SS ORDER BY SS.payDate DESC LIMIT 200 ) SSS ORDER BY payDate; My question is in regards to steps 2 and 3 above. Is there some way that I can combine both steps into one to save some time? PostgreSQL 7.4beta2 on i686-pc-linux-gnu, compiled by GCC 2.95.4 Thanks Ron