Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1f8K2u-0003OT-BS for pgsql-general@arkaria.postgresql.org; Tue, 17 Apr 2018 06:24:52 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1f8K2s-0000k2-V0 for pgsql-general@arkaria.postgresql.org; Tue, 17 Apr 2018 06:24:50 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1f8K2s-0000jr-N2 for pgsql-general@lists.postgresql.org; Tue, 17 Apr 2018 06:24:50 +0000 Received: from mx2.mailbox.org ([80.241.60.215]) by magus.postgresql.org with esmtps (TLS1.2:RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1f8K2l-0003dL-27 for pgsql-general@postgresql.org; Tue, 17 Apr 2018 06:24:50 +0000 Received: from smtp1.mailbox.org (smtp1.mailbox.org [80.241.60.240]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mx2.mailbox.org (Postfix) with ESMTPS id 3114740F80; Tue, 17 Apr 2018 08:24:41 +0200 (CEST) X-Virus-Scanned: amavisd-new at heinlein-support.de Received: from smtp1.mailbox.org ([80.241.60.240]) by gerste.heinlein-support.de (gerste.heinlein-support.de [91.198.250.173]) (amavisd-new, port 10030) with ESMTP id eBzxvpKRdShy; Tue, 17 Apr 2018 08:24:28 +0200 (CEST) Message-ID: <1523946266.2329.5.camel@cybertec.at> Subject: Re: To prefer sorts or filters in postgres, that is the question.... From: Laurenz Albe To: Bob Jones , pgsql-general Date: Tue, 17 Apr 2018 08:24:26 +0200 In-Reply-To: References: Organization: Cybertec Content-Type: text/plain; charset="UTF-8" Mime-Version: 1.0 Content-Transfer-Encoding: 7bit List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Bob Jones wrote: > I've been playing around with hierarchical queries a bit and one thing > I wanted to do is build a query that gives the ultimate parent for a > given child. > > The two queries below seem to be a good a shortlist as any. > > I'm no query-plan guru, but these seem to be largely identical aside > from one uses "filter IS NULL" and the other uses "top-N heapsort". > > Would there be a reason to prefer one over the other (or perhaps > there's an altogether more efficient way of doing this query ?!?). > My gut-instinct says the sort version ? The ultimate criterion which one is better is the execution time, but you probably need more data to tell with certainty. At a short glance, I'd say that they are pretty much the same. The filter and the top-1-sort will both require a single scan through the result set and one operation per row found. And the recursive queries are pretty similar, right? Yours, Laurenz Albe -- Cybertec | https://www.cybertec-postgresql.com