Skip to content

Latest commit

History

30 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SolvedEasyMediumHardMySQL


Not just solutions — a full study companion.

Every problem has the schema, sample data, a working query, a step-by-step breakdown, and a personal takeaway so you know why it works — not just that it does.


📌 Why This Repo?

Most SQL solution repos dump queries in a .sql file and call it done.

This one is different. Every single problem is its own documented file — with the table schema, sample input/output, the SQL solution, a numbered approach walking through the logic, the concepts it exercises, and a personal takeaway distilled from actually solving it. Think of it as the notes you wish someone had written before you started.

Who is this for?

  • 🎓 Students preparing for placements / internships
  • 💼 Anyone brushing up SQL for data analyst / data engineering roles
  • 🏗️ People who want to understand why a query works, not just copy it

🗂️ Repo Structure

leetcode-sql-50/
│
├── 📂 easy/ # 32 problems — WHERE, JOINs, Aggregation, String Functions
├── 📂 medium/ # 17 problems — Subqueries, Window Functions, CTEs, UNION
├── 📂 hard/ # 1 problem — DENSE_RANK, Advanced Window Functions
└── 📄 README.md

Each file follows this exact structure:

# 🟡 [Problem Number] · [Title]
Difficulty + Topic badge | LeetCode link
---
📋 Problem Statement
🗂️ Schema (CREATE TABLE block)
📥 Sample Input (markdown table)
📤 Sample Output (markdown table)
💡 Solution (SQL code block)
🧠 Approach (numbered steps)
📌 Concepts Used (`backtick` tags)
💭 My Takeaway (1–2 sentences in plain language)

🟢 Easy — 32 Problems

#LC #ProblemTopic
011757Recyclable and Low Fat ProductsFiltering / WHERE
02584Find Customer RefereeNULL Handling / Filtering
03595Big CountriesFiltering / WHERE
041148Article Views IFiltering / WHERE
051683Invalid TweetsString Functions / LENGTH()
061378Replace Employee ID With The Unique IdentifierJOIN / LEFT JOIN
071068Product Sales Analysis IJOIN / INNER JOIN
081581Customer Who Visited but Did Not Make Any TransactionsLEFT JOIN / NULL / GROUP BY
09197Rising TemperatureSelf JOIN / DATEDIFF
101661Average Time of Process per MachineSelf JOIN / Aggregation
11577Employee BonusLEFT JOIN / NULL Handling
121280Students and ExaminationsCROSS JOIN / Aggregation
13620Not Boring MoviesWHERE / MOD
141251Average Selling PriceJOIN / CASE WHEN / AVG
151075Project Employees IJOIN / AVG
161633Percentage of Users Attended a ContestJOIN / Subquery / Aggregation
171211Queries Quality and PercentageAVG / Conditional Aggregation
182356Number of Unique Subjects Taught by Each TeacherCOUNT DISTINCT
191141User Activity for the Past 30 Days IDate Filtering / COUNT DISTINCT
20596Classes More Than 5 StudentsGROUP BY / HAVING
211729Find Followers CountGROUP BY / COUNT
22619Biggest Single NumberSubquery / MAX / HAVING
231731Number of Employees Reporting to Each EmployeeSelf JOIN / Aggregation
241789Primary Department for Each EmployeeUNION / Filtering
25610Triangle JudgementCASE WHEN
261978Employees Whose Manager Left the CompanySubquery / NOT IN
271667Fix Names in a TableUPPER / LOWER / CONCAT / SUBSTR
281527Patients With a ConditionLIKE / String Matching
29196Delete Duplicate EmailsDELETE / Self JOIN
301484Group Sold Products By The DateGROUP_CONCAT / GROUP BY
311327List the Products Ordered in a PeriodJOIN / HAVING / Date Filter
321517Find Users With Valid E-MailsREGEXP / Pattern Validation

🟡 Medium — 17 Problems

#LC #ProblemTopic
01570Managers with at Least 5 Direct ReportsSelf JOIN / GROUP BY / HAVING
021934Confirmation RateLEFT JOIN / SUM(condition) / IFNULL
031193Monthly Transactions ICASE WHEN / Conditional Aggregation
041174Immediate Food Delivery IISubquery / MIN / Conditional AVG
05550Game Play Analysis IVDATE_ADD / Subquery / COUNT
061070Product Sales Analysis IIISubquery / IN with Tuple / MIN
071045Customers Who Bought All ProductsGROUP BY / COUNT DISTINCT vs Scalar Subquery
08180Consecutive NumbersSelf JOIN / 3-way Join
091164Product Price at a Given DateSubquery / UNION / Date Filtering
101204Last Person to Fit in the BusWindow Functions / Cumulative SUM
111907Count Salary CategoriesUNION ALL / Conditional COUNT
12626Exchange SeatsCASE WHEN / MOD / COUNT
131341Movie RatingUNION ALL / GROUP BY / ORDER BY / LIMIT
141321Restaurant GrowthWindow Functions / Moving Average / CTE
15602Friend Requests II: Who Has the Most FriendsUNION ALL / GROUP BY
16585Investments in 2016Subquery / IN / COUNT > 1
17176Second Highest SalaryLIMIT+OFFSET / IFNULL / Subquery

