cswork / libraryOpen practice workspace

Coding questions · Databricks

Calculate Second-Degree Followers for Each YouTuber

This question evaluates competency in relational data manipulation and graph-style relationship reasoning, including use of joins, aggregation and distinct counting, and is categorized under Data Manipulation (SQL/Python).

following

+----------+----------+
| YouTuber | follower |
+----------+----------+
| A        | B        |
| A        | C        |
| B        | D        |
| C        | E        |
| D        | F        |
+----------+----------+
Scenario

Analyzing a social-network-style following table to compute second-degree followers for each YouTuber.

Question

Write an SQL query that returns, for every YouTuber, the count of distinct second-degree followers (followers of followers) excluding direct followers and the YouTuber themselves.

Hints

Self-join the table: T1.YouTuber→T1.follower→T2.follower; exclude duplicates and direct connections, then group count distinct second-degree followers.

Count Distinct Second-Degree Followers

You are given a social-network-style table following that records which YouTuber follows which other YouTuber. Each row represents a directed follow relationship (YouTuber → follower). Write an SQL query that returns, for every distinct YouTuber in the YouTuber column, the count of distinct second-degree followers (followers of their followers). Exclude any second-degree follower that is also a direct follower of the YouTuber, and also exclude the YouTuber themself. YouTubers with no second-degree followers should still appear with a count of 0.

Table following

columntypeconstraints
YouTuberVARCHAR(50)NOT NULL
followerVARCHAR(50)NOT NULL

Sample data:

YouTuberfollower
AB
AC
BD
CE
DF

Expected output

One row per distinct YouTuber from the YouTuber column, with the number of distinct second-degree followers. Second-degree followers are followers of followers, excluding direct followers and the YouTuber themself. YouTubers with no second-degree followers appear with a count of 0.

YouTubersecond_degree_count
A2
B1
C0
D0

Hints

  1. Self-join the table to traverse YouTuber -> follower -> follower-of-follower.
  2. Use a LEFT JOIN chain and COUNT(DISTINCT ...) to avoid double-counting second-degree followers.
  3. Exclude second-degree candidates that are direct followers or equal to the original YouTuber.