# Delete all users not in a specific group

**URL:** https://meta.discourse.org/t/delete-all-users-not-in-a-specific-group/198804
**Category:** Support
**Created:** [August 1, 2021, 9:55am UTC](https://meta.discourse.org/t/delete-all-users-not-in-a-specific-group/198804 "2021-08-01T09:55:09Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![nathank](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/nathank/32/290039_2.png) [@nathank](https://meta.discourse.org/u/nathank)
#### Post date: [August 20, 2021, 10:02pm UTC](https://meta.discourse.org/t/delete-all-users-not-in-a-specific-group/198804/2 "2021-08-20T22:02:04Z")

</div>

Answering my own question, having learned a few lessons.

1. Yes, use `UserDestroyer` or your database will be littered with orphaned records.
2. You might need to be clever about how you gather your unwanted users. I used this [Data Explorer](https://meta.discourse.org/t/32566?silent=true) query to get a list of them, which I then bulk added them to a group called `unwanted`

```plaintext
WITH included_users AS (
SELECT
gu.user_id
FROM group_users gu
JOIN groups g
ON g.id = gu.group_id
WHERE g.name = :included_group
),

excluded_users AS (
SELECT
gu.user_id
FROM group_users gu
JOIN groups g
ON g.id = gu.group_id
WHERE g.name = :excluded_group
)

SELECT 
     u.id AS user_id, u.username
FROM users as u
WHERE u.id in (SELECT user_id FROM included_users)
AND u.id NOT IN (SELECT user_id FROM excluded_users)
GROUP by u.id

```

## How to destroy a lot of users:

Enter the Discourse app (`./launcher enter app`, etc) and run these:

```plaintext
rails c
 target_group = Group.find_by_name("unwanted")
 users = User.joins(:group_users).where(group_users:{group_id: target_group.id})
 users.each do |u|
  u.admin = false
  u.moderator = false
  u.save
  UserDestroyer.new(Discourse.system_user).destroy(u, delete_posts: true)
 end
Exit

```

It isn’t fast. For 6000 users it took 2 hours.

---

_[View the full topic](https://meta.discourse.org/t/delete-all-users-not-in-a-specific-group/198804)._
