File tree Expand file tree Collapse file tree
src/main/java/dev/mayankg/db_concepts/mysql/ig_clone_db Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ -- 1. Find the 5 oldest users.
2+ SELECT *
3+ FROM users
4+ ORDER BY created_at ASC
5+ LIMIT 5 ;
6+
7+ -- 2. What day of the week do most users register on?
8+ SELECT
9+ DAYNAME(created_at) AS day_of_week,
10+ COUNT (* ) AS new_users
11+ FROM users
12+ GROUP BY day_of_week
13+ ORDER BY new_users DESC
14+ LIMIT 1 ;
15+
16+ -- 3. Find the users who have never posted a photo.
17+ -- Option 1
18+ SELECT *
19+ FROM users
20+ WHERE id NOT IN (
21+ SELECT user_id
22+ FROM photos
23+ GROUP BY user_id
24+ );
25+
26+ -- Option 2
27+ SELECT
28+ username
29+ FROM users u
30+ LEFT JOIN photos p ON u .id = p .user_id
31+ WHERE p .user_id IS NULL ;
32+
33+ -- 4. Which user has the most likes on a single photo?
34+ SELECT
35+ p .id ,
36+ u .username ,
37+ p .image_url ,
38+ lp .like_count
39+ FROM photos p
40+ RIGHT JOIN (
41+ SELECT
42+ photo_id,
43+ COUNT (* ) AS like_count
44+ FROM likes
45+ GROUP BY photo_id
46+ ORDER BY like_count DESC
47+ ) AS lp ON p .id = lp .photo_id
48+ INNER JOIN users u ON u .id = p .user_id
49+ LIMIT 1 ;
50+
51+ -- 5.1. How many times does the average user post (excludes users who have never posted)?
52+ SELECT
53+ COUNT (* ) / COUNT (DISTINCT user_id) AS avg_post_per_user
54+ FROM photos;
55+
56+ -- 5.2. How many times does the average user post (includes users who have never posted)?
57+ SELECT
58+ (SELECT COUNT (* ) FROM photos) / (SELECT COUNT (* ) FROM users) AS avg_post_per_user;
59+
60+ -- 6. What are the top 5 most commonly used hashtags?
61+ SELECT
62+ pt .tag_id ,
63+ t .tag_name ,
64+ COUNT (* ) AS used
65+ FROM photo_tags pt
66+ LEFT JOIN tags t ON pt .tag_id = t .id
67+ GROUP BY pt .tag_id , t .tag_name
68+ ORDER BY used DESC
69+ LIMIT 5 ;
70+
71+ -- 7. Find the users who have liked every single photo on the site.
72+ SELECT
73+ l .user_id ,
74+ u .username ,
75+ COUNT (* ) AS total
76+ FROM users u
77+ RIGHT JOIN likes l ON u .id = l .user_id
78+ GROUP BY l .user_id , u .username
79+ HAVING total = (SELECT COUNT (* ) FROM photos);
You can’t perform that action at this time.
0 commit comments