# Bulk delete users that match an email pattern

**URL:** https://meta.discourse.org/t/bulk-delete-users-that-match-an-email-pattern/147012
**Category:** Support
**Created:** [April 6, 2020, 4:01pm UTC](https://meta.discourse.org/t/bulk-delete-users-that-match-an-email-pattern/147012 "2020-04-06T16:01:47Z")
**Posts on this page:** 1
**Showing post:** 3

<div class="post-metadata">

### Author: ![xrav3nz](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/xrav3nz/32/76894_2.png) [@xrav3nz](https://meta.discourse.org/u/xrav3nz)
#### Post date: [April 9, 2020, 1:22am UTC](https://meta.discourse.org/t/bulk-delete-users-that-match-an-email-pattern/147012/3 "2020-04-09T01:22:44Z")

</div>

> [@fallais](#):
>
> users that match an email pattern

```ruby
User.joins(:user_emails)
  .where('lower(user_emails.email) LIKE ?', '%domain.com')

```

In particular, the percentage sign (`%`) is a wildard that represents zero or more of any character. So `%domain.com` means emails ending with `domain.com`.

> [@fallais](#):
>
> delete users

Rather than `User#destroy`, it’s best to use the [`UserDestroyer`](https://github.com/discourse/discourse/blob/befaf39aca3af22756a988134245bf1a88a7481d/app/services/user_destroyer.rb):

```ruby
UserDestroyer.new(Discourse.system_user)
  .destroy(user, delete_posts: true)

```

This will have the system user delete the user and all of their posts.

> [@fallais](#):
>
> bulk delete users that match an email pattern

To sum it up:

```ruby
User.joins(:user_emails)
  .where('lower(user_emails.email) LIKE ?', '%domain.com')
  .find_each do |user|
    UserDestroyer.new(Discourse.system_user).destroy(user, delete_posts: true)
  end

```

Be ware that this is irreversable. You may want to verify the users selected by the query before actually deleting them. Also I am unsure of the performance implications if you’re deleting a great number of users and/or if they have a large number of posts.

On another note, not sure if [Anonymizing Users in Discourse](https://meta.discourse.org/t/anonymizing-users-in-discourse/86929) is an alternative for you?

---

_[View the full topic](https://meta.discourse.org/t/bulk-delete-users-that-match-an-email-pattern/147012)._
