Skip to main content
Back to AcademyπŸ•ΈοΈ 5. Graph Analytics & Fraud Investigation
5 min read
Try Hands-on Lab
VISUAL LESSON5. Graph Analytics & Fraud Investigation

Marketplace Social Graph & Fraud Detection in Relational SQL

You don't always need Neo4j for social graphs & fraud rings! Learn how to traverse multi-hop friendships, eliminate AB/BA mirrored duplicates with LEAST/GREATEST, and flag shared-account fraud using pure SQL.

SQL Graph TraversalFriend of a Friend SQL QueryEliminate Mirrored Pairs LEAST GREATESTFraud Detection Entity Resolution SQLNetwork Centrality SQLAnti-Join Recommendation Query

Explain Like I'm New: Degrees of Separation & Fraud Ring Detective Work

Imagine mapping everyone attending a music festival by who knows whom (friendships), or checking which accounts share the same stolen credit card or device fingerprint (Fraud Ring Detection): - Edges (`friendships`): (Alice -> Bob), (Bob -> Carol), (Alice -> Dave). - Notice a sneaky trap: In undirected social networks, if Alice is friends with Bob, the table often stores two mirrored rows: (Alice, Bob) AND (Bob, Alice)! If you ask *"How many friendships exist?"*, naive counting doubles the real number! - Also notice: Can standard SQL traverse "Friends-of-Friends" (e.g., *Recommend Carol to Alice because Bob connects them*) or spot Ticket Scalper Rings? YES β€” easily, cleanly, and at massive scale!

Key Beginner Takeaway: Before installing a specialized Graph Database, check whether 1–3 hop SQL Self-Joins, `LEAST()` / `GREATEST()` canonical pair deduplication, and `NOT EXISTS` anti-joins solve your graph/fraud problem directly inside your Lakehouse!

Essential Graph SQL Techniques Explained Simply

Graph ProblemSQL Trick That Solves ItWhy It Works
Mirrored Pair Deduplication (`A-B` vs `B-A`)LEAST(user_a, user_b), GREATEST(user_a, user_b)Forces (10, 25) and (25, 10) into one identical ordered pair `(10, 25)`!
Node Degree (Most Connected Users)UNION ALL both endpoints -> GROUP BY user_id COUNT(*)Counts total connections accurately whether a user appears on the left or right column.
2-Hop Traversal (Friends of Friends)Self-join edges e1 JOIN edges e2 ON e1.friend = e2.userWalks 1 hop from A -> B, then 1 hop from B -> C in one fast relational join!
Cycle Removal (`A -> B -> A`)WHERE e1.user_id <> e2.friend_idPrevents SQL from recommending *yourself* as a friend-of-a-friend!
Exclude Existing ConnectionsAND NOT EXISTS (SELECT 1 FROM edges d WHERE ...)Keeps only *brand-new* candidate recommendations (Friends-of-Friends you don't already follow).

Step-by-Step Worked Example 1: Clean Pair Deduplication

Suppose `raw_friendships` stores undirected edges messily (both directions + duplicates):

user_1user_2
101202
202101
202303
303202
101404

Normalize into clean unique undirected edges (canonical_edges) using LEAST & GREATEST:

WITH canonical_edges AS (
  SELECT DISTINCT
    LEAST(user_1, user_2)    AS node_a,
    GREATEST(user_1, user_2) AS node_b
  FROM raw_friendships
  WHERE user_1 <> user_2  -- Drop accidental self-loops!
)
SELECT node_a, node_b FROM canonical_edges;

Output (5 messy rows collapsed cleanly into 3 true edges): (101, 202), (202, 303), (101, 404)!


Step-by-Step Worked Example 2: Mutual-Friend Recommendations & Scalper Detection

Pattern A: "Who Should User 101 Connect With?" (2-Hop Friend-of-Friend + Mutual Count) First mirror canonical edges cleanly into `directed_edges` (`a -> b` and `b -> a`), then take 2 hops while blocking self-loops and existing friends:

WITH directed_edges AS (
  SELECT node_a AS src, node_b AS dst FROM canonical_edges
  UNION ALL
  SELECT node_b AS src, node_a AS dst FROM canonical_edges
)
SELECT
  e1.src              AS target_user,
  e2.dst              AS recommended_user,
  COUNT(DISTINCT e1.dst) AS mutual_friend_count
FROM directed_edges e1
JOIN directed_edges e2
  ON e1.dst = e2.src
WHERE e1.src = 101
  AND e2.dst <> e1.src  -- 1. Never recommend yourself!
  AND NOT EXISTS (      -- 2. Exclude people 101 ALREADY knows!
    SELECT 1
    FROM directed_edges existing
    WHERE existing.src = e1.src
      AND existing.dst = e2.dst
  )
GROUP BY e1.src, e2.dst
ORDER BY mutual_friend_count DESC;

With our sample data: 101 -> 202 -> 303 cleanly recommends `303` (1 mutual friend: `202`), while ignoring 101 -> 202 -> 101!

Pattern B: Scalper Collusion / Entity Resolution (Shared Payment / IP Clusters) In fraud analytics, multiple user accounts buying max ticket limits using the **same hashed credit card, phone, or device ID** expose organized scalper rings:

SELECT
  payment_instrument_hash,
  COUNT(DISTINCT buyer_id) AS linked_accounts,
  SUM(qty_sold)            AS total_tickets_hoarded,
  COLLECT_SET(buyer_id)    AS suspect_user_ring
FROM silver.ticket_orders
GROUP BY payment_instrument_hash
HAVING COUNT(DISTINCT buyer_id) >= 3
ORDER BY total_tickets_hoarded DESC;

Common Beginner Mistakes (And How to Fix Them)

  1. Forgetting to normalize undirected edges before 2-hop joins: If you only have (101, 202) in one direction without symmetrizing UNION ALL, joining e1.dst = e2.src misses reverse paths like 303 -> 202 -> 101!
  2. Unbounded 5+ hop recursion without depth limits: Circular loops (A -> B -> C -> A -> B...) explode exponentially into billions of rows! Always bound graph SQL traversals strictly to 1–3 hops (LIMIT / hop guards).
  3. Comparing PII raw strings instead of trimmed normalized keys: Always lowercase + trim emails (LOWER(TRIM(email))) before matching shared-identity fraud clusters!

Quick Cheat Sheet

  1. Deduplicate undirected pairs with `LEAST(a, b)` & `GREATEST(a, b)`, filtering out `a <> b` self-loops.
  2. Symmetrize canonical edges via `UNION ALL` before performing 2-hop traversals cleanly.
  3. Guard Friend-of-Friend recommendations with `target <> candidate` and `NOT EXISTS` against existing edges.
  4. Spot fraud rings cleanly via `GROUP BY shared_identifier HAVING COUNT(DISTINCT user_id) >= threshold`.

Comprehension & Architecture Check (3 Questions)

Test your understanding of the concepts covered in this lesson.

1. How can SQL queries eliminate mirrored duplicate pairs when analyzing bidirectional social relationships?
2. Why should beginners check a table's grain before writing a JOIN?
3. Which Medallion layer is meant to store clean, deduplicated, standardized records?
Practice What You Learned

TICKIT-13: Social Graph Co-Attendance: Event Companion Discovery

Marketing wants to discover which events are frequently attended by the same groups of people so they can bundle concert tickets together. We write a self-join query to find event pairs with high co-attendance.

Solve Challenge