-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql-practice.html
More file actions
768 lines (700 loc) · 36.2 KB
/
Copy pathsql-practice.html
File metadata and controls
768 lines (700 loc) · 36.2 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
758
759
760
761
762
763
764
765
766
767
768
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SQL Practice Log | Dev Anand Jayakumar</title>
<style>
/* ── RESET & BASE ── */
*{box-sizing:border-box;margin:0;padding:0}
:root{
--bg:#0b0f1a;--s1:#111827;--s2:#1a2234;--s3:#1e2a3a;
--border:#1e2d45;--border2:#243447;
--text:#e2e8f0;--muted:#64748b;--muted2:#94a3b8;
--blue:#38bdf8;--blue-dim:#0ea5e9;--blue-glow:rgba(56,189,248,.15);
--green:#34d399;--green-dim:rgba(52,211,153,.15);
--amber:#fbbf24;--amber-dim:rgba(251,191,36,.13);
--red:#f87171;--red-dim:rgba(248,113,113,.13);
--purple:#a78bfa;
}
html,body{height:100%;background:var(--bg);color:var(--text);
font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
font-size:14px;overflow:hidden}
/* ── LOADING ── */
#loading{position:fixed;inset:0;background:var(--bg);display:flex;flex-direction:column;
align-items:center;justify-content:center;gap:14px;z-index:999}
.spin{width:32px;height:32px;border:3px solid var(--border);
border-top-color:var(--blue);border-radius:50%;animation:spin .7s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
/* ── APP SHELL ── */
#app{height:100%;display:flex;flex-direction:column}
/* ── TOP NAV ── */
nav{height:54px;background:var(--s1);border-bottom:1px solid var(--border);
padding:0 24px;display:flex;align-items:center;gap:16px;flex-shrink:0}
.nav-back{font-size:12px;color:var(--muted2);text-decoration:none;
display:flex;align-items:center;gap:5px;transition:color .15s}
.nav-back:hover{color:var(--blue)}
.nav-divider{color:var(--border);font-size:16px}
.nav-title{font-size:14px;font-weight:700;color:var(--text)}
.nav-sub{font-size:12px;color:var(--muted);margin-left:2px}
.nav-right{margin-left:auto;display:flex;align-items:center;gap:8px}
/* ── STATS STRIP ── */
#stats-strip{background:var(--s1);border-bottom:1px solid var(--border);
padding:10px 24px;display:flex;align-items:center;gap:20px;flex-shrink:0;flex-wrap:wrap}
.stat-chip{display:flex;align-items:center;gap:7px}
.stat-icon{font-size:14px}
.stat-val{font-size:16px;font-weight:800;line-height:1}
.stat-lbl{font-size:11px;color:var(--muted);margin-top:1px}
.stat-sep{width:1px;height:28px;background:var(--border);flex-shrink:0}
.prog-outer{flex:1;min-width:180px;max-width:320px}
.prog-label{display:flex;justify-content:space-between;font-size:11px;color:var(--muted);margin-bottom:5px}
.prog-track{height:6px;background:var(--s3);border-radius:3px;overflow:hidden}
.prog-fill{height:100%;border-radius:3px;
background:linear-gradient(90deg,var(--blue-dim),var(--blue));transition:width .5s}
.chip-easy{color:var(--green)}.chip-medium{color:var(--amber)}.chip-hard{color:var(--red)}
.last-active{font-size:11px;color:var(--muted);margin-left:auto;white-space:nowrap}
/* ── MAIN LAYOUT ── */
#main{flex:1;display:flex;overflow:hidden}
/* ── SIDEBAR ── */
aside{width:230px;background:var(--s1);border-right:1px solid var(--border);
overflow-y:auto;flex-shrink:0}
aside::-webkit-scrollbar{width:3px}
aside::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px}
.day-hdr{font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;
color:var(--muted);padding:14px 16px 5px;display:flex;align-items:center;gap:8px}
.day-hdr::after{content:'';flex:1;height:1px;background:var(--border)}
.q-row{display:flex;align-items:center;gap:9px;padding:7px 14px;cursor:pointer;
border-left:3px solid transparent;transition:background .12s,border-color .12s}
.q-row:hover{background:var(--s2)}
.q-row.active{background:var(--s2);border-left-color:var(--blue)}
.q-dot{width:17px;height:17px;border-radius:50%;border:2px solid var(--border2);
display:flex;align-items:center;justify-content:center;font-size:9px;
flex-shrink:0;transition:all .2s;color:transparent}
.q-dot.done{background:var(--green);border-color:var(--green);color:#000;font-weight:900}
.q-name{font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--text)}
.q-diff{font-size:10.5px;margin-top:1px}
.q-diff.Easy{color:var(--green)}.q-diff.Medium{color:var(--amber)}.q-diff.Hard{color:var(--red)}
/* ── CONTENT ── */
#content{flex:1;overflow-y:auto;padding:22px 26px 40px;background:var(--bg)}
#content::-webkit-scrollbar{width:4px}
#content::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px}
/* ── QUESTION HEADER ── */
.qh-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:12px}
.qh-num{font-size:12px;color:var(--muted);background:var(--s2);
padding:2px 8px;border-radius:4px;border:1px solid var(--border2)}
.qh-title{font-size:20px;font-weight:800;letter-spacing:-.3px}
.badge{padding:3px 10px;border-radius:10px;font-size:11px;font-weight:700}
.badge.Easy{background:var(--green-dim);color:var(--green)}
.badge.Medium{background:var(--amber-dim);color:var(--amber)}
.badge.Hard{background:var(--red-dim);color:var(--red)}
.tag{padding:2px 8px;background:var(--s2);border-radius:4px;
font-size:11px;color:var(--muted2);border:1px solid var(--border2)}
/* ── DESCRIPTION ── */
.desc{background:var(--s1);border:1px solid var(--border2);border-radius:8px;
padding:14px 16px;margin-bottom:14px;line-height:1.75;font-size:13.5px;color:var(--muted2)}
.desc strong{color:var(--text)}.desc em{color:var(--muted2);font-style:italic}
.desc code{background:var(--s3);padding:1px 6px;border-radius:3px;
font-family:monospace;font-size:12px;color:var(--blue)}
/* ── SECTION LABEL ── */
.slbl{font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;
color:var(--muted);margin-bottom:7px;display:flex;align-items:center;gap:8px}
.slbl::after{content:'';flex:1;height:1px;background:var(--border)}
/* ── SAMPLE TABLES ── */
.tables-row{display:flex;gap:12px;flex-wrap:wrap;margin-bottom:14px}
.tbl-wrap{flex:1;min-width:150px}
.tbl-name{font-size:11.5px;font-weight:700;color:var(--blue);
margin-bottom:5px;display:flex;align-items:center;gap:5px}
.tbl-name::before{content:'⊞';font-size:12px}
.dtbl{border-collapse:collapse;font-size:12px;width:100%;
background:var(--s1);border:1px solid var(--border2);border-radius:7px;overflow:hidden}
.dtbl th{background:var(--s3);padding:5px 10px;text-align:left;
border-bottom:1px solid var(--border2);color:var(--muted2);font-weight:700;font-size:10.5px}
.dtbl td{padding:5px 10px;border-bottom:1px solid var(--border);font-family:monospace;font-size:12px}
.dtbl tr:last-child td{border-bottom:none}
/* ── NOTE ── */
.note{background:rgba(56,189,248,.07);border:1px solid rgba(56,189,248,.2);
border-left:3px solid var(--blue);border-radius:0 6px 6px 0;
padding:9px 14px;font-size:12.5px;color:var(--muted2);margin-bottom:12px;line-height:1.6}
.note strong{color:var(--blue)}
/* ── EDITOR ── */
.editor-box{background:#080d16;border:1px solid var(--border2);border-radius:8px;overflow:hidden;margin-bottom:12px}
.editor-hdr{padding:7px 14px;background:var(--s2);border-bottom:1px solid var(--border);
display:flex;align-items:center;gap:8px;font-size:11px;color:var(--muted)}
.editor-dot{width:10px;height:10px;border-radius:50%}
.dot-r{background:#f87171}.dot-y{background:#fbbf24}.dot-g{background:#34d399}
#sql-editor{width:100%;min-height:120px;background:transparent;color:#e2e8f0;
border:none;padding:13px 16px;font-family:'Consolas','Cascadia Code','Menlo',monospace;
font-size:13px;line-height:1.65;resize:vertical;outline:none;tab-size:2}
.editor-actions{display:flex;gap:9px;padding:10px 14px;background:var(--s2);
border-top:1px solid var(--border);flex-wrap:wrap}
/* ── BUTTONS ── */
.btn{padding:7px 14px;border-radius:6px;border:none;cursor:pointer;font-size:12.5px;
font-weight:700;display:inline-flex;align-items:center;gap:5px;transition:opacity .15s;white-space:nowrap}
.btn:hover{opacity:.82}.btn:active{opacity:.6}
.btn-run{background:var(--blue);color:#000}
.btn-clr{background:var(--s3);color:var(--text);border:1px solid var(--border2)}
.btn-hint{background:rgba(167,139,250,.1);color:var(--purple);border:1px solid rgba(167,139,250,.25)}
.btn-sol{background:rgba(56,189,248,.1);color:var(--blue);border:1px solid rgba(56,189,248,.25)}
.btn-done{background:var(--green);color:#000}
.btn-undo{background:var(--s3);color:var(--muted2);border:1px solid var(--border2)}
/* ── RESULTS ── */
.res-box{background:var(--s1);border:1px solid var(--border2);border-radius:8px;
overflow:hidden;margin-bottom:12px}
.res-hdr{padding:7px 14px;background:var(--s2);border-bottom:1px solid var(--border);
font-size:11px;display:flex;justify-content:space-between;color:var(--muted);align-items:center}
.ok{color:var(--green)}.err{color:var(--red)}
.res-scroll{overflow-x:auto;max-height:200px;overflow-y:auto}
.res-scroll::-webkit-scrollbar{height:3px;width:3px}
.res-scroll::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px}
.rtbl{border-collapse:collapse;font-size:12px;width:100%}
.rtbl th{background:var(--s3);padding:6px 12px;text-align:left;border-bottom:1px solid var(--border);
font-size:10.5px;color:var(--muted2);font-weight:700;white-space:nowrap}
.rtbl td{padding:6px 12px;border-bottom:1px solid var(--border);font-family:monospace;font-size:12px}
.rtbl tr:last-child td{border-bottom:none}
.rtbl tr:hover td{background:var(--s2)}
.null-val{color:var(--muted);font-style:italic}
.err-msg{padding:14px 16px;color:var(--red);font-family:monospace;font-size:12px;line-height:1.5}
.empty-msg{padding:14px 16px;color:var(--muted);font-size:13px}
/* ── SOLUTION ── */
.sol-box{background:#080d16;border:1px solid rgba(56,189,248,.2);border-radius:8px;
overflow:hidden;margin-bottom:12px}
.sol-hdr{padding:7px 14px;background:rgba(56,189,248,.08);border-bottom:1px solid rgba(56,189,248,.15);
font-size:11px;color:var(--blue);font-weight:700;letter-spacing:.06em;text-transform:uppercase;
display:flex;align-items:center;gap:6px}
.sol-code{padding:14px 16px;font-family:monospace;font-size:12.5px;line-height:1.65;
white-space:pre-wrap;overflow-x:auto;color:#e2e8f0}
/* ── BOTTOM NAV ── */
.bottom-bar{display:flex;align-items:center;gap:10px;margin-top:6px;
padding-top:14px;border-top:1px solid var(--border);flex-wrap:wrap}
.spacer{flex:1}
/* ── EMPTY STATE ── */
.empty-qs{padding:40px;text-align:center;color:var(--muted)}
/* ── RESPONSIVE ── */
@media(max-width:700px){
aside{display:none}
#stats-strip{gap:12px}
}
</style>
</head>
<body>
<div id="loading">
<div class="spin"></div>
<p style="color:var(--muted);font-size:12px;margin-top:4px">Loading SQL engine…</p>
</div>
<div id="app" style="display:none">
<!-- ── NAV ── -->
<nav>
<a class="nav-back" href="https://dev-anandj.netlify.app/">← Portfolio</a>
<span class="nav-divider">/</span>
<span class="nav-title">SQL Practice Log</span>
<span class="nav-sub">· Dev Anand Jayakumar</span>
<div class="nav-right">
<span style="font-size:11px;color:var(--muted)">LeetCode · FAANG SQL</span>
</div>
</nav>
<!-- ── STATS STRIP ── -->
<div id="stats-strip">
<div class="stat-chip">
<div>
<div class="stat-val" id="s-total" style="color:var(--blue)">0</div>
<div class="stat-lbl">Solved</div>
</div>
</div>
<div class="stat-sep"></div>
<div class="stat-chip">
<div>
<div class="stat-val chip-easy" id="s-easy">0</div>
<div class="stat-lbl">Easy</div>
</div>
</div>
<div class="stat-chip">
<div>
<div class="stat-val chip-medium" id="s-med">0</div>
<div class="stat-lbl">Medium</div>
</div>
</div>
<div class="stat-chip">
<div>
<div class="stat-val chip-hard" id="s-hard">0</div>
<div class="stat-lbl">Hard</div>
</div>
</div>
<div class="stat-sep"></div>
<div class="prog-outer">
<div class="prog-label">
<span>Overall Progress</span>
<span id="s-pct">0 / 16</span>
</div>
<div class="prog-track"><div class="prog-fill" id="s-bar" style="width:0%"></div></div>
</div>
<div class="last-active" id="s-last"></div>
</div>
<!-- ── MAIN ── -->
<div id="main">
<aside id="sidebar"></aside>
<div id="content"></div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.2/sql-wasm.js"></script>
<script>
// ════════════════════════════════════════════════════════════
// QUESTIONS (same dataset as practice app, localStorage edition)
// ════════════════════════════════════════════════════════════
const QS = [
{num:175,title:"Combine Two Tables",difficulty:"Easy",tags:["LEFT JOIN"],
desc:"Write a SQL query providing <strong>FirstName, LastName, City, State</strong> for every person — <em>even those with no address on record</em>.",
setup:`CREATE TABLE Person (PersonId INTEGER PRIMARY KEY, FirstName TEXT, LastName TEXT);
CREATE TABLE Address (AddressId INTEGER PRIMARY KEY, PersonId INTEGER, City TEXT, State TEXT);
INSERT INTO Person VALUES (1,'Wang','Allen'),(2,'Alice','Bob'),(3,'Tom','Smith');
INSERT INTO Address VALUES (1,2,'New York','NY'),(2,3,'Los Angeles','CA');`,
tables:["Person","Address"],
hint:"Wang has no address — he must still appear. Which JOIN keeps all left-table rows regardless of a match?",
solution:`SELECT p.FirstName, p.LastName, a.City, a.State
FROM Person p
LEFT JOIN Address a ON p.PersonId = a.PersonId;`,note:null},
{num:176,title:"Second Highest Salary",difficulty:"Easy",tags:["Subquery","DENSE_RANK"],
desc:"Return the <strong>second highest salary</strong> from Employee. Return <code>NULL</code> if it doesn't exist.",
setup:`CREATE TABLE Employee (Id INTEGER PRIMARY KEY, Salary INTEGER);
INSERT INTO Employee VALUES (1,100),(2,200),(3,300);`,
tables:["Employee"],
hint:"Filter out the MAX, then take the MAX of what remains. Or use DENSE_RANK() and filter rank = 2.",
solution:`SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT MAX(Salary) FROM Employee);`,note:null},
{num:177,title:"Nth Highest Salary",difficulty:"Medium",tags:["LIMIT","OFFSET","Window Functions"],
desc:"Find the <strong>Nth highest salary</strong> (use N = 2 here). Return NULL if it doesn't exist. Stored functions are not available — use LIMIT/OFFSET or window functions.",
setup:`CREATE TABLE Employee (Id INTEGER PRIMARY KEY, Salary INTEGER);
INSERT INTO Employee VALUES (1,100),(2,200),(3,300);`,
tables:["Employee"],
hint:"LIMIT 1 OFFSET N-1 skips the top N-1 rows. Use DISTINCT to handle duplicate salaries.",
solution:`SELECT DISTINCT Salary AS NthHighestSalary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1;`,
note:"⚠️ <strong>SQLite:</strong> No stored procedures. Use LIMIT/OFFSET or DENSE_RANK() with WHERE rnk = N."},
{num:178,title:"Rank Scores",difficulty:"Medium",tags:["DENSE_RANK","Window Functions"],
desc:"Rank each score. Ties share the same rank with no gaps afterwards. Return rows ordered highest score first.",
setup:`CREATE TABLE Scores (Id INTEGER PRIMARY KEY, Score REAL);
INSERT INTO Scores VALUES (1,3.50),(2,3.65),(3,4.00),(4,3.85),(5,4.00),(6,3.65);`,
tables:["Scores"],
hint:"DENSE_RANK gives consecutive ranks on ties. RANK leaves gaps. ROW_NUMBER breaks ties arbitrarily.",
solution:`SELECT Score,
DENSE_RANK() OVER (ORDER BY Score DESC) AS "Rank"
FROM Scores ORDER BY Score DESC;`,note:null},
{num:180,title:"Consecutive Numbers",difficulty:"Medium",tags:["Self JOIN","LAG"],
desc:"Find all numbers appearing <strong>at least three times consecutively</strong> (by Id). Return distinct values.",
setup:`CREATE TABLE Logs (Id INTEGER PRIMARY KEY, Num INTEGER);
INSERT INTO Logs VALUES (1,1),(2,1),(3,1),(4,2),(5,1),(6,2),(7,2);`,
tables:["Logs"],
hint:"Self-join Logs 3× on consecutive IDs and matching Num. Or use LAG(Num,1) and LAG(Num,2) window functions.",
solution:`SELECT DISTINCT a.Num AS ConsecutiveNums
FROM Logs a
JOIN Logs b ON a.Id = b.Id+1 AND a.Num = b.Num
JOIN Logs c ON a.Id = c.Id+2 AND a.Num = c.Num;`,note:null},
{num:181,title:"Employees Earning More Than Their Managers",difficulty:"Easy",tags:["Self JOIN"],
desc:"Find <strong>employees who earn more than their own manager</strong>.",
setup:`CREATE TABLE Employee (Id INTEGER PRIMARY KEY, Name TEXT, Salary INTEGER, ManagerId INTEGER);
INSERT INTO Employee VALUES (1,'Joe',70000,3),(2,'Henry',80000,4),(3,'Sam',60000,NULL),(4,'Max',90000,NULL);`,
tables:["Employee"],
hint:"Join Employee to itself — one alias for the employee, one for the manager — and compare salaries.",
solution:`SELECT e.Name AS Employee
FROM Employee e
JOIN Employee m ON e.ManagerId = m.Id
WHERE e.Salary > m.Salary;`,note:null},
{num:182,title:"Duplicate Emails",difficulty:"Easy",tags:["GROUP BY","HAVING","ROW_NUMBER"],
desc:"Find all <strong>duplicate emails</strong> in the Person table.",
setup:`CREATE TABLE Person (Id INTEGER PRIMARY KEY, Email TEXT);
INSERT INTO Person VALUES (1,'a@b.com'),(2,'c@d.com'),(3,'a@b.com');`,
tables:["Person"],
hint:"GROUP BY Email, then HAVING COUNT(*) > 1 keeps only groups with duplicates.",
solution:`SELECT Email FROM Person
GROUP BY Email HAVING COUNT(*) > 1;`,note:null},
{num:183,title:"Customers Who Never Order",difficulty:"Easy",tags:["LEFT JOIN","NOT IN"],
desc:"Find all <strong>customers who never placed any order</strong>.",
setup:`CREATE TABLE Customers (Id INTEGER PRIMARY KEY, Name TEXT);
CREATE TABLE Orders (Id INTEGER PRIMARY KEY, CustomerId INTEGER);
INSERT INTO Customers VALUES (1,'Joe'),(2,'Henry'),(3,'Sam'),(4,'Max');
INSERT INTO Orders VALUES (1,3),(2,1);`,
tables:["Customers","Orders"],
hint:"LEFT JOIN: customers with no order have NULL in Orders columns. Or use WHERE Id NOT IN (SELECT CustomerId FROM Orders).",
solution:`SELECT c.Name AS Customers
FROM Customers c
LEFT JOIN Orders o ON c.Id = o.CustomerId
WHERE o.CustomerId IS NULL;`,
note:"⚠️ <strong>Caution:</strong> NOT IN returns no rows if the subquery contains any NULL. Always verify your subquery is NULL-safe."},
{num:184,title:"Department Highest Salary",difficulty:"Medium",tags:["JOIN","Subquery","RANK"],
desc:"Find the <strong>employee(s) with the highest salary in each department</strong>. Multiple employees can tie.",
setup:`CREATE TABLE Employee (Id INTEGER PRIMARY KEY, Name TEXT, Salary INTEGER, DepartmentId INTEGER);
CREATE TABLE Department (Id INTEGER PRIMARY KEY, Name TEXT);
INSERT INTO Employee VALUES (1,'Joe',70000,1),(2,'Jim',90000,1),(3,'Henry',80000,2),(4,'Sam',60000,2),(5,'Max',90000,1);
INSERT INTO Department VALUES (1,'IT'),(2,'Sales');`,
tables:["Employee","Department"],
hint:"Use RANK() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) and filter where rank = 1.",
solution:`WITH ranked AS (
SELECT Name, Salary, DepartmentId,
RANK() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) AS rnk
FROM Employee
)
SELECT d.Name AS Department, r.Name AS Employee, r.Salary
FROM ranked r JOIN Department d ON r.DepartmentId = d.Id
WHERE r.rnk = 1;`,note:null},
{num:185,title:"Department Top Three Salaries",difficulty:"Hard",tags:["DENSE_RANK","CTE"],
desc:"Find all employees earning a <strong>top-three distinct salary</strong> within their department.",
setup:`CREATE TABLE Employee (Id INTEGER PRIMARY KEY, Name TEXT, Salary INTEGER, DepartmentId INTEGER);
CREATE TABLE Department (Id INTEGER PRIMARY KEY, Name TEXT);
INSERT INTO Employee VALUES (1,'Joe',85000,1),(2,'Henry',80000,2),(3,'Sam',60000,2),(4,'Max',90000,1),(5,'Janet',69000,1),(6,'Randy',85000,1),(7,'Will',70000,1);
INSERT INTO Department VALUES (1,'IT'),(2,'Sales');`,
tables:["Employee","Department"],
hint:"DENSE_RANK() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) — filter where rnk <= 3.",
solution:`WITH ranked AS (
SELECT Name AS Employee, Salary, DepartmentId,
DENSE_RANK() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) AS rnk
FROM Employee
)
SELECT d.Name AS Department, r.Employee, r.Salary
FROM ranked r JOIN Department d ON r.DepartmentId = d.Id
WHERE r.rnk <= 3
ORDER BY d.Name, r.Salary DESC;`,note:null},
{num:196,title:"Delete Duplicate Emails",difficulty:"Easy",tags:["DELETE","Subquery"],
desc:"Delete all duplicate emails, keeping only the row with the <strong>smallest Id</strong> per email. Run <code>SELECT * FROM Person;</code> afterwards to verify.",
setup:`CREATE TABLE Person (Id INTEGER PRIMARY KEY, Email TEXT);
INSERT INTO Person VALUES (1,'john@example.com'),(2,'bob@example.com'),(3,'john@example.com');`,
tables:["Person"],
hint:"Keep MIN(Id) per Email. Delete all rows whose Id is NOT in that set.",
solution:`DELETE FROM Person
WHERE Id NOT IN (
SELECT MIN(Id) FROM Person GROUP BY Email
);
SELECT * FROM Person;`,
note:"⚠️ <strong>SQLite:</strong> MySQL's <code>DELETE t2 FROM t1 JOIN t2...</code> syntax is not supported. Use <code>WHERE Id NOT IN (...)</code>."},
{num:197,title:"Rising Temperature",difficulty:"Easy",tags:["Self JOIN","Date Functions","LAG"],
desc:"Find all Id values where the temperature was <strong>higher than the previous day</strong>.",
setup:`CREATE TABLE Weather (Id INTEGER PRIMARY KEY, RecordDate TEXT, Temperature INTEGER);
INSERT INTO Weather VALUES (1,'2015-01-01',10),(2,'2015-01-02',25),(3,'2015-01-03',20),(4,'2015-01-04',30);`,
tables:["Weather"],
hint:"Self-join where one RecordDate = the other + 1 day. In SQLite: <code>date(y.RecordDate, '+1 day') = t.RecordDate</code>.",
solution:`SELECT t.Id
FROM Weather t
JOIN Weather y ON date(y.RecordDate, '+1 day') = t.RecordDate
WHERE t.Temperature > y.Temperature;`,
note:"⚠️ <strong>SQLite:</strong> Use <code>date(col, '+1 day')</code> instead of MySQL's <code>DATEDIFF()</code>."},
{num:262,title:"Trips and Users",difficulty:"Hard",tags:["Subquery","NOT IN","CASE WHEN"],
desc:"Find the <strong>cancellation rate</strong> per day (Oct 1–3 2013) for trips where neither the client nor driver is banned. Round to 2 decimal places.",
setup:`CREATE TABLE Trips (Id INTEGER PRIMARY KEY, Client_Id INTEGER, Driver_Id INTEGER, City_Id INTEGER, Status TEXT, Request_at TEXT);
CREATE TABLE Users (Users_Id INTEGER PRIMARY KEY, Banned TEXT, Role TEXT);
INSERT INTO Trips VALUES (1,1,10,1,'completed','2013-10-01'),(2,2,11,1,'cancelled_by_driver','2013-10-01'),(3,3,12,6,'completed','2013-10-01'),(4,4,13,6,'cancelled_by_client','2013-10-01'),(5,1,10,1,'completed','2013-10-02'),(6,2,11,6,'completed','2013-10-02'),(7,3,12,6,'completed','2013-10-02'),(8,2,12,12,'completed','2013-10-03'),(9,3,10,12,'completed','2013-10-03'),(10,4,13,12,'cancelled_by_driver','2013-10-03');
INSERT INTO Users VALUES (1,'No','client'),(2,'Yes','client'),(3,'No','client'),(4,'No','client'),(10,'No','driver'),(11,'No','driver'),(12,'No','driver'),(13,'No','driver');`,
tables:["Trips","Users"],
hint:"1) Filter banned users with NOT IN. 2) GROUP BY date. 3) CASE WHEN status != 'completed'. 4) ROUND(SUM/COUNT, 2).",
solution:`SELECT Request_at AS Day,
ROUND(SUM(CASE WHEN Status!='completed' THEN 1.0 ELSE 0 END)/COUNT(*),2) AS "Cancellation Rate"
FROM Trips
WHERE Request_at BETWEEN '2013-10-01' AND '2013-10-03'
AND Client_Id NOT IN (SELECT Users_Id FROM Users WHERE Banned='Yes')
AND Driver_Id NOT IN (SELECT Users_Id FROM Users WHERE Banned='Yes')
GROUP BY Request_at ORDER BY Request_at;`,
note:"⚠️ <strong>SQLite:</strong> Use <code>CASE WHEN</code> instead of MySQL's <code>IF()</code>. Use <code>1.0</code> for float division."},
{num:511,title:"Game Play Analysis I",difficulty:"Easy",tags:["GROUP BY","MIN"],
desc:"Report the <strong>first login date</strong> for each player.",
setup:`CREATE TABLE Activity (player_id INTEGER, device_id INTEGER, event_date TEXT, games_played INTEGER, PRIMARY KEY(player_id,event_date));
INSERT INTO Activity VALUES (1,2,'2016-03-01',5),(1,2,'2016-05-02',6),(2,3,'2017-06-25',1),(3,1,'2016-03-02',0),(3,4,'2018-07-03',5);`,
tables:["Activity"],
hint:"GROUP BY player_id and find MIN(event_date).",
solution:`SELECT player_id, MIN(event_date) AS first_login
FROM Activity GROUP BY player_id;`,note:null},
{num:512,title:"Game Play Analysis II",difficulty:"Easy",tags:["Subquery","JOIN","ROW_NUMBER"],
desc:"Report the <strong>device each player first logged in with</strong>.",
setup:`CREATE TABLE Activity (player_id INTEGER, device_id INTEGER, event_date TEXT, games_played INTEGER, PRIMARY KEY(player_id,event_date));
INSERT INTO Activity VALUES (1,2,'2016-03-01',5),(1,2,'2016-05-02',6),(2,3,'2017-06-25',1),(3,1,'2016-03-02',0),(3,4,'2018-07-03',5);`,
tables:["Activity"],
hint:"Find MIN(event_date) per player, then join back to Activity to get the device_id for that exact date.",
solution:`SELECT a.player_id, a.device_id
FROM Activity a
JOIN (
SELECT player_id, MIN(event_date) AS first_date
FROM Activity GROUP BY player_id
) b ON a.player_id=b.player_id AND a.event_date=b.first_date;`,note:null},
{num:534,title:"Game Play Analysis III",difficulty:"Medium",tags:["Running Total","Window Functions"],
desc:"For each player and date, report the <strong>cumulative number of games played so far</strong> (including that day).",
setup:`CREATE TABLE Activity (player_id INTEGER, device_id INTEGER, event_date TEXT, games_played INTEGER, PRIMARY KEY(player_id,event_date));
INSERT INTO Activity VALUES (1,2,'2016-03-01',5),(1,2,'2016-05-02',6),(1,3,'2017-06-25',1),(3,1,'2016-03-02',0),(3,4,'2018-07-03',5);`,
tables:["Activity"],
hint:"SUM(games_played) OVER (PARTITION BY player_id ORDER BY event_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW).",
solution:`SELECT player_id, event_date,
SUM(games_played) OVER (
PARTITION BY player_id ORDER BY event_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS games_played_so_far
FROM Activity ORDER BY player_id, event_date;`,note:null}
];
const DAYS = [];
for(let i=0;i<QS.length;i+=2) DAYS.push(QS.slice(i,i+2));
const TOTAL = QS.length;
// ════════════════════════════════════════
// STATE (localStorage)
// ════════════════════════════════════════
const LS_KEY = 'devanand_sql_practice_v1';
function loadState() {
try {
const raw = localStorage.getItem(LS_KEY);
if (raw) return JSON.parse(raw);
} catch(_) {}
return { completed: [], currentIdx: 0 };
}
function saveState() {
try {
localStorage.setItem(LS_KEY, JSON.stringify({
completed: [...completed],
currentIdx,
lastActive: new Date().toISOString()
}));
} catch(_) {}
}
function getLastActive() {
try {
const raw = localStorage.getItem(LS_KEY);
if (raw) return JSON.parse(raw).lastActive;
} catch(_) {}
return null;
}
let SQL=null, db=null;
let currentIdx=0;
let completed=new Set();
let showSol=false;
// ════════════════════════════════════════
// DB HELPERS
// ════════════════════════════════════════
function freshDB(setup) {
if(db){try{db.close()}catch(_){}}
db=new SQL.Database();
try{db.run(setup)}catch(e){console.warn('Setup:',e)}
}
function runSQL(sql) {
try { return {ok:true, results:db.exec(sql)} }
catch(e) { return {ok:false, error:e.message} }
}
function tableData(name) {
try { const r=db.exec(`SELECT * FROM ${name} LIMIT 25`); return r.length?r[0]:null }
catch(_){return null}
}
// ════════════════════════════════════════
// RENDER
// ════════════════════════════════════════
function esc(s){
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
}
function renderStats() {
const easy = QS.filter(q=>completed.has(q.num)&&q.difficulty==='Easy').length;
const med = QS.filter(q=>completed.has(q.num)&&q.difficulty==='Medium').length;
const hard = QS.filter(q=>completed.has(q.num)&&q.difficulty==='Hard').length;
const total = completed.size;
const pct = Math.round(total/TOTAL*100);
document.getElementById('s-total').textContent = total;
document.getElementById('s-easy').textContent = easy;
document.getElementById('s-med').textContent = med;
document.getElementById('s-hard').textContent = hard;
document.getElementById('s-pct').textContent = `${total} / ${TOTAL}`;
document.getElementById('s-bar').style.width = pct+'%';
const la = getLastActive();
if(la) {
const d = new Date(la);
document.getElementById('s-last').textContent =
'Last active: '+d.toLocaleDateString('en-IE',{day:'numeric',month:'short',year:'numeric'});
}
}
function renderSidebar() {
let html='';
DAYS.forEach((day,di) => {
html+=`<div class="day-hdr">Day ${di+1}</div>`;
day.forEach(q => {
const qi=QS.indexOf(q);
const active=qi===currentIdx?' active':'';
const done=completed.has(q.num);
html+=`<div class="q-row${active}" onclick="selectQ(${qi})">
<div class="q-dot${done?' done':''}">${done?'✓':''}</div>
<div style="flex:1;min-width:0">
<div class="q-name">${q.num}. ${q.title}</div>
<div class="q-diff ${q.difficulty}">${q.difficulty}</div>
</div>
</div>`;
});
});
document.getElementById('sidebar').innerHTML=html;
}
function renderQ() {
showSol=false;
const q=QS[currentIdx];
freshDB(q.setup);
// Sample tables
let tbls='<div class="slbl">Sample Data</div><div class="tables-row">';
q.tables.forEach(t => {
const r=tableData(t);
tbls+=`<div class="tbl-wrap"><div class="tbl-name">${t}</div>`;
if(r){
tbls+=`<table class="dtbl"><thead><tr>${r.columns.map(c=>`<th>${esc(c)}</th>`).join('')}</tr></thead><tbody>`;
r.values.forEach(row=>{
tbls+=`<tr>${row.map(v=>v===null?`<td><span class="null-val">NULL</span></td>`:`<td>${esc(String(v))}</td>`).join('')}</tr>`;
});
tbls+=`</tbody></table>`;
}
tbls+=`</div>`;
});
tbls+=`</div>`;
const note=q.note?`<div class="note">${q.note}</div>`:'';
const tags=q.tags.map(t=>`<span class="tag">${t}</span>`).join(' ');
const isDone=completed.has(q.num);
const dayNum=Math.floor(currentIdx/2)+1;
const qInDay=(currentIdx%2)+1;
document.getElementById('content').innerHTML=`
<div class="qh-row">
<span class="qh-num">Day ${dayNum} · Q${qInDay}/2</span>
<span class="qh-num">#${q.num}</span>
<span class="qh-title">${q.title}</span>
<span class="badge ${q.difficulty}">${q.difficulty}</span>
${tags}
</div>
<div class="desc">${q.desc}</div>
${tbls}
${note}
<div class="slbl" style="margin-bottom:8px">Write Your Query</div>
<div class="editor-box">
<div class="editor-hdr">
<div class="editor-dot dot-r"></div>
<div class="editor-dot dot-y"></div>
<div class="editor-dot dot-g"></div>
<span style="margin-left:6px">query.sql</span>
<span style="margin-left:auto;font-size:10.5px">Ctrl+Enter to run</span>
</div>
<textarea id="sql-editor" placeholder="-- Write your SQL here… SELECT ..." spellcheck="false"></textarea>
<div class="editor-actions">
<button class="btn btn-run" onclick="runQuery()">▶ Run</button>
<button class="btn btn-clr" onclick="clearEditor()">✕ Clear</button>
<button class="btn btn-hint" onclick="showHint()">💡 Hint</button>
<button class="btn btn-sol" onclick="toggleSol()">👁 Solution</button>
</div>
</div>
<div class="slbl" style="margin-bottom:8px">Results</div>
<div class="res-box" id="res-box">
<div class="res-hdr"><span>Run a query to see results</span></div>
</div>
<div id="sol-wrap" style="display:none">
<div class="slbl" style="margin-bottom:8px">Solution</div>
<div class="sol-box">
<div class="sol-hdr">✅ Reference Solution</div>
<div class="sol-code" id="sol-code"></div>
</div>
</div>
<div class="bottom-bar">
<button class="btn ${isDone?'btn-done':'btn-undo'}" id="done-btn" onclick="toggleDone()">
${isDone?'✓ Completed':'○ Mark as Done'}
</button>
<div class="spacer"></div>
${currentIdx>0?`<button class="btn btn-clr" onclick="selectQ(${currentIdx-1})">← Prev</button>`:''}
${currentIdx<TOTAL-1?`<button class="btn btn-run" onclick="selectQ(${currentIdx+1})">Next →</button>`:''}
</div>
`;
document.getElementById('sql-editor').addEventListener('keydown',e=>{
if((e.ctrlKey||e.metaKey)&&e.key==='Enter'){e.preventDefault();runQuery()}
});
}
// ════════════════════════════════════════
// ACTIONS
// ════════════════════════════════════════
function selectQ(idx) {
currentIdx=idx;
saveState();
renderSidebar();
renderStats();
renderQ();
document.getElementById('content').scrollTop=0;
}
function runQuery() {
const sql=document.getElementById('sql-editor').value.trim();
if(!sql) return;
freshDB(QS[currentIdx].setup);
const {ok,results,error}=runSQL(sql);
const box=document.getElementById('res-box');
if(!ok){
box.innerHTML=`<div class="res-hdr"><span class="err">⚠ Error</span></div><div class="err-msg">${esc(error)}</div>`;
return;
}
if(!results||results.length===0){
box.innerHTML=`<div class="res-hdr"><span class="ok">✓ Executed</span><span>0 rows returned</span></div>
<div class="empty-msg">No rows returned. For DELETE/UPDATE, run SELECT * to verify.</div>`;
return;
}
const r=results[results.length-1];
const cols=r.columns||[], rows=r.values||[];
let tbl=`<table class="rtbl"><thead><tr>${cols.map(c=>`<th>${esc(c)}</th>`).join('')}</tr></thead><tbody>`;
rows.forEach(row=>{
tbl+=`<tr>${row.map(v=>v===null?`<td><span class="null-val">NULL</span></td>`:`<td>${esc(String(v))}</td>`).join('')}</tr>`;
});
tbl+=`</tbody></table>`;
box.innerHTML=`<div class="res-hdr">
<span class="ok">✓ ${rows.length} row${rows.length!==1?'s':''}</span>
<span>${cols.length} col${cols.length!==1?'s':''}</span>
</div><div class="res-scroll">${tbl}</div>`;
}
function clearEditor() {
const ed=document.getElementById('sql-editor');
if(ed) ed.value='';
const box=document.getElementById('res-box');
if(box) box.innerHTML=`<div class="res-hdr"><span>Run a query to see results</span></div>`;
}
function showHint() {
alert('💡 Hint\n\n'+QS[currentIdx].hint);
}
function toggleSol() {
showSol=!showSol;
const wrap=document.getElementById('sol-wrap');
if(showSol){
document.getElementById('sol-code').textContent=QS[currentIdx].solution;
wrap.style.display='block';
wrap.scrollIntoView({behavior:'smooth',block:'nearest'});
} else {
wrap.style.display='none';
}
}
function toggleDone() {
const q=QS[currentIdx];
if(completed.has(q.num)) completed.delete(q.num);
else completed.add(q.num);
saveState();
renderSidebar();
renderStats();
const isDone=completed.has(q.num);
const btn=document.getElementById('done-btn');
if(btn){
btn.textContent=isDone?'✓ Completed':'○ Mark as Done';
btn.className='btn '+(isDone?'btn-done':'btn-undo');
}
}
// ════════════════════════════════════════
// BOOT
// ════════════════════════════════════════
async function boot() {
const state=loadState();
completed=new Set(state.completed||[]);
currentIdx=state.currentIdx||0;
if(currentIdx>=TOTAL) currentIdx=0;
try {
SQL=await initSqlJs({
locateFile:f=>`https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.2/${f}`
});
} catch(e) {
document.getElementById('loading').innerHTML=
`<p style="color:var(--red);text-align:center;padding:24px;max-width:400px">
Failed to load SQL engine.<br><small style="color:var(--muted)">${e.message}</small>
</p>`;
return;
}
document.getElementById('loading').style.display='none';
document.getElementById('app').style.display='flex';
renderStats();
renderSidebar();
renderQ();
}
boot();
</script>
</body>
</html>