cswork / libraryOpen practice workspace

Coding questions · Meta

Posts and Replies Engagement

This question tests practical SQL skills, specifically the use of LEFT JOIN and aggregate functions to compute engagement metrics across relational tables. It evaluates a data scientist's ability to handle zero-count rows and filter results using set-based logic, competencies commonly assessed in data manipulation interviews.

A content platform stores user-generated posts and the replies that those posts receive. You need to answer two questions about reply engagement.

Tables

posts

columntypedescription
post_idINTEGERPrimary key. Unique id of the post.
author_idINTEGERId of the user who created the post.
created_atTIMESTAMPWhen the post was created (UTC).

replies

columntypedescription
reply_idINTEGERPrimary key. Unique id of the reply.
post_idINTEGERForeign key referencing posts.post_id. The post replied to.
author_idINTEGERId of the user who wrote the reply.
created_atTIMESTAMPWhen the reply was created (UTC).

Notes / assumptions:

  • A post may have zero, one, or many replies.
  • replies.post_id always references an existing row in posts.
  • A user may reply to their own post.
  • All timestamps are in UTC.

Part 1 — Reply count per post

Return every post together with the number of replies it has received. Posts with zero replies must still appear, with a reply count of 0.

Output columns, in this exact order:

columntypedescription
post_idINTEGERThe post id.
reply_countINTEGERNumber of replies for that post.

Order the result by reply_count descending, breaking ties by post_id ascending.

Part 2 — Posts with no replies

Return the post_id of every post that has received no replies at all.

Output column:

columntypedescription
post_idINTEGERId of a post that has zero replies.

Order the result by post_id ascending.

Posts and Replies Engagement

Table posts

columntypeconstraints
post_idINTEGERPRIMARY KEY
author_idINTEGER
created_atTIMESTAMP

Sample data:

author_idcreated_atpost_id
1002026-01-01 09:00:001
1012026-01-01 10:00:002
1002026-01-02 08:30:003
1022026-01-02 12:00:004
1032026-01-03 15:45:005

Table replies

columntypeconstraints
reply_idINTEGERPRIMARY KEY
post_idINTEGER
author_idINTEGER
created_atTIMESTAMP

Sample data:

author_idcreated_atpost_idreply_id
1012026-01-01 09:15:0011000
1022026-01-01 09:20:0011001
1002026-01-01 09:25:0011002
1002026-01-01 10:05:0021003
1032026-01-01 10:10:0021004
1012026-01-02 12:30:0041005

Expected output

post_idreply_count
13
22
41
30
50

Hints

  1. Use a LEFT JOIN from posts to replies so that posts with no matching replies are still kept.
  2. COUNT(replies.reply_id) counts only non-NULL reply rows, so posts with zero replies get a count of 0 (COUNT(*) would wrongly return 1).
  3. GROUP BY posts.post_id, then ORDER BY reply_count DESC, post_id ASC.
  4. Part 2 (no replies): filter the LEFT JOIN with WHERE replies.reply_id IS NULL, or use NOT EXISTS / a subquery, then order by post_id.