Detect Self Interactions
Beginner Mode

Scenario

You work at a social media platform and have a table recording interactions between users, where occasionally a user interacts with their own post.

Task

Write a Snowflake SQL query that:

  1. Reads from {{ ref("interactions") }}
  2. Filters to only include rows where a user interacted with themselves (user1_id equals user2_id)
  3. Groups by user and counts the number of self-interactions per user

The output should contain two columns: user_id and self_interaction_count.

Schema

interactions

Column Type Description
interaction_id Integer Unique identifier for the interaction
user1_id Integer ID of the first user in the interaction
user2_id Integer ID of the second user in the interaction
interaction_type String Type of interaction (like, comment, share)
timestamp Date When the interaction occurred

Example

interactions:

interaction_id user1_id user2_id interaction_type timestamp
1 201 305 like 2024-03-01
2 202 202 comment 2024-03-01
3 203 410 share 2024-03-02
4 204 204 like 2024-03-02
5 205 312 comment 2024-03-03

Expected Output:

user_id self_interaction_count
202 1
204 1

Note: Only users 202 and 204 interacted with themselves. Users 201, 203, and 205 interacted with different users and are excluded.

Quick Solution

Code Environment

Sign in or try as guest to run your code.

Sign In

Track

Question Difficulty Company Access
Need more practice in this area? Explore more questions →