The Number of Comments per Post SQL problem asks you to count the number of comments for each post. Posts and comments are in the same Submissions table, where comments have a non-NULL parent_id pointing to their parent post. For each post (parent_id IS NULL), count how many direct comments it has. Posts with no comments should show 0. This is a self-join or GROUP BY with LEFT JOIN problem.
Meta asks this to test hierarchical data querying in SQL — a common pattern in social media and forum databases. It validates knowledge of self-referencing tables, LEFT JOIN for zero-count handling, and proper NULL filtering. The database interview pattern is directly demonstrated.
LEFT JOIN + GROUP BY with NULL handling. Join the posts (parent_id IS NULL) with comments (parent_id IS NOT NULL) on post.sub_id = comment.parent_id. Group by post.sub_id and count comments. Use COALESCE to return 0 for posts with no comments.
SELECT p.sub_id AS post_id, COUNT(c.sub_id) AS number_of_comments
FROM Submissions p
LEFT JOIN Submissions c ON p.sub_id = c.parent_id
WHERE p.parent_id IS NULL
GROUP BY p.sub_id
ORDER BY p.sub_id
Submissions: (1, NULL), (2, 1), (3, 1), (4, NULL), (5, 4), (6, 6) (self-ref, skip). Posts: IDs 1, 4. Comments of post 1: IDs 2, 3. Comments of post 4: ID 5. Result: post 1 → 2 comments, post 4 → 1 comment.
Hierarchical self-referencing table queries use a self-JOIN pattern: join the same table twice, once for parents and once for children. Always use LEFT JOIN to preserve parent rows with no children, and COUNT(child_column) (not COUNT(*)) to correctly return 0 for empty groups. This pattern appears in org chart queries, thread/reply systems, and category/subcategory hierarchies.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Ads Performance | Easy | Solve | |
| Find Books with No Available Copies | Easy | Solve | |
| Friend Requests I: Overall Acceptance Rate | Easy | Solve | |
| Project Employees II | Easy | Solve | |
| Reported Posts | Easy | Solve |