diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml
index 8a66ce7..d99945d 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>
+         The autocommit cannot be set to on inside a transaction, the ongoing
+         transaction has to be ended by entering <command>COMMIT</> or
+         <command>ROLLBACK</> before setting autocommit to on.
+        </para>
+        </note>
 
         <note>
         <para>
diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index a9a2fdb..64b0cd5 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -1308,7 +1308,14 @@ exec_command(const char *cmd,
 				free(opt);
 			}
 
-			if (!SetVariable(pset.vars, opt0, newval))
+			if (!strcmp(opt0,"AUTOCOMMIT") && ParseVariableBool(newval,
+				"AUTOCOMMIT") && PQtransactionStatus(pset.db) == PQTRANS_INTRANS)
+			{
+				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;
