diff --git a/phpBB/phpbb/db/migration/data/v33x/remove_non_existant_assigned_roles.php b/phpBB/phpbb/db/migration/data/v33x/remove_non_existant_assigned_roles.php
new file mode 100644
index 0000000000..477825c53d
--- /dev/null
+++ b/phpBB/phpbb/db/migration/data/v33x/remove_non_existant_assigned_roles.php
@@ -0,0 +1,72 @@
+<?php
+/**
+*
+* This file is part of the phpBB Forum Software package.
+*
+* @copyright (c) phpBB Limited <https://www.phpbb.com>
+* @license GNU General Public License, version 2 (GPL-2.0)
+*
+* For full copyright and license information, please see
+* the docs/CREDITS.txt file.
+*
+*/
+
+namespace phpbb\db\migration\data\v33x;
+
+class remove_non_existant_assigned_roles extends \phpbb\db\migration\migration
+{
+	static public function depends_on()
+	{
+		return ['\phpbb\db\migration\data\v33x\v335',];
+	}
+
+	public function update_data()
+	{
+		return [
+			['custom', [[$this, 'remove_non_existant_roles_assignment']]],
+		];
+	}
+
+	public function remove_non_existant_roles_assignment()
+	{
+		$auth_role_ids = $role_ids = $auth_settings = [];
+
+		$sql = 'SELECT auth_role_id
+			FROM ' . ACL_GROUPS_TABLE . '
+			WHERE auth_role_id <> 0
+				AND forum_id = 0';
+		$result = $this->db->sql_query($sql);
+		$auth_role_ids = array_keys($this->db->sql_fetchrowset($result));
+		$this->db->sql_freeresult($result);
+
+		if (count($auth_role_ids))
+		{
+			$sql = 'SELECT role_id
+				FROM ' . ACL_ROLES_TABLE . '
+				WHERE ' . $this->db->sql_in_set('role_id', $auth_role_ids);
+			$result = $this->db->sql_query($sql);
+			$role_ids = array_keys($this->db->sql_fetchrowset($result));
+			$this->db->sql_freeresult($result);
+		}
+
+		$non_existant_role_ids = array_diff($auth_role_ids, $role_ids);
+
+		// Nothing to do, there are no non-existant roles assigned to groups
+		if (empty($non_existant_role_ids))
+		{
+			return true;
+		}
+
+		// Remove assigned non-existant roles from users and groups
+		$sql = 'DELETE FROM ' . ACL_USERS_TABLE . '
+			WHERE ' . $this->db->sql_in_set('auth_role_id', $non_existant_role_ids);
+		$this->db->sql_query($sql);
+
+		$sql = 'DELETE FROM ' . ACL_GROUPS_TABLE . '
+			WHERE ' . $this->db->sql_in_set('auth_role_id', $non_existant_role_ids);
+		$this->db->sql_query($sql);
+
+		$auth = new \phpbb\auth\auth();
+		$auth->acl_clear_prefetch();
+	}
+}