Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1gdPr1-0002Lm-2D for pgsql-performance@arkaria.postgresql.org; Sun, 30 Dec 2018 01:25:23 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1gdPqx-0004NE-O1 for pgsql-performance@arkaria.postgresql.org; Sun, 30 Dec 2018 01:25:19 +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_SHA1:256) (Exim 4.89) (envelope-from ) id 1gdPqx-0004Ge-ER for pgsql-performance@lists.postgresql.org; Sun, 30 Dec 2018 01:25:19 +0000 Received: from n3.nabble.com ([162.255.23.22]) by magus.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1gdPqq-00075v-60 for pgsql-performance@postgresql.org; Sun, 30 Dec 2018 01:25:18 +0000 Received: from n3.nabble.com (localhost [127.0.0.1]) by n3.nabble.com (Postfix) with ESMTP id EE90F111B9AFA for ; Sat, 29 Dec 2018 18:25:09 -0700 (MST) Date: Sat, 29 Dec 2018 18:25:09 -0700 (MST) From: Jim Finnerty To: pgsql-performance@postgresql.org Message-ID: <1546133109941-0.post@n3.nabble.com> In-Reply-To: References: Subject: Re: Need help with optimising simple query MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk I didn't find any CREATE TABLE's in your description, or else I would have tried it with the sequences and all that, but I think this ought to work. postgres=# explain select * from ((select * from parent inner join child on parent.child_id = child.id limit 10) union all (select * from parent left outer join child on parent.child_id = child.id where child.id is null limit 10)) as v limit 10; QUERY PLAN --------------------------------------------------------------------------------------------------------- Limit (cost=0.15..3.72 rows=10 width=88) -> Append (cost=0.15..7.29 rows=20 width=88) -> Limit (cost=0.15..2.46 rows=10 width=88) -> Nested Loop (cost=0.15..246.54 rows=1070 width=88) -> Seq Scan on parent (cost=0.00..20.70 rows=1070 width=48) -> Index Scan using child_pkey on child (cost=0.15..0.21 rows=1 width=40) Index Cond: (id = parent.child_id) -> Limit (cost=0.15..4.63 rows=10 width=88) -> Nested Loop Anti Join (cost=0.15..239.71 rows=535 width=88) -> Seq Scan on parent parent_1 (cost=0.00..20.70 rows=1070 width=48) -> Index Scan using child_pkey on child child_1 (cost=0.15..0.21 rows=1 width=40) Index Cond: (parent_1.child_id = id) (12 rows) ----- Jim Finnerty, AWS, Amazon Aurora PostgreSQL -- Sent from: http://www.postgresql-archive.org/PostgreSQL-performance-f2050081.html