diff --git a/src/backend/commands/cluster.c b/src/backend/commands/cluster.c
index dc967390ba6..2d2ac3e8940 100644
--- a/src/backend/commands/cluster.c
+++ b/src/backend/commands/cluster.c
@@ -11,7 +11,7 @@
  *
  *
  * IDENTIFICATION
- *	  $PostgreSQL: pgsql/src/backend/commands/cluster.c,v 1.195 2010/01/28 23:21:11 petere Exp $
+ *	  $PostgreSQL: pgsql/src/backend/commands/cluster.c,v 1.196 2010/02/02 19:12:29 tgl Exp $
  *
  *-------------------------------------------------------------------------
  */
@@ -657,20 +657,25 @@ rebuild_relation(Relation OldHeap, Oid indexOid,
 	newrel = heap_open(tableOid, NoLock);
 	if (OidIsValid(newrel->rd_rel->reltoastrelid))
 	{
-		char		NewToastName[NAMEDATALEN];
 		Relation	toastrel;
+		Oid			toastidx;
+		Oid			toastnamespace;
+		char		NewToastName[NAMEDATALEN];
+
+		toastrel = relation_open(newrel->rd_rel->reltoastrelid, AccessShareLock);
+		toastidx = toastrel->rd_rel->reltoastidxid;
+		toastnamespace = toastrel->rd_rel->relnamespace;
+		relation_close(toastrel, AccessShareLock);
 
 		/* rename the toast table ... */
 		snprintf(NewToastName, NAMEDATALEN, "pg_toast_%u", tableOid);
 		RenameRelationInternal(newrel->rd_rel->reltoastrelid, NewToastName,
-							   PG_TOAST_NAMESPACE);
+							   toastnamespace);
 
 		/* ... and its index too */
-		toastrel = relation_open(newrel->rd_rel->reltoastrelid, AccessShareLock);
 		snprintf(NewToastName, NAMEDATALEN, "pg_toast_%u_index", tableOid);
-		RenameRelationInternal(toastrel->rd_rel->reltoastidxid, NewToastName,
-							   PG_TOAST_NAMESPACE);
-		relation_close(toastrel, AccessShareLock);
+		RenameRelationInternal(toastidx, NewToastName,
+							   toastnamespace);
 	}
 	relation_close(newrel, NoLock);
 }
diff --git a/src/test/regress/expected/cluster.out b/src/test/regress/expected/cluster.out
index 9bf4764b689..23d0a3cd509 100644
--- a/src/test/regress/expected/cluster.out
+++ b/src/test/regress/expected/cluster.out
@@ -434,6 +434,18 @@ SELECT * FROM clustertest;
  100
 (5 rows)
 
+-- check that temp tables can be clustered
+create temp table clstr_temp (col1 int primary key, col2 text);
+NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "clstr_temp_pkey" for table "clstr_temp"
+insert into clstr_temp values (2, 'two'), (1, 'one');
+cluster clstr_temp using clstr_temp_pkey;
+select * from clstr_temp;
+ col1 | col2 
+------+------
+    1 | one
+    2 | two
+(2 rows)
+
 -- clean up
 \c -
 DROP TABLE clustertest;
diff --git a/src/test/regress/sql/cluster.sql b/src/test/regress/sql/cluster.sql
index a54d6e07f50..f3f7a248100 100644
--- a/src/test/regress/sql/cluster.sql
+++ b/src/test/regress/sql/cluster.sql
@@ -187,6 +187,12 @@ COMMIT;
 
 SELECT * FROM clustertest;
 
+-- check that temp tables can be clustered
+create temp table clstr_temp (col1 int primary key, col2 text);
+insert into clstr_temp values (2, 'two'), (1, 'one');
+cluster clstr_temp using clstr_temp_pkey;
+select * from clstr_temp;
+
 -- clean up
 \c -
 DROP TABLE clustertest;