diff --git a/lib/modules/Sql.pmod/pgsql_util.pmod b/lib/modules/Sql.pmod/pgsql_util.pmod
index 9cede304cfdcd58ff935ab7880eb93f5e939dc3e..57b9f6ccd7ff007f44d6d265493f10cf1dc63d2d 100644
--- a/lib/modules/Sql.pmod/pgsql_util.pmod
+++ b/lib/modules/Sql.pmod/pgsql_util.pmod
@@ -1784,7 +1784,7 @@ class proxy {
   final int _fetchlimit = FETCHLIMIT;
   final MUTEX unnamedportalmux;
   final MUTEX unnamedstatement;
-  private Thread.MutexKey termlock;
+  private Thread.MutexKey|int termlock;
   final Thread.ResourceCount portalsinflight, statementsinflight;
   final int(0..1) wasparallelisable;
   final int(0..1) intransaction;
@@ -1960,7 +1960,7 @@ class proxy {
       if (catch(cs = ci->start())) {
         destruct(waitforauthready);
         unnamedstatement = 0;
-        termlock = 0;
+        termlock = 1;
         return;
       } else {
         CHAIN(cs)->add_hstring(plugbuffer, 4, 4);
@@ -2668,13 +2668,13 @@ class proxy {
       portal->_purgeportal();
     }
     destruct(waitforauthready);
-    termlock = 0;
+    termlock = 1;
     if (err && !stringp(err))
       throw(err);
     };
     catch {
-     unnamedstatement = 0;
-     termlock = 0;
+      unnamedstatement = 0;
+      termlock = 1;
       if (err) {
         PD("Terminating processloop due to %s\n", describe_backtrace(err));
         delayederror = err;
@@ -2688,7 +2688,7 @@ class proxy {
     throwdelayederror(this);
     {
       Thread.MutexKey lock;
-      if (unnamedstatement)
+      if (unnamedstatement && !termlock)
         termlock = unnamedstatement->lock(1);
       foreach (c->runningportals; sql_result result; )
         if (result->_state < CLOSED)