Each user's top category

window functions

Each user's top category

Pinterest SQL Interview Question

Pinterest personalizes each user's home feed around the category their pins get saved most in.

For each user, find the category whose pins have the most saves in total. Return user_id, category and total_saves. If two categories tie, pick the one that comes first alphabetically. Sort by user_id.

Asked of

  • Data Analyst
  • Business Analyst
  • BI Analyst
  • Product Analyst
  • Analytics Engineer

pinsTable20 rows

Column NameType
pin_idBIGINT
user_idBIGINT
categoryVARCHAR
created_atDATE
savesBIGINT

pinsExample Input

pin_iduser_idcategorycreated_atsaves
1701Food2024-07-0114
2701Food2024-07-013
3702Travel2024-07-0227
4701DIY2024-07-028
5703DIY2024-07-035
6702Travel2024-07-0311
7704Food2024-07-042
8703Travel2024-07-0419
9702Food2024-07-056
10704Food2024-07-059
11705DIY2024-07-0631
12703DIY2024-07-064
13701Travel2024-07-0712
14705DIY2024-07-077
15704DIY2024-07-081
16702Travel2024-07-0822
17705Food2024-07-0910
18703Food2024-07-093
19704Travel2024-07-1016
20701Food2024-07-105

Example Output

user_idcategorytotal_saves
701Food22
702Travel60
703Travel19
704Travel16
705DIY38

Explanation

User 701's Food pins were saved 14, 3 and 5 times, 22 in total, more than their Travel pin with 12 saves or their DIY pin with 8. User 703's single Travel pin has 19 saves, more than their two DIY pins combined, which have 9.

The example above is a small slice of the data. Your query runs against the full tables.