🔴 Hard — 1 Problem

#LC #ProblemTopic
01185Department Top Three SalariesDENSE_RANK / PARTITION BY / Subquery

🧩 Concept Index

Jump straight to any SQL technique and see every problem that uses it.

🔗 JOIN & NULL Handling — click to expand
TechniqueProblems
INNER JOIN1068 · 1075 · 570 · 185
LEFT JOIN1378 · 1581 · 577 · 1934
CROSS JOIN1280
Self JOIN197 · 1731 · 570 · 180
NULL Handling (IS NULL, IFNULL, COALESCE)584 · 577 · 1934 · 176
📊 Aggregation & Grouping — click to expand
TechniqueProblems
GROUP BY + HAVING596 · 1581 · 570 · 1045
COUNT DISTINCT2356 · 1729 · 1141
SUM(condition) trick1934 · 1211
Conditional aggregation (CASE WHEN inside SUM/AVG)1193 · 1251 · 1174
🪟 Window Functions — click to expand
TechniqueProblems
DENSE_RANK() OVER (PARTITION BY ...)185
Cumulative SUM() OVER (ORDER BY ...)1204
Moving Average (AVG OVER ROWS BETWEEN)1321
🔀 Subqueries & Set Operations — click to expand
TechniqueProblems
Scalar subquery in WHERE619 · 1978 · 176
Correlated subquery / IN with tuple1070 · 585
UNION ALL1789 · 1907 · 1341 · 602
UNION (distinct)1164
🔡 String & Pattern Matching — click to expand
TechniqueProblems
LENGTH() vs CHAR_LENGTH()1683
UPPER() / LOWER() / SUBSTR() / CONCAT()1667
LIKE pattern1527
REGEXP1517
GROUP_CONCAT()1484
📅 Date Functions — click to expand
TechniqueProblems
DATEDIFF()197
DATE_ADD()550
DATE_FORMAT() / month filtering1193 · 1141
💡 Conditional Logic — click to expand
TechniqueProblems
CASE WHEN1251 · 610 · 1193 · 626
IFNULL() / COALESCE()1934 · 176
DELETE with Self JOIN196

🧠 SQL Quick-Reference Cheatsheet

The most commonly tested patterns — pulled from these 50 problems.

-- ✅ Safe NULL comparison (never use = NULL)WHERE column IS NULLWHERE column IS NOT NULL-- ✅ LEFT JOIN to include non-matching rowsSELECTa.id, b.valueFROM TableA a
LEFT JOIN TableB b ONa.id=b.a_idWHEREb.a_id IS NULL-- rows in A with NO match in B-- ✅ SUM(condition) trick — count rows matching a conditionSELECTSUM(status ='confirmed') /COUNT(*) AS rate -- MySQL booleanFROM Orders
-- ✅ DENSE_RANK for top-N per group (no gaps on ties)SELECT*FROM (
SELECT name, salary,
DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk
FROM Employee
) t
WHERE rnk <=3-- ✅ Moving average — last N rows inclusiveSELECTAVG(amount) OVER (
ORDER BY visit_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_avg
-- ✅ UNION ALL to combine then aggregate (preserve duplicates)SELECT id FROM TableA
UNION ALLSELECT id FROM TableB
-- ✅ GROUP_CONCAT for comma-separated strings per groupSELECT sell_date, COUNT(DISTINCT product) AS num_sold,
GROUP_CONCAT(DISTINCT product ORDER BY product) AS products
FROM Activities
GROUP BY sell_date
-- ✅ Second highest salary (handles NULL edge case)SELECT IFNULL(
(SELECT DISTINCT salary FROM Employee ORDER BY salary DESCLIMIT1 OFFSET 1),
NULL
) AS SecondHighestSalary
-- ✅ DELETE with self-join (avoid correlated subquery trap)DELETE p1
FROM Person p1
JOIN Person p2 ONp1.email=p2.emailANDp1.id>p2.id

🤝 Contributing

Found a better approach or a bug in my solution? PRs are welcome.

  1. Fork the repo
  2. Create a branch: git checkout -b fix/problem-number
  3. Commit your change: git commit -m "fix: improved approach for #1934"
  4. Open a pull request

If this helped you, a ⭐ keeps it alive.

GitHubLeetCode

About

SQL solutions for LeetCode 50 problems with structured and readable queries. Categorized by difficulty for systematic SQL practice and learning.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors