# Slow queries in Discourse

**URL:** <https://meta.discourse.org/t/slow-queries-in-discourse/152494>\
**Category:** Development\
**Created:** [May 24, 2020, 2:47am UTC](https://meta.discourse.org/t/slow-queries-in-discourse/152494 "2020-05-24T02:47:11Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![wtune](https://avatars.discourse-cdn.com/v4/letter/w/8dc957/32.png) [@wtune](https://meta.discourse.org/u/wtune)\
**Post date:** [May 25, 2020, 7:29am UTC](https://meta.discourse.org/t/slow-queries-in-discourse/152494/4 "2020-05-25T07:29:10Z")

</div>

We run specs in discourse, and from Database we find a slow query((6480259 nanosecond) compared with similar query) with unnecessary DISTINCT produced by  
[site\_settings\_controller.rb#L141](https://github.com/discourse/discourse/blob/61d8955fcb165d2a55760279928306b47fb98898/app/controllers/admin/site_settings_controller.rb#L141)as follows:

```plaintext
SELECT 
  DISTINCT users.id 
FROM 
  "users" CROSS 
  JOIN tags t 
  LEFT JOIN tag_users tu ON users.id = tu.user_id 
  AND t.id = tu.tag_id 
WHERE 
  (
    t.id IN (1825) 
    AND tu.notification_level IS NULL
  )

```

When tags.id and notification\_level are specify value, because of UNIQUE (tag\_id, user\_id, notification\_level) in tag\_users and PRIMARY KEY(id) in tags, both cross join and left join will not create duplicate  
records which means that we can remove DISTINCT to accelerate query.  
This opt query take 4538891 nanosecond(improve 30%)

---

_[View the full topic](https://meta.discourse.org/t/slow-queries-in-discourse/152494)._
