diff --git a/mysql-test/include/deadlock.inc b/mysql-test/include/deadlock.inc
index 41c68f393202f16bb7488442cacfb2537b082700..89c34abc87105a48abfabc0893ee67ded3b3eb9b 100644
--- a/mysql-test/include/deadlock.inc
+++ b/mysql-test/include/deadlock.inc
@@ -144,4 +144,29 @@ disconnect con1;
 disconnect con2;
 drop table t1, t2;
 
-# End of 4.1 tests
+--echo End of 4.1 tests
+
+#
+# Bug#25164 create table `a` as select * from `A` hangs
+#
+
+set storage_engine=innodb;
+
+--disable_warnings
+drop table if exists a;
+drop table if exists A;
+--enable_warnings
+
+create table A (c int);
+insert into A (c) values (0);
+--error 0,ER_LOCK_DEADLOCK,ER_UPDATE_TABLE_USED
+create table a as select * from A;
+drop table A;
+
+--disable_warnings
+drop table if exists a;
+--enable_warnings
+
+set storage_engine=default;
+
+--echo End of 5.0 tests.
diff --git a/mysql-test/r/deadlock_innodb.result b/mysql-test/r/deadlock_innodb.result
index a0686d1c844d4c59ee6a6bfbf087057382aeeec5..7a4874d6aab33cd229b7386ba7d3645c432a5c9f 100644
--- a/mysql-test/r/deadlock_innodb.result
+++ b/mysql-test/r/deadlock_innodb.result
@@ -112,3 +112,14 @@ id	x
 commit;
 # Switch to connection default + disconnect con1 and con2
 drop table t1, t2;
+End of 4.1 tests
+set storage_engine=innodb;
+drop table if exists a;
+drop table if exists A;
+create table A (c int);
+insert into A (c) values (0);
+create table a as select * from A;
+drop table A;
+drop table if exists a;
+set storage_engine=default;
+End of 5.0 tests.
diff --git a/sql/lock.cc b/sql/lock.cc
index d9e9dd31f81ea34132d49791693e9b5ee5e169f6..29a07858bc1989360c8a3dfb6d93c7722aa42dbb 100644
--- a/sql/lock.cc
+++ b/sql/lock.cc
@@ -276,6 +276,8 @@ MYSQL_LOCK *mysql_lock_tables(THD *thd, TABLE **tables, uint count,
                                                      thd->lock_id)];
     if (rc > 1)                                 /* a timeout or a deadlock */
     {
+      if (sql_lock->table_count)
+        VOID(unlock_external(thd, sql_lock->table, sql_lock->table_count));
       my_error(rc, MYF(0));
       my_free((uchar*) sql_lock,MYF(0));
       sql_lock= 0;