r/SolveSQL • • Aug 20 '26

SQL Challenge β€” Detect Suspicious Account Sharing πŸ”₯

You have a table called logins:
user_id | login_time | device_id | country
--------|------------------|-----------|---------
101 | 2026-01-01 10:00 | D1 | India
101 | 2026-01-01 10:18 | D2 | USA
101 | 2026-01-01 14:00 | D1 | India
102 | 2026-01-02 09:00 | D3 | India
102 | 2026-01-02 09:20 | D4 | India
103 | 2026-01-03 11:00 | D5 | UK
103 | 2026-01-03 11:15 | D6 | Germany
103 | 2026-01-03 11:25 | D7 | UK

🎯 Challenge
A user is considered suspicious if they log in:
β€’ From different countries
β€’ Using different devices
β€’ Within 30 minutes of each other

Find ALL suspicious login pairs.

Expected output:
user_id | first_login | second_login | device_1 | device_2 | country_1 | country_2

⚠️** The Catc**h
Don’t just compare each login with the immediately previous login.

For example:
10:00 β†’ India
10:10 β†’ India
10:20 β†’ USA
The 10:00 and 10:20 logins also form a suspicious pair.
Your query should identify every qualifying pair while avoiding duplicate combinations like:
(A, B)
(B, A)
How would you solve this in SQL? πŸ‘€

2 Upvotes

1 comment sorted by

2

u/Brilliant-Parsley69 Aug 22 '26 edited Aug 22 '26

That should be an easy one (SQL-Server):

SELECT  
    l1.user_id,  
    l1.login_time AS first_login,  
    l2.login_time AS second_login,  
    l1.device_id AS device_1,  
    l2.device_id AS device_2,  
    l1.country AS country_1,  
    l2.country AS country_2. 
FROM logins l1
JOIN logins l2
    ON l1.user_id = l2.user_id  
-- Should exclude (A,B) / (B,A) duplicates and ensure chronological order. 
    AND l1.login_time < l2.login_time   
WHERE l1.country <> l2.country  
AND l1.device_id <> l2.device_id  
-- Checks for logins of the same device within 30 minutes  
AND DATEDIFF(minute, l1.login_time, l2.login_time) <= 30;