# Need some help with a bit of Badge SQL please

**URL:** <https://meta.discourse.org/t/need-some-help-with-a-bit-of-badge-sql-please/212430>\
**Category:** Product Support\
**Created:** [December 17, 2021, 12:00pm UTC](https://meta.discourse.org/t/need-some-help-with-a-bit-of-badge-sql-please/212430 "2021-12-17T12:00:35Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![Richie](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/richie/32/115110_2.png) [@Richie](https://meta.discourse.org/u/Richie)\
**Post date:** [December 17, 2021, 12:00pm UTC](https://meta.discourse.org/t/need-some-help-with-a-bit-of-badge-sql-please/212430/1 "2021-12-17T12:00:35Z")

</div>

Hi everyone,

I have some badge SQL which issues a badge depending on the number of _new_ topics created in a specific category which also and containing a specific phrase (a specific url) in the first post of the topic.

It works, but not quite as intended:

```plaintext
SELECT badge_posts.user_id, min(badge_posts.created_at) granted_at, MIN(badge_posts.id) AS post_id
FROM badge_posts
JOIN topics ON topics.id = badge_posts.topic_id
WHERE category_id = 17
AND badge_posts.post_number = 1 
AND badge_posts.raw LIKE '%dronescene.co.uk%' 
GROUP BY badge_posts.user_id
HAVING COUNT(*) > 49
ORDER BY post_id DESC
```

I have four badges available, bronze, silver, gold, platinum and I use things like `HAVING count(*) > 1` for the bronze and `HAVING count(*) > 10` for the silver, etc. The badges all get issued automatically, no problems there.

The problem I do seem to be having is that all the badges are issued for the first topic ID in that category, instead of the last topic id.

For example, I have a member with three badges and all three badges have been issued against the same first topic they made that match my `WHERE` clause, instead of for the very latest topic id that matches the `WHERE` clause.

Can someone let me know what I’m doing wrong with my `ORDER BY`’s ? 🤔

---

_[View the full topic](https://meta.discourse.org/t/need-some-help-with-a-bit-of-badge-sql-please/212430)._
