diff --git src/bin/pg_dump/pg_dump_sort.c src/bin/pg_dump/pg_dump_sort.c
index d2b0949d6b..79df0e87cc 100644
--- src/bin/pg_dump/pg_dump_sort.c
+++ src/bin/pg_dump/pg_dump_sort.c
@@ -230,11 +230,7 @@ DOTypeNameCompare(const void *p1, const void *p2)
 	if (cmpval != 0)
 		return cmpval;
 
-	/*
-	 * Sort by namespace.  Note that all objects of the same type should
-	 * either have or not have a namespace link, so we needn't be fancy about
-	 * cases where one link is null and the other not.
-	 */
+	/* Sort by namespace */
 	if (obj1->namespace && obj2->namespace)
 	{
 		cmpval = strcmp(obj1->namespace->dobj.name,
@@ -242,6 +238,11 @@ DOTypeNameCompare(const void *p1, const void *p2)
 		if (cmpval != 0)
 			return cmpval;
 	}
+	else if (obj1->namespace || obj2->namespace)
+	{
+		/* NULL namespace sorts first. */
+		return obj1->namespace ? 1 : -1;
+	}
 
 	/* Sort by name */
 	cmpval = strcmp(obj1->name, obj2->name);
