Fix permalinks to point to topic-url and not to first post of topic

After a customized migration many permalinks were pointing to the first post in a topic instead of the topic-url itself.

e.g. permalinks pointing to

instead of


A Discourse forum is affected if there are records for this SQL query:

SELECT permalinks.*,,
FROM permalinks
         LEFT JOIN posts
                   ON = permalinks.post_id
WHERE permalinks.post_id IS NOT NULL
  AND posts.post_number = 1

Quick Fix

This changes permalinks to directly point to the topic, if they were originally pointing to the first post in topic.

UPDATE permalinks
SET topic_id = posts.topic_id,
    post_id  = NULL
FROM posts
WHERE permalinks.post_id =
  AND permalinks.post_id IS NOT NULL
  AND posts.post_number = 1;

This might be a good cleanup routine to run at the end of migration scripts.

1 Like

How did you create the permalinks?

For example, here discourse/vanilla_mysql.rb at main · discourse/discourse · GitHub they specifically check the post number, if it’s 1, then the post_is not passed (left as NULL) and thus the permalink shouldn’t point to the first post.


I did a SQL based approach on permalinks based on some code similar to

… but with AND post_number <> 1 missing – so that was the culprit.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.