sqldataexplorer

SEDE Data Query to find posts that have hidden comments added by me


Preface

I have developed a browser extension which is useful for stackexchange community users. It helps identify important or relevant information on any post based on their previous activity - It's called Stack Me First, do check it out if interested

One of the features it has is to identify if there are any comments/answers added by the user in the current post which are hidden by pagination.

Question

Now I want to create a Data Query to find any such post which could have hidden comments and return those questions so that I can add this query in my documentation to help the user in getting started with using the extension.

To be honest, I would like to get this done using Stack Exchange API, but I don't think it's possible.


I know we can use below query to fetch posts that I have commented on, but I want to improve this query by looking for posts with hidden comments

SELECT id, creationdate, text, postid AS [Post Link]
FROM Comments
WHERE UserId = '736172'

Solution

  • To get the number of comments, you just need to add one line to the SELECT. As a result, the query will look like this:

    SELECT 
      id, 
      creationdate, 
      text, 
      postid AS [Post Link],
      (SELECT COUNT(*) FROM Comments AS c WHERE Comments.PostId = c.PostId) AS total_comments
    FROM Comments
    WHERE UserId = 736172
    ORDER BY Id
    

    Well, I found this post that describes the algorithm for displaying comments under a post. I wrote a query that does what is needed: finds all comments of a certain user if they are hidden by pagination and adds the total number of comments under the post. The final query looks like this:

    WITH posts_with_user_comment AS (
      SELECT
        Posts.Id AS PostId
      FROM
        Posts
      WHERE
        EXISTS (
          SELECT
            1
          FROM
            Comments
          WHERE
            UserId = ##UserId##
            AND Comments.PostId = Posts.Id
        )
    ),
    
    all_comments_under_post AS (
      SELECT
        Comments.*
      FROM
        posts_with_user_comment
      JOIN
        Comments
      ON
        Comments.PostId = posts_with_user_comment.PostId
    )
    
    SELECT
      t.*,
      t.PostId AS [Post Link]
    FROM (
      SELECT
        *,
        rank() over(PARTITION BY PostId ORDER BY Score DESC, CreationDate ASC) AS rnk,
        count(*) over(PARTITION BY PostId) AS total_post_comments
      FROM
        all_comments_under_post
    ) AS t
    WHERE
      t.UserId = ##UserId##
      AND rnk > 5
    ORDER BY
      PostId DESC
    ;