Repository navigation
Expand file tree
/
Copy pathassignment.sql
More file actions
758 lines (578 loc) · 16.9 KB
/
Copy pathassignment.sql
File metadata and controls
758 lines (578 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
-- SESSION 1
create database music_streaming_app ;
use music_streaming_app ;
create table playlists (
playlist_id int primary key ,
name varchar(80),
created_by varchar(90)
);
INSERT INTO playlists (playlist_id, name, created_by)
VALUES
(1, 'Bollywood Hits', 'Amit'),
(2, 'Chill Vibes', 'Priya'),
(3, 'Workout Mix', 'Rahul');
select * from playlists
where created_by = 'Amit' ;
/*
A table is a collection of related data stored in rows and columns.
For example, in a Zomato database,
there could be an orders table that stores information about customer orders.
Row:
A row represents one complete record in a table.
For example, one row in the orders table might represent a single food order placed by a customer.
Example row:
order_id customer_name restaurant total_amount
101 Rahul Pizza Hut 550
This entire record is one row.
Column:
A column represents one specific type of information stored for every record in the table.
In the orders table, order_id, customer_name, restaurant, and total_amount are all columns.
Example:
order_id customer_name restaurant total_amount
Each vertical field is a column because it stores the same type of data for every order.
*/
-- SESSION 2
CREATE DATABASE foodie_app;
USE foodie_app;
CREATE TABLE restaurants (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
cuisine VARCHAR(50),
rating DECIMAL(3, 2),
location VARCHAR(100)
);
CREATE TABLE users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phone_number VARCHAR(20) UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE test_error (
id INT PRIMARY KEY
name TEXTUAL(50) -- Missing comma above, and 'TEXTUAL' is invalid
);
CREATE TABLE test_error (
id INT PRIMARY KEY,
name varchar(50) -- Missing comma above, and 'TEXTUAL' is invalid
);
-- SESSION 3
CREATE TABLE Playlist (
id INT AUTO_INCREMENT PRIMARY KEY,
song_name VARCHAR(100),
artist VARCHAR(100),
duration INT
);
INSERT INTO Playlist (song_name, artist, duration)
VALUES ('Kesariya', 'Arijit Singh', 268);
INSERT INTO Playlist (song_name, artist, duration) VALUES
('Brown Munde', 'AP Dhillon', 195),
('Chaleya', 'Arjit Singh', 234),
('Excuses', 'AP Dhillon', 175);
UPDATE Playlist
SET artist = 'Arijit Singh'
WHERE artist = 'Arjit Singh';
DELETE FROM Playlist
WHERE duration < 120;
UPDATE Playlist
SET song_name = CONCAT(song_name, ' (Remix)')
WHERE artist = 'AP Dhillon' AND duration > 180;
-- SESSION 4
create table MusicPlaylist(
id int ,
song_name varchar(100),
artist varchar(100),
genre varchar(100),
duration time
);
INSERT INTO MusicPlaylist (id, song_name, artist, genre, duration)
VALUES
(1, 'Blinding Lights', 'The Weeknd', 'Pop', '00:03:20'),
(2, 'Believer', 'Imagine Dragons', 'Rock', '00:03:24'),
(3, 'Perfect', 'Ed Sheeran', 'Pop', '00:04:23'),
(4, 'Heat Waves', 'Glass Animals', 'Indie', '00:03:58'),
(5, 'Levitating', 'Dua Lipa', 'Pop', '00:03:23');
select song_name ,artist
from MusicPlaylist
limit 3 ;
select distinct restaurant from FoodOrders ;
select fooditem as 'dish',
order_date as 'date_ordered'
from FoodOrders ;
/*
correct limit
select distinct
food_item , restaurant
from FoodOrders
limit 2 ;
*/
-- SESSION 5
CREATE TABLE Restaurants (
id INT PRIMARY KEY,
name VARCHAR(100),
cuisine VARCHAR(50),
rating DECIMAL(2,1),
city VARCHAR(50)
);
INSERT INTO Restaurants (id, name, cuisine, rating, city)
VALUES
(1, 'Spice Garden', 'North Indian', 4.5, 'Ahmedabad'),
(2, 'Pizza Palace', 'Italian', 4.3, 'Mumbai'),
(3, 'Dragon Wok', 'Chinese', 4.2, 'Delhi'),
(4, 'Burger Hub', 'Fast Food', 4.0, 'Pune'),
(5, 'Saffron Bites', 'South Indian', 4.6, 'Bengaluru');
insert into restaurants (id,name,cuisine,rating,city) values
(6,'pizza hut' , 'Italian',4.9 ,'Surat');
select * from restaurants ;
select * from restaurants where
rating > 4.0 and city in ('Ahmedabad','Surat') ;
select name from restaurants
where name
like 'S%' ;
INSERT INTO Restaurants (id, name, cuisine, rating, city) VALUES
(7, 'Gujarati Thali House', 'Gujarati', 3.5, 'Ahmedabad'),
(8, 'Surat Spice Hub', 'South Indian', 4.3, 'Surat');
select * from restaurants
where rating
between 3.5 and 4.5 ;
select * from restaurants
where cuisine in ('Chinese','Italian','South Indian') ;
-- SESSION 6
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10, 2),
category VARCHAR(50)
);
INSERT INTO products (id, name, price, category) VALUES
(1, 'Wireless Mouse', 25.50, 'Electronics'),
(2, 'USB-C Cable', 12.99, 'Electronics'),
(3, 'Gaming Keyboard', 89.99, 'Electronics'),
(4, 'Office Chair', 150.00, 'Furniture'),
(5, 'Desk Lamp', 35.75, 'Furniture'),
(6, 'Notebook Set', 8.50, 'Stationery'),
(7, 'Bluetooth Headphones', 120.00, 'Electronics'),
(8, 'Monitor Stand', 45.00, 'Furniture');
select * from products
order by price asc ;
select * from products
order by price desc
limit 5 ;
CREATE TABLE movies (
id INT PRIMARY KEY,
title VARCHAR(150),
release_year INT,
rating DECIMAL(3, 2)
);
INSERT INTO movies (id, title, release_year, rating) VALUES
(1, 'Inception', 2010, 8.8),
(2, 'The Dark Knight', 2008, 9.0),
(3, 'Interstellar', 2014, 8.6),
(4, 'Dunkirk', 2017, 7.8),
(5, 'Tenet', 2020, 7.3),
(6, 'The Matrix', 1999, 8.7),
(7, 'Avatar', 2009, 7.9),
(8, 'Oppenheimer', 2023, 8.9);
select * from movies
order by release_year desc , rating desc ;
select * from restaurants
order by name asc
limit 10 ;
CREATE TABLE songs (
id INT PRIMARY KEY,
title VARCHAR(100),
artist VARCHAR(100),
play_count INT,
added_date DATE
);
INSERT INTO songs (id, title, artist, play_count, added_date) VALUES
(1, 'Blinding Lights', 'The Weeknd', 5000000, '2023-01-15'),
(2, 'Shape of You', 'Ed Sheeran', 4800000, '2023-02-20'),
(3, 'Levitating', 'Dua Lipa', 5000000, '2023-03-10'), -- Tie in play_count with #1, but newer
(4, 'Peaches', 'Justin Bieber', 3200000, '2023-01-05'),
(5, 'Stay', 'Kid Laroi & Bieber', 4800000, '2023-04-01'), -- Tie in play_count with #2, but newer
(6, 'Good 4 U', 'Olivia Rodrigo', 3900000, '2023-02-14'),
(7, 'Montero', 'Lil Nas X', 3500000, '2023-03-22');
select title as trending_songs
from songs
order by play_count desc , added_date desc
limit 3;
show tables ;
-- SESSION 7
-- Create the Orders table
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
user_name VARCHAR(100),
total_amount DECIMAL(10, 2),
order_date DATE
);
-- Insert 5 sample records (one with NULL total_amount)
INSERT INTO Orders (order_id, user_name, total_amount, order_date) VALUES
(101, 'Alice Johnson', 150.75, '2026-07-01'),
(102, 'Bob Smith', 89.99, '2026-07-02'),
(103, 'Charlie Brown', NULL, '2026-07-03'), -- Pending payment
(104, 'Diana Prince', 210.50, '2026-07-04'),
(105, 'Ethan Hunt', 45.00, '2026-07-05');
select user_name ,
count(order_id) as order_count
from Orders
group by user_name ;
select avg(total_amount) from Orders ;
select max(total_amount) as highest ,
min(total_amount) as lowest
from Orders ;
select sum(total_amount) as total_sales
from Orders
where total_amount is not null ;
-- SESSION 8
drop table orders ;
-- Create the Orders table
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
user_id INT,
payment_method VARCHAR(20),
amount DECIMAL(10, 2)
);
-- Insert 8 sample records
INSERT INTO Orders (order_id, user_id, payment_method, amount) VALUES
(1001, 101, 'UPI', 1250.50),
(1002, 102, 'Card', 3499.00),
(1003, 103, 'COD', 899.99),
(1004, 101, 'Wallet', 450.00),
(1005, 104, 'UPI', 2100.75),
(1006, 105, 'Card', 15999.00),
(1007, 102, 'COD', 350.00),
(1008, 106, 'Wallet', 720.25);
select payment_method,
count(order_id) as method from orders
group by payment_method ;
select user_id ,
sum(amount) as total_spend
from orders
group by user_id ;
select payment_method,
avg(amount) as amount from orders
group by payment_method
having avg(amount) > 300 ;
/*
Use WHERE to exclude specific records from the calculation entirely.
Scenario: Calculate the average order amount per payment method,
but ignore any single order that is less than 100
(perhaps filtering out test transactions or cancellations).
Logic: The row with amount < 100 is removed before the average is calculated.
SELECT payment_method, AVG(amount) AS avg_amount
FROM Orders
WHERE amount >= 100 -- Filters individual rows first
GROUP BY payment_method;
Use HAVING to exclude entire categories based on their calculated statistics.
Scenario: Calculate the average order amount per payment method,
but only show methods where the final average is greater than 1000.
Logic: All rows are included in the calculation first;
then, entire payment methods (groups) with a low average are hidden.
SELECT payment_method, AVG(amount) AS avg_amount
FROM Orders
GROUP BY payment_method
HAVING AVG(amount) > 1000; -- Filters the resulting groups
*/
-- SESSION 9
drop table restaurants ;
-- Create the 'restaurants' table
CREATE TABLE restaurants (
id INT PRIMARY KEY,
name VARCHAR(100),
city VARCHAR(50)
);
-- Create the 'dishes' table with a Foreign Key constraint
CREATE TABLE dishes (
id INT PRIMARY KEY,
restaurant_id INT,
dish_name VARCHAR(100),
price DECIMAL(10, 2),
FOREIGN KEY (restaurant_id) REFERENCES restaurants(id)
);
-- Insert 3 restaurants
INSERT INTO restaurants (id, name, city) VALUES
(1, 'The Golden Spoon', 'New York'),
(2, 'Sushi Master', 'Tokyo'),
(3, 'La Bella Italia', 'Rome');
-- Insert dishes for each restaurant
INSERT INTO dishes (id, restaurant_id, dish_name, price) VALUES
-- The Golden Spoon
(101, 1, 'Classic Burger', 12.99),
(102, 1, 'Caesar Salad', 9.50),
(103, 1, 'Chocolate Cake', 6.00),
-- Sushi Master
(201, 2, 'Salmon Nigiri', 8.00),
(202, 2, 'Dragon Roll', 14.50),
-- La Bella Italia
(301, 3, 'Margherita Pizza', 11.00),
(302, 3, 'Spaghetti Carbonara', 13.50),
(303, 3, 'Tiramisu', 7.25);
select * from restaurants ;
select * from dishes ;
select r.name , r.city
from restaurants r
inner join dishes d
on r.id = d.restaurant_id ;
select r.name , r.city
from restaurants r
left join dishes d
on r.id = d.restaurant_id ;
SELECT
d.dish_name,
d.price,
r.name AS restaurant_name,
r.city
FROM
restaurants r
RIGHT JOIN
dishes d ON r.id = d.restaurant_id;
show tables;
select * from musicplaylist ;
/*Given this scenario:
You want to show a list of all playlists and the songs inside them,
like Spotify. Explain which JOIN type (INNER, LEFT, or RIGHT)
you would use to show all playlists, even if some are empty, and write the SQL query for it.
Finished
To show all playlists even if they are empty (contain no songs), you must use a LEFT JOIN.
Why LEFT JOIN?
Goal: Keep every row from the playlists table.
Logic: A LEFT JOIN returns all records from the left table (playlists) and the matched records from the right table (songs). If no match is found (an empty playlist), the song columns will simply show NULL.
Alternative: An INNER JOIN would hide empty playlists entirely. A RIGHT JOIN would work only if you swapped the table order, but LEFT JOIN is the standard convention for "Show all X and their related Y".
SQL Query
SELECT
p.playlist_name,
s.song_title,
s.artist
FROM
playlists p
LEFT JOIN
songs s ON p.id = s.playlist_id;
*/
-- SESSION 10
-- Create Influencers table
CREATE TABLE Influencers (
id INT PRIMARY KEY,
name VARCHAR(100)
);
-- Create Collaborations table
CREATE TABLE Collaborations (
id INT PRIMARY KEY,
influencer1_id INT,
influencer2_id INT,
collab_date DATE,
FOREIGN KEY (influencer1_id) REFERENCES Influencers(id),
FOREIGN KEY (influencer2_id) REFERENCES Influencers(id)
);
-- Insert Data
INSERT INTO Influencers (id, name) VALUES
(1, 'Alice'),
(2, 'Bob'),
(3, 'Charlie'),
(4, 'Diana'); -- Diana has no collaborations
INSERT INTO Collaborations (id, influencer1_id, influencer2_id, collab_date) VALUES
(101, 1, 2, '2026-01-15'), -- Alice & Bob
(102, 1, 3, '2026-02-20'); -- Alice & Charlie
select * from influencers ;
select * from collaborations ;
select i.name as influencer ,
c.collab_date from
influencers i
left join collaborations c
on i.id = c.influencer1_id or
i.id = c.influencer2_id ;
show databases ;
use music_streaming_app ;
show tables ;
-- SESSION 11
SELECT name, location, rating
FROM Restaurants
WHERE rating > (
SELECT AVG(rating)
FROM Restaurants
WHERE city = 'Mumbai' -- Replace with your specific city or remove filter for global average
);
SELECT
u.username,
(SELECT COUNT(*)
FROM Orders o
WHERE o.user_id = u.id) AS total_orders
FROM Users u;
SELECT title, release_year
FROM Movies
WHERE id IN (
SELECT movie_id
FROM Reviews
WHERE rating = 5
);
SELECT seller_name
FROM Sellers s
WHERE NOT EXISTS (
SELECT c.id
FROM Categories c
WHERE NOT EXISTS (
SELECT p.id
FROM Products p
JOIN Orders o ON p.id = o.product_id
WHERE p.seller_id = s.id
AND p.category_id = c.id
)
);
-- SESSION 12
WITH TopRatedProducts AS (
SELECT id, name, price, rating
FROM Products
WHERE rating > 4.5
)
SELECT *
FROM TopRatedProducts;
SELECT name, delivery_charge
FROM Restaurants
WHERE city = 'Ahmedabad'
AND delivery_charge < 50;
WITH AffordableAhmedabad AS (
SELECT name, delivery_charge
FROM Restaurants
WHERE city = 'Ahmedabad'
AND delivery_charge < 50
)
SELECT *
FROM AffordableAhmedabad;
WITH TopFollowedUsers AS (
SELECT id, username, follower_count
FROM Users
ORDER BY follower_count DESC
LIMIT 3
),
TopLikedPosts AS (
SELECT id, content, like_count
FROM Posts
ORDER BY like_count DESC
LIMIT 3
)
SELECT 'User' AS type, username AS name, follower_count AS metric FROM TopFollowedUsers
UNION ALL
SELECT 'Post' AS type, content AS name, like_count AS metric FROM TopLikedPosts;
WITH RECURSIVE NextWeek AS (
-- Base case: Today
SELECT CURDATE() AS booking_date, 1 AS day_num
UNION ALL
-- Recursive step: Add 1 day
SELECT DATE_ADD(booking_date, INTERVAL 1 DAY), day_num + 1
FROM NextWeek
WHERE day_num < 7
)
SELECT booking_date
FROM NextWeek;
SELECT username
FROM Users
WHERE id IN (
SELECT user_id
FROM Followers
GROUP BY user_id
HAVING COUNT(*) > 1000
);
WITH Influencers AS (
SELECT user_id
FROM Followers
GROUP BY user_id
HAVING COUNT(*) > 1000
)
SELECT u.username
FROM Users u
JOIN Influencers i ON u.id = i.user_id;
-- SESSION 13
CREATE TABLE Playlists (
id INT PRIMARY KEY,
user_id INT,
playlist_name VARCHAR(100),
total_likes INT
);
INSERT INTO Playlists (id, user_id, playlist_name, total_likes) VALUES
(1, 1, 'Gym Motivation', 1500),
(2, 1, 'Chill Vibes', 800),
(3, 1, 'Road Trip 2024', 1200),
(4, 2, 'Coding Focus', 2000),
(5, 2, 'Sleep Sounds', 500),
(6, 3, 'Party Hits', 3000),
(7, 4, 'Jazz Classics', 900),
(8, 4, 'Morning Coffee', 900);
SELECT
id,
playlist_name,
total_likes,
ROW_NUMBER() OVER (ORDER BY total_likes DESC) AS row_num
FROM Playlists;
SELECT
playlist_name,
user_id,
total_likes,
RANK() OVER (ORDER BY total_likes DESC) AS playlist_rank
FROM Playlists;
SELECT
playlist_name,
user_id,
total_likes,
DENSE_RANK() OVER (PARTITION BY user_id ORDER BY total_likes DESC) AS user_dense_rank
FROM Playlists;
SELECT playlist_name, user_id, total_likes
FROM (
SELECT
playlist_name,
user_id,
total_likes,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY total_likes DESC) AS rn
FROM Playlists
) AS ranked_playlists
WHERE rn <= 2;
-- SESSION 14
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
user_id INT,
order_date DATE,
total_amount DECIMAL(10, 2)
);
INSERT INTO Orders (order_id, user_id, order_date, total_amount) VALUES
(101, 1, '2026-08-01', 450.00),
(102, 1, '2026-08-05', 320.50),
(103, 1, '2026-08-10', 550.00),
(104, 2, '2026-08-02', 200.00),
(105, 2, '2026-08-08', 600.00),
(106, 3, '2026-08-03', 150.00),
(107, 3, '2026-08-12', 250.00);
SELECT
user_id,
order_id,
order_date,
total_amount,
LAG(total_amount) OVER (PARTITION BY user_id ORDER BY order_date) AS prev_order_amount
FROM Orders;
SELECT
order_id,
user_id,
order_date,
total_amount,
LEAD(total_amount) OVER (PARTITION BY user_id ORDER BY order_date) AS next_order_amount
FROM Orders;
SELECT
order_id,
user_id,
order_date,
total_amount,
SUM(total_amount) OVER (
PARTITION BY user_id
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM Orders;
SELECT
order_id,
user_id,
order_date,
total_amount,
AVG(total_amount) OVER (
PARTITION BY user_id
ORDER BY order_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS moving_avg
FROM Orders;