Social Network Feed Analytics with SQL Aggregation
SQL & DataAuto-gradedLast updated
Build SQL queries to analyze user engagement patterns across friend and non-friend content, handling temporal aggregation and interaction scoring.
You're analyzing engagement metrics for a social platform. The database contains user activity across posts, feed views, and interactions.
Schema (PostgreSQL):
users(user_id INT, join_date DATE)
friendships(user_id INT, friend_id INT) -- bidirectional; both edges stored
posts(post_id INT, author_id INT, created_at TIMESTAMP)
feed_impressions(imp_id INT, user_id INT, post_id INT, impression_ts TIMESTAMP)
interactions(int_id INT, user_id INT, post_id INT, type VARCHAR, interaction_ts TIMESTAMP)
-- type is one of: 'like', 'comment', 'share'
Sample Data:
users: (1, '2025-06-01'), (2, '2025-06-15'), (3, '2025-07-01')
friendships: (1,2), (2,1)
posts: (10, 2, '2025-08-01 10:00'), (11, 3, '2025-08-01 11:00'),
(12, 2, '2025-08-02 09:00'), (13, 3, '2025-07-15 08:00')
feed_impressions:
(100, 1, 10, '2025-08-01 10:05'), (101, 1, 11, '2025-08-01 11:05'),
(102, 1, 12, '2025-08-02 09:10'), (103, 2, 11, '2025-08-01 12:00'),
(104, 1, 13, '2025-07-15 08:05')
interactions:
(200, 1, 10, 'like', '2025-08-01 10:06'), (201, 1, 11, 'comment', '2025-08-01 11:06'),
(202, 1, 12, 'share', '2025-08-02 09:12'), (203, 2, 11, 'like', '2025-08-01 12:05'),
(204, 1, 13, 'like', '2025-07-15 08:06')
Write SQL queries for each task:
1. Daily Content Source Distribution
For each viewer and calendar date, calculate what proportion of their feed views came from friends versus non-friends. Tag each impression by checking if the post author is connected to the viewer via the friendships table.
2. Engagement Score by Content Origin
Calculate a weighted engagement metric per (viewer, date, content_origin) where content_origin is 'friend' or 'unconnected'. Use these weights: like=1, comment=3, share=5. Count all interaction types separately and compute the total weighted value. Feed views with no corresponding interaction contribute zero.
3. Daily Top Posts per User
For the date '2025-08-01', identify each user's top 2 posts by their engagement score (same weighting). Use DENSE_RANK() to include all ties at the boundary rank. Within ties, sort by post_id ascending for display.
4. Monthly Growth Analysis
Calculate month-over-month percentage change in total engagement score by content origin, comparing July 2025 to August 2025. Generate a complete calendar of months and handle cases where a month has no activity by treating it as zero score. Clearly state your handling of division by zero.
For all queries, assume UTC timestamps. Be precise about aggregation levels—ensure viewer-day grain where specified, not post-level.
Hints
Hint 1
When classifying impressions by relationship, use EXISTS rather than LEFT JOIN to avoid accidentally duplicating rows if the friendships table has unexpected entries.
Hint 2
A viewer might see the same post multiple times in one day and interact with it once. Pre-aggregate interactions to (viewer, post, date) grain before joining to impressions to avoid counting interactions multiple times.
Hint 3
For month-over-month calculations with sparse data, generate a complete calendar with CROSS JOIN to ensure both content types appear in both months, even if they had zero activity.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is managing aggregation grain correctly across multiple joins. Three principles guide the solution:
1. Relationship classification must not duplicate rows
Use EXISTS to tag each impression as friend-sourced or not. A LEFT JOIN on friendships could silently multiply rows if there are duplicate entries.
2. Interaction aggregation happens first
Pre-aggregate interactions to (viewer, post, date) before joining to impressions. If a viewer sees post X twice on Monday and likes it once, a naive join creates two rows, double-counting the like.
3. Final aggregation matches the requested unit
Most tasks ask for viewer-day summaries, not per-post metrics. Post appears as a grouping key in intermediate CTEs but is summed away in the final output.
Building Blocks (Common CTEs)
WITH impressions_tagged AS (
SELECT
fi.imp_id,
fi.user_id,
fi.post_id,
DATE(fi.impression_ts) AS view_date,
CASE
WHEN EXISTS (
SELECT 1
FROM friendships f
WHERE f.user_id = fi.user_id
AND f.friend_id = p.author_id
) THEN 'friend'
ELSE 'unconnected'
END AS content_origin
FROM feed_impressions fi
JOIN posts p ON p.post_id = fi.post_id
),
interactions_daily AS (
SELECT
user_id,
post_id,
DATE(interaction_ts) AS interaction_date,
COUNT(*) FILTER (WHERE type = 'like') AS like_count,
COUNT(*) FILTER (WHERE type = 'comment') AS comment_count,
COUNT(*) FILTER (WHERE type = 'share') AS share_count
FROM interactions
GROUP BY user_id, post_id, DATE(interaction_ts)
)
The content_origin is determined purely by (viewer, author), so it's safe to group by it alongside post_id without splitting related rows.
Task 1: Content Source Distribution
SELECT
user_id,
view_date,
COUNT(*) AS total_impressions,
ROUND(AVG((content_origin = 'friend')::INT)::NUMERIC, 4) AS friend_fraction,
ROUND(AVG((content_origin = 'unconnected')::INT)::NUMERIC, 4) AS unconnected_fraction
FROM impressions_tagged
GROUP BY user_id, view_date
ORDER BY user_id, view_date;
Converting booleans to integers and taking AVG yields the fraction directly, avoiding integer division pitfalls.
Expected output:
- User 1 on 2025-08-01: 2 impressions, 50% from friends (post 10 from user 2)
- User 1 on 2025-08-02: 1 impression, 100% from friends (post 12 from user 2)
Task 2: Weighted Engagement Scoring
WITH viewer_post_day AS (
SELECT
i.user_id,
i.post_id,
i.view_date,
i.content_origin,
COUNT(*) AS impression_count
FROM impressions_tagged i
GROUP BY i.user_id, i.post_id, i.view_date, i.content_origin
),
scored AS (
SELECT
v.*,
COALESCE(ix.like_count, 0) AS likes,
COALESCE(ix.comment_count, 0) AS comments,
COALESCE(ix.share_count, 0) AS shares,
COALESCE(
ix.like_count * 1 + ix.comment_count * 3 + ix.share_count * 5,
0
) AS engagement_score
FROM viewer_post_day v
LEFT JOIN interactions_daily ix
ON v.user_id = ix.user_id
AND v.post_id = ix.post_id
AND v.view_date = ix.interaction_date
)
SELECT
user_id,
view_date,
content_origin,
SUM(impression_count) AS total_impressions,
SUM(likes) AS total_likes,
SUM(comments) AS total_comments,
SUM(shares) AS total_shares,
SUM(engagement_score) AS weighted_engagement
FROM scored
GROUP BY user_id, view_date, content_origin
ORDER BY user_id, view_date, content_origin;
The LEFT JOIN with COALESCE ensures impressions without interactions contribute a score of zero rather than being excluded.
Task 3: Top Posts with Tie Handling
WITH scored AS (
-- (reuse scored CTE from Task 2)
),
ranked_posts AS (
SELECT
user_id,
post_id,
SUM(engagement_score) AS total_score,
DENSE_RANK() OVER (
PARTITION BY user_id
ORDER BY SUM(engagement_score) DESC
) AS rank
FROM scored
WHERE view_date = DATE '2025-08-01'
GROUP BY user_id, post_id
)
SELECT
user_id,
post_id,
total_score,
rank
FROM ranked_posts
WHERE rank <= 2
ORDER BY user_id, rank, post_id;
Critical detail: post_id appears in the final ORDER BY for tie-breaking display but NOT in the DENSE_RANK() ordering clause. Including it there would make every post unique, defeating tie inclusion. User 1 saw posts 10 (score 1) and 11 (score 3) on Aug 1st—both are returned.
Task 4: Month-over-Month Growth
WITH month_series AS (
SELECT DATE_TRUNC('month', d)::DATE AS month
FROM GENERATE_SERIES(
DATE '2025-07-01',
DATE '2025-08-01',
INTERVAL '1 month'
) AS d
),
complete_calendar AS (
SELECT
m.month,
origin.content_origin
FROM month_series m
CROSS JOIN (VALUES ('friend'), ('unconnected')) AS origin(content_origin)
),
monthly_scores AS (
SELECT
DATE_TRUNC('month', view_date)::DATE AS month,
content_origin,
SUM(engagement_score) AS score
FROM scored -- reuse from Task 2
GROUP BY DATE_TRUNC('month', view_date)::DATE, content_origin
),
complete_scores AS (
SELECT
c.month,
c.content_origin,
COALESCE(m.score, 0) AS score
FROM complete_calendar c
LEFT JOIN monthly_scores m USING (month, content_origin)
)
SELECT
month,
content_origin,
score,
ROUND(
100.0 * (score - LAG(score) OVER w) / NULLIF(LAG(score) OVER w, 0),
2
) AS mom_pct_change
FROM complete_scores
WINDOW w AS (PARTITION BY content_origin ORDER BY month)
ORDER BY content_origin, month;
The calendar generation with CROSS JOIN ensures that even if friend content had zero engagement in July, it appears in the result set so August's LAG function has something to compare against. NULLIF prevents division by zero—when the prior month is zero, growth is undefined (NULL) rather than infinity.
Complexity & Trade-offs
- Time: O(impressions + interactions) for base CTEs; window functions add O(n log n) per partition but n is small (2 months × 2 origins)
- Space: Intermediate tables scale with unique (viewer, post, date) combinations
Key assumptions to state:
- Multiple interactions of the same type on one post all count (two comments = 6 points). If the product model treats "like" as a toggle state, deduplicate with
COUNT(DISTINCT ...)or keep only the latest event per type. - Interactions only count if the viewer had an impression on the same UTC calendar day. A like at 00:01 doesn't match an impression at 23:58 the prior day.
- UTC bucketing may misattribute activity for users in distant time zones. For production use, consider bucketing by viewer's local time.