diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml
index 8a66ce7..573f61d 100644
--- a/doc/src/sgml/ref/psql-ref.sgml
+++ b/doc/src/sgml/ref/psql-ref.sgml
@@ -3089,6 +3089,14 @@ bar
          without committing, your work will be lost.
         </para>
         </note>
+        
+        <note>
+        <para>
+         Autocommit cannot be set on inside a transaction, the ongoing
+         transaction has to be ended by entering <command>COMMIT</> or
+         <command>ROLLBACK</> before setting autocommit on.
+        </para>
+        </note>
 
         <note>
         <para>
diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index a9a2fdb..914298c 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -1294,7 +1294,9 @@ exec_command(const char *cmd,
 			 */
 			char	   *newval;
 			char	   *opt;
+			PGTransactionStatusType transaction_status;
 
+			transaction_status = PQtransactionStatus(pset.db);
 			opt = psql_scan_slash_option(scan_state,
 										 OT_NORMAL, NULL, false);
 			newval = pg_strdup(opt ? opt : "");
@@ -1308,7 +1310,14 @@ exec_command(const char *cmd,
 				free(opt);
 			}
 
-			if (!SetVariable(pset.vars, opt0, newval))
+			if (transaction_status == PQTRANS_INTRANS && !pset.autocommit &&
+				!strcmp(newval,"ON"))
+			{
+				psql_error("\\%s: Cannot set %s to %s inside a transaction, either COMMIT or ROLLBACK and retry\n",
+							cmd, opt0, newval);
+				success = false;
+			}
+			else if (!SetVariable(pset.vars, opt0, newval))
 			{
 				psql_error("\\%s: error while setting variable\n", cmd);
 				success = false;
