From af3009cfef4f8750ac9a07a190db32f9c0fc7863 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@enterprisedb.com>
Date: Wed, 14 Mar 2018 12:32:37 +1300
Subject: [PATCH] Fix performance regression in REFRESH MATERIALIZED VIEW
 CONCURRENTLY.

Jeff Janes discovered that commit 7ca25b7de6aefa5537e0dbe56541bc41c0464f97
had made one of the queries run by REFRESH MATERIALIZED VIEW CONCURRENTLY
perform badly.  The root cause is bad cardinality estimation for correlated
quals, but a principled solution to that problem is some way off.  In this
case we don't expect the join to produce any rows so the whole join will run
to completion.  By removing the LIMIT clause, we can avoid a nested loop join
that would otherwise be chosen for its low startup cost.

Thomas Munro and Tom Lane
Discussion: https://postgr.es/m/CAMkU%3D1z-JoGymHneGHar1cru4F1XDfHqJDzxP_CtK5cL3DOfmg%40mail.gmail.com
---
 src/backend/commands/matview.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/backend/commands/matview.c b/src/backend/commands/matview.c
index ab6a889b129..e828f2bff58 100644
--- a/src/backend/commands/matview.c
+++ b/src/backend/commands/matview.c
@@ -660,7 +660,7 @@ refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,
 					 "(SELECT * FROM %s newdata2 WHERE newdata2 IS NOT NULL "
 					 "AND newdata2 OPERATOR(pg_catalog.*=) newdata "
 					 "AND newdata2.ctid OPERATOR(pg_catalog.<>) "
-					 "newdata.ctid) LIMIT 1",
+					 "newdata.ctid)",
 					 tempname, tempname);
 	if (SPI_execute(querybuf.data, false, 1) != SPI_OK_SELECT)
 		elog(ERROR, "SPI_exec failed: %s", querybuf.data);
-- 
2.16.2

