# Updating Likes in \`user\_stats\` in the database via SQL

**URL:** <https://meta.discourse.org/t/updating-likes-in-user-stats-in-the-database-via-sql/135283>\
**Category:** Self-hosting\
**Created:** [4 בדצמבר,‏ 2019,‏ 12:35pm UTC](https://meta.discourse.org/t/updating-likes-in-user-stats-in-the-database-via-sql/135283 "2019-12-04T12:35:02Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![pgr](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pgr/32/156783_2.png) [@pgr](https://meta.discourse.org/u/pgr)\
**Post date:** [4 בדצמבר,‏ 2019,‏ 12:35pm UTC](https://meta.discourse.org/t/updating-likes-in-user-stats-in-the-database-via-sql/135283/1 "2019-12-04T12:35:02Z")

</div>

Hey everyone!

Is there somewhere where I can find a ready-made query to update `likes_given` and `likes_received` in the `user_stats` table? I’m not sure where that is supposed to come from, probably something based on what is in the `user_actions` and `posts` table?

This is for a migration where I’m already using a couple of queries I grabbed from one of the importers, I think:

```sql
UPDATE posts SET like_count = coalesce(cnt,0)
    FROM (
	SELECT post_id, count(*) cnt
	FROM post_actions
	WHERE post_action_type_id = 2 AND deleted_at IS NULL
	GROUP BY post_id
) x
WHERE posts.like_count <> x.cnt AND posts.id = x.post_id

```

```sql
UPDATE topics SET like_count = coalesce(cnt,0)
  FROM (
	SELECT topic_id, sum(like_count) cnt
	FROM posts
	WHERE deleted_at IS NULL
	GROUP BY topic_id
  ) x
WHERE topics.like_count <> x.cnt AND topics.id = x.topic_id

```

That updates the Like counts in `posts` and `topics`, but not in `users_stats`…

---

_[View the full topic](https://meta.discourse.org/t/updating-likes-in-user-stats-in-the-database-via-sql/135283)._
