# 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:** 3

<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,‏ 1:47pm UTC](https://meta.discourse.org/t/updating-likes-in-user-stats-in-the-database-via-sql/135283/3 "2019-12-04T13:47:40Z")

</div>

I’m using DBeaver, I can use `UPDATE` queries. I assumed “[Data explorer](https://meta.discourse.org/t/32566?silent=true)” was just another equivalent DB client, sorry for my confusion. I guess this doesn’t belong here then, **if an admin wants to split these posts into a separate thread** , that’s ok. I suggest a title like `Updating likes in user_stats via SQL`.

I came up with the following, but I am not sure if they are correct, Id love to check by finding out some place where this is already made by someone more knowledgeable, but I can’t find it 🙁

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

```

```sql
UPDATE user_stats SET likes_received = coalesce(cnt,0)
     FROM (
	SELECT posts.user_id, SUM(posts.like_count) cnt
	FROM post_actions
	LEFT JOIN posts ON post_actions.post_id = posts.id
	WHERE post_action_type_id = 2 AND post_actions.deleted_at IS NULL
	GROUP BY posts.user_id
) x
WHERE user_stats.likes_received <> x.cnt 
       AND user_stats.user_id = x.user_id

```

---

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