# SQLMaster: Complete Knowledge Base & SQL Interview Repository Website: https://freesqlmaster.com Platform Type: Client-side Interactive SQL Learning & Interview Prep Engine: SQLite 3 WebAssembly (runs 100% locally in browser, zero-login, 0ms server latency) --- ## 1. SQL Quick Reference & Key Concepts ### Logical Query Execution Order Unlike procedural programming languages, SQL queries are NOT executed in the written order. The database engine parses and executes clauses in this specific order: 1. FROM (and JOIN): Identifies and combines the base tables. 2. WHERE: Filters individual rows BEFORE grouping. 3. GROUP BY: Aggregates rows sharing identical values into distinct groups. 4. HAVING: Filters the grouped aggregate results AFTER grouping. 5. SELECT: Evaluates expressions, calculates output columns, and generates aliases. 6. DISTINCT: Eliminates duplicate result rows. 7. ORDER BY: Sorts the final output rows. 8. LIMIT / OFFSET: Constrains the total number of rows returned. ### Essential Comparison Matrix | Concept | Primary Purpose | Key Trap / Gotcha | |---|---|---| | INNER JOIN | Returns only matching rows from both tables | Drops rows with no match on either side | | LEFT JOIN | Preserves all rows from the left table, padding right table with NULLs | Filtering right table columns in WHERE can accidentally convert it to an INNER JOIN | | WHERE | Filters individual records before aggregation | Cannot use aggregate functions (e.g. WHERE SUM(val) > 10 fails) | | HAVING | Filters grouped records after aggregation | Runs after GROUP BY; expensive if used for row filters that WHERE could eliminate | | ROW_NUMBER() | Assigns consecutive unique integers (1, 2, 3...) | No ties; arbitrary ordering on duplicates unless secondary sort columns specified | | RANK() | Assigns ranks with gaps for ties (1, 2, 2, 4...) | Skips rank positions after duplicates | | DENSE_RANK() | Assigns ranks without gaps for ties (1, 2, 2, 3...) | Ideal for "find the Nth highest value" questions | | CTE (WITH clause) | Creates named temporary result sets for modular queries | Improves maintainability over deeply nested subqueries | --- ## 2. Top 50 SQL Interview Challenges with Canonical Solutions ### Challenge: Recyclable and Low Fat Products (Easy) - Topic: Select - URL: https://freesqlmaster.com/interview/recyclable-and-low-fat-products/ - Task: Find the ids of products that are both low fat and recyclable. - Explanation: This query filters the table using basic `SELECT` and `WHERE` clauses to match the exact conditions specified in the problem. Canonical SQL Query: ```sql SELECT product_id FROM Products WHERE low_fats = 'Y' AND recyclable = 'Y'; ``` ### Challenge: Find Customer Referee (Easy) - Topic: Select - URL: https://freesqlmaster.com/interview/find-customer-referee/ - Task: Find the names of the customer that are not referred by the customer with id = 2. - Explanation: This query filters the table using basic `SELECT` and `WHERE` clauses to match the exact conditions specified in the problem. Canonical SQL Query: ```sql SELECT name FROM Customer WHERE referee_id != 2 OR referee_id IS NULL; ``` ### Challenge: Big Countries (Easy) - Topic: Select - URL: https://freesqlmaster.com/interview/big-countries/ - Task: Find the name, population, and area of the big countries. - Explanation: This query filters the table using basic `SELECT` and `WHERE` clauses to match the exact conditions specified in the problem. Canonical SQL Query: ```sql SELECT name, population, area FROM World WHERE area >= 3000000 OR population >= 25000000; ``` ### Challenge: Article Views I (Easy) - Topic: Select - URL: https://freesqlmaster.com/interview/article-views-i/ - Task: Find all the authors that viewed at least one of their own articles. Return the result table sorted by id in ascending order. - Explanation: This query filters the table using basic `SELECT` and `WHERE` clauses to match the exact conditions specified in the problem. Canonical SQL Query: ```sql SELECT DISTINCT author_id AS id FROM Views WHERE author_id = viewer_id ORDER BY id ASC; ``` ### Challenge: Invalid Tweets (Easy) - Topic: Select - URL: https://freesqlmaster.com/interview/invalid-tweets/ - Task: Find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15. - Explanation: This query filters the table using basic `SELECT` and `WHERE` clauses to match the exact conditions specified in the problem. Canonical SQL Query: ```sql SELECT tweet_id FROM Tweets WHERE LENGTH(content) > 15; ``` ### Challenge: Replace Employee ID With The Unique Identifier (Easy) - Topic: Basic Joins - URL: https://freesqlmaster.com/interview/replace-employee-id-with-the-unique-identifier/ - Task: Write a solution to show the unique ID of each user. - Explanation: This solution uses a `JOIN` to combine data from multiple tables to find the required output. Canonical SQL Query: ```sql SELECT eu.unique_id, e.name FROM Employees e LEFT JOIN EmployeeUNI eu ON e.id = eu.id; ``` ### Challenge: Product Sales Analysis I (Easy) - Topic: Basic Joins - URL: https://freesqlmaster.com/interview/product-sales-analysis-i/ - Task: Write a solution to report the product_name, year, and price for each sale_id in the Sales table. - Explanation: This solution uses a `JOIN` to combine data from multiple tables to find the required output. Canonical SQL Query: ```sql SELECT p.product_name, s.year, s.price FROM Sales s JOIN Product p ON s.product_id = p.product_id; ``` ### Challenge: Customer Who Visited but Did Not Make Any Transactions (Easy) - Topic: Basic Joins - URL: https://freesqlmaster.com/interview/customer-who-visited-but-did-not-make-any-transactions/ - Task: Find the IDs of the users who visited without making any transactions and the number of times they made these types of visits. - Explanation: This solution uses a `JOIN` to combine data from multiple tables and the `GROUP BY` clause to aggregate results. Canonical SQL Query: ```sql SELECT v.customer_id, COUNT(v.visit_id) as count_no_trans FROM Visits v LEFT JOIN Transactions t ON v.visit_id = t.visit_id WHERE t.transaction_id IS NULL GROUP BY v.customer_id; ``` ### Challenge: Rising Temperature (Easy) - Topic: Basic Joins - URL: https://freesqlmaster.com/interview/rising-temperature/ - Task: Find all dates' Id with higher temperatures compared to its previous dates (yesterday). - Explanation: This solution uses a `JOIN` to combine data from multiple tables and date functions to handle time-based filtering or grouping. Canonical SQL Query: ```sql SELECT w1.id FROM Weather w1 JOIN Weather w2 ON DATE(w1.recordDate, '-1 day') = w2.recordDate WHERE w1.temperature > w2.temperature; ``` ### Challenge: Average Time of Process per Machine (Easy) - Topic: Basic Joins - URL: https://freesqlmaster.com/interview/average-time-of-process-per-machine/ - Task: Find the average time each machine takes to complete a process. Result should have machine_id and processing_time (rounded to 3 decimal places). - Explanation: This solution uses a `JOIN` to combine data from multiple tables, the `GROUP BY` clause to aggregate results, and the `ROUND()` function to format numerical output. Canonical SQL Query: ```sql SELECT a1.machine_id, ROUND(AVG(a2.timestamp - a1.timestamp), 3) as processing_time FROM Activity a1 JOIN Activity a2 ON a1.machine_id = a2.machine_id AND a1.process_id = a2.process_id AND a1.activity_type = 'start' AND a2.activity_type = 'end' GROUP BY a1.machine_id; ``` ### Challenge: Employee Bonus (Easy) - Topic: Basic Joins - URL: https://freesqlmaster.com/interview/employee-bonus/ - Task: Report the name and bonus amount of each employee with a bonus less than 1000. - Explanation: This solution uses a `JOIN` to combine data from multiple tables to find the required output. Canonical SQL Query: ```sql SELECT e.name, b.bonus FROM Employee e LEFT JOIN Bonus b ON e.empId = b.empId WHERE b.bonus < 1000 OR b.bonus IS NULL; ``` ### Challenge: Students and Examinations (Easy) - Topic: Basic Joins - URL: https://freesqlmaster.com/interview/students-and-examinations/ - Task: Find the number of times each student attended each exam. Order by student_id and subject_name. - Explanation: This solution uses a `JOIN` to combine data from multiple tables and the `GROUP BY` clause to aggregate results. Canonical SQL Query: ```sql SELECT s.student_id, s.student_name, sub.subject_name, COUNT(e.subject_name) AS attended_exams FROM Students s CROSS JOIN Subjects sub LEFT JOIN Examinations e ON s.student_id = e.student_id AND sub.subject_name = e.subject_name GROUP BY s.student_id, s.student_name, sub.subject_name ORDER BY s.student_id, sub.subject_name; ``` ### Challenge: Managers with at Least 5 Direct Reports (Medium) - Topic: Basic Joins - URL: https://freesqlmaster.com/interview/managers-with-at-least-5-direct-reports/ - Task: Find the names of managers with at least 5 direct reports. - Explanation: This solution uses a `JOIN` to combine data from multiple tables, the `GROUP BY` clause to aggregate results, and a `HAVING` clause to filter the aggregated groups. Canonical SQL Query: ```sql SELECT e1.name FROM Employee e1 JOIN Employee e2 ON e1.id = e2.managerId GROUP BY e1.id HAVING COUNT(e2.id) >= 5; ``` ### Challenge: Confirmation Rate (Medium) - Topic: Basic Joins - URL: https://freesqlmaster.com/interview/confirmation-rate/ - Task: Find the confirmation rate of each user (confirmed / total requests). Round to 2 decimal places. - Explanation: This solution uses a `JOIN` to combine data from multiple tables, the `GROUP BY` clause to aggregate results, a `CASE` statement for conditional logic, and the `ROUND()` function to format numerical output. Canonical SQL Query: ```sql SELECT s.user_id, ROUND(AVG(CASE WHEN c.action = 'confirmed' THEN 1 ELSE 0 END), 2) AS confirmation_rate FROM Signups s LEFT JOIN Confirmations c ON s.user_id = c.user_id GROUP BY s.user_id; ``` ### Challenge: Not Boring Movies (Easy) - Topic: Basic Aggregate Functions - URL: https://freesqlmaster.com/interview/not-boring-movies/ - Task: Report the movies with an odd-numbered ID and a description that is not "boring". Order by rating DESC. - Explanation: This query filters the table using basic `SELECT` and `WHERE` clauses to match the exact conditions specified in the problem. Canonical SQL Query: ```sql SELECT * FROM Cinema WHERE id % 2 = 1 AND description != 'boring' ORDER BY rating DESC; ``` ### Challenge: Average Selling Price (Easy) - Topic: Basic Aggregate Functions - URL: https://freesqlmaster.com/interview/average-selling-price/ - Task: Find the average selling price for each product. average_price = total_price / total_units. - Explanation: This solution uses a `JOIN` to combine data from multiple tables, the `GROUP BY` clause to aggregate results, and the `ROUND()` function to format numerical output. Canonical SQL Query: ```sql SELECT p.product_id, IFNULL(ROUND(SUM(p.price * u.units) / CAST(SUM(u.units) AS FLOAT), 2), 0) AS average_price FROM Prices p LEFT JOIN UnitsSold u ON p.product_id = u.product_id AND u.purchase_date BETWEEN p.start_date AND p.end_date GROUP BY p.product_id; ``` ### Challenge: Project Employees I (Easy) - Topic: Basic Aggregate Functions - URL: https://freesqlmaster.com/interview/project-employees-i/ - Task: Write an SQL query that reports the average experience years of all the employees for each project, rounded to 2 digits. - Explanation: This solution uses a `JOIN` to combine data from multiple tables, the `GROUP BY` clause to aggregate results, and the `ROUND()` function to format numerical output. Canonical SQL Query: ```sql SELECT p.project_id, ROUND(AVG(e.experience_years), 2) AS average_years FROM Project p JOIN Employee e ON p.employee_id = e.employee_id GROUP BY p.project_id; ``` ### Challenge: Percentage of Users Attended a Contest (Easy) - Topic: Basic Aggregate Functions - URL: https://freesqlmaster.com/interview/percentage-of-users-attended-a-contest/ - Task: Find the percentage of users registered in each contest rounded to 2 decimals. Return sorted by percentage descending, then contest_id ascending. - Explanation: This solution uses the `GROUP BY` clause to aggregate results, the `ROUND()` function to format numerical output, and a subquery as a derived table or inline value. Canonical SQL Query: ```sql SELECT contest_id, ROUND(COUNT(user_id) * 100.0 / (SELECT COUNT(*) FROM Users), 2) AS percentage FROM Register GROUP BY contest_id ORDER BY percentage DESC, contest_id ASC; ``` ### Challenge: Queries Quality and Percentage (Easy) - Topic: Basic Aggregate Functions - URL: https://freesqlmaster.com/interview/queries-quality-and-percentage/ - Task: Find the quality (avg of rating/position) and poor query percentage (rating < 3 percentage). - Explanation: This solution uses the `GROUP BY` clause to aggregate results, a `CASE` statement for conditional logic, and the `ROUND()` function to format numerical output. Canonical SQL Query: ```sql SELECT query_name, ROUND(AVG(rating * 1.0 / position), 2) AS quality, ROUND(AVG(CASE WHEN rating < 3 THEN 1 ELSE 0 END) * 100, 2) AS poor_query_percentage FROM Queries WHERE query_name IS NOT NULL GROUP BY query_name; ``` ### Challenge: Monthly Transactions I (Medium) - Topic: Basic Aggregate Functions - URL: https://freesqlmaster.com/interview/monthly-transactions-i/ - Task: Find for each month and country, the number of transactions, total amount, number of approved transactions and total approved amount. - Explanation: This solution uses the `GROUP BY` clause to aggregate results, a `CASE` statement for conditional logic, and date functions to handle time-based filtering or grouping. Canonical SQL Query: ```sql SELECT STRFTIME('%Y-%m', trans_date) AS month, country, COUNT(*) AS trans_count, SUM(CASE WHEN state = 'approved' THEN 1 ELSE 0 END) AS approved_count, SUM(amount) AS trans_total_amount, SUM(CASE WHEN state = 'approved' THEN amount ELSE 0 END) AS approved_total_amount FROM Transactions GROUP BY month, country; ``` ### Challenge: Immediate Food Delivery II (Medium) - Topic: Basic Aggregate Functions - URL: https://freesqlmaster.com/interview/immediate-food-delivery-ii/ - Task: Find the percentage of immediate orders in the first orders of all customers, rounded to 2 decimal places. - Explanation: This solution uses the `GROUP BY` clause to aggregate results, a `CASE` statement for conditional logic, the `ROUND()` function to format numerical output, and a subquery to filter records based on another query's result. Canonical SQL Query: ```sql SELECT ROUND(AVG(CASE WHEN order_date = customer_pref_delivery_date THEN 1.0 ELSE 0 END) * 100, 2) AS immediate_percentage FROM Delivery WHERE (customer_id, order_date) IN (SELECT customer_id, MIN(order_date) FROM Delivery GROUP BY customer_id); ``` ### Challenge: Game Play Analysis IV (Medium) - Topic: Basic Aggregate Functions - URL: https://freesqlmaster.com/interview/game-play-analysis-iv/ - Task: Report the fraction of players that logged in again on the day after the day they first logged in. - Explanation: This solution uses window functions to perform calculations across a set of rows related to the current row, a `CASE` statement for conditional logic, the `ROUND()` function to format numerical output, aggregate functions to compute a single value from the data, a subquery as a derived table or inline value, and date functions to handle time-based filtering or grouping. Canonical SQL Query: ```sql SELECT ROUND(SUM(CASE WHEN DATE(event_date, '-1 day') = first_login THEN 1 ELSE 0 END) * 1.0 / COUNT(DISTINCT player_id), 2) AS fraction FROM (SELECT player_id, event_date, MIN(event_date) OVER(PARTITION BY player_id) as first_login FROM Activity); ``` ### Challenge: Number of Unique Subjects Taught by Each Teacher (Easy) - Topic: Sorting and Grouping - URL: https://freesqlmaster.com/interview/number-of-unique-subjects-taught-by-each-teacher/ - Task: Write a solution to calculate the number of unique subjects each teacher teaches in the university. - Explanation: This solution uses the `GROUP BY` clause to aggregate results to find the required output. Canonical SQL Query: ```sql SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt FROM Teacher GROUP BY teacher_id; ``` ### Challenge: User Activity for the Past 30 Days I (Easy) - Topic: Sorting and Grouping - URL: https://freesqlmaster.com/interview/user-activity-for-the-past-30-days-i/ - Task: Find the daily active user count for a period of 30 days ending 2019-07-27 inclusive. A user was active on someday if they made at least one activity on that day. - Explanation: This solution uses the `GROUP BY` clause to aggregate results to find the required output. Canonical SQL Query: ```sql SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users FROM Activity WHERE activity_date BETWEEN '2019-06-28' AND '2019-07-27' GROUP BY activity_date; ``` ### Challenge: Product Sales Analysis III (Medium) - Topic: Sorting and Grouping - URL: https://freesqlmaster.com/interview/product-sales-analysis-iii/ - Task: Write a solution to select the product id, year, quantity, and price for the first year of every product sold. - Explanation: This solution uses the `GROUP BY` clause to aggregate results and a subquery to filter records based on another query's result. Canonical SQL Query: ```sql SELECT product_id, year AS first_year, quantity, price FROM Sales WHERE (product_id, year) IN (SELECT product_id, MIN(year) FROM Sales GROUP BY product_id); ``` ### Challenge: Classes More Than 5 Students (Easy) - Topic: Sorting and Grouping - URL: https://freesqlmaster.com/interview/classes-more-than-5-students/ - Task: Write a solution to find all the classes that have at least five students. - Explanation: This solution uses the `GROUP BY` clause to aggregate results and a `HAVING` clause to filter the aggregated groups. Canonical SQL Query: ```sql SELECT class FROM Courses GROUP BY class HAVING COUNT(student) >= 5; ``` ### Challenge: Find Followers Count (Easy) - Topic: Sorting and Grouping - URL: https://freesqlmaster.com/interview/find-followers-count/ - Task: Write a solution that will, for each user, return the number of followers. Order the result by user_id. - Explanation: This solution uses the `GROUP BY` clause to aggregate results to find the required output. Canonical SQL Query: ```sql SELECT user_id, COUNT(follower_id) AS followers_count FROM Followers GROUP BY user_id ORDER BY user_id; ``` ### Challenge: Biggest Single Number (Easy) - Topic: Sorting and Grouping - URL: https://freesqlmaster.com/interview/biggest-single-number/ - Task: A single number is a number that appeared only once in the MyNumbers table. Find the largest single number. If there is no single number, report null. - Explanation: This solution uses the `GROUP BY` clause to aggregate results, a `HAVING` clause to filter the aggregated groups, and a subquery as a derived table or inline value. Canonical SQL Query: ```sql SELECT MAX(num) AS num FROM (SELECT num FROM MyNumbers GROUP BY num HAVING COUNT(num) = 1); ``` ### Challenge: Customers Who Bought All Products (Medium) - Topic: Sorting and Grouping - URL: https://freesqlmaster.com/interview/customers-who-bought-all-products/ - Task: Write a solution to report the customer ids from the Customer table that bought all the products in the Product table. - Explanation: This solution uses the `GROUP BY` clause to aggregate results, a `HAVING` clause to filter the aggregated groups, and a subquery as a derived table or inline value. Canonical SQL Query: ```sql SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product); ``` ### Challenge: The Number of Employees Which Report to Each Employee (Easy) - Topic: Advanced Select and Joins - URL: https://freesqlmaster.com/interview/the-number-of-employees-which-report-to-each-employee/ - Task: Report the ids and the names of all managers, the number of employees who report directly to them, and the average age of the reports rounded to the nearest integer. - Explanation: This solution uses a `JOIN` to combine data from multiple tables, the `GROUP BY` clause to aggregate results, and the `ROUND()` function to format numerical output. Canonical SQL Query: ```sql SELECT m.employee_id, m.name, COUNT(e.employee_id) AS reports_count, ROUND(AVG(e.age)) AS average_age FROM Employees m JOIN Employees e ON m.employee_id = e.reports_to GROUP BY m.employee_id, m.name ORDER BY m.employee_id; ``` ### Challenge: Primary Department for Each Employee (Easy) - Topic: Advanced Select and Joins - URL: https://freesqlmaster.com/interview/primary-department-for-each-employee/ - Task: Report all the employees with their primary department. For employees who belong to one department, report their only department. - Explanation: This solution uses the `GROUP BY` clause to aggregate results, a `HAVING` clause to filter the aggregated groups, and a subquery to filter records based on another query's result. Canonical SQL Query: ```sql SELECT employee_id, department_id FROM Employee WHERE primary_flag = 'Y' OR employee_id IN (SELECT employee_id FROM Employee GROUP BY employee_id HAVING COUNT(*) = 1); ``` ### Challenge: Triangle Judgement (Easy) - Topic: Advanced Select and Joins - URL: https://freesqlmaster.com/interview/triangle-judgement/ - Task: Report for every three line segments whether they can form a triangle. - Explanation: This solution uses a `CASE` statement for conditional logic to find the required output. Canonical SQL Query: ```sql SELECT x, y, z, CASE WHEN x + y > z AND x + z > y AND y + z > x THEN 'Yes' ELSE 'No' END AS triangle FROM Triangle; ``` ### Challenge: Consecutive Numbers (Medium) - Topic: Advanced Select and Joins - URL: https://freesqlmaster.com/interview/consecutive-numbers/ - Task: Find all numbers that appear at least three times consecutively. - Explanation: This solution uses a `JOIN` to combine data from multiple tables to find the required output. Canonical SQL Query: ```sql SELECT DISTINCT l1.num AS ConsecutiveNums FROM Logs l1 JOIN Logs l2 ON l1.id = l2.id - 1 AND l1.num = l2.num JOIN Logs l3 ON l1.id = l3.id - 2 AND l1.num = l3.num; ``` ### Challenge: Product Price at a Given Date (Medium) - Topic: Advanced Select and Joins - URL: https://freesqlmaster.com/interview/product-price-at-a-given-date/ - Task: Find the prices of all products on 2019-08-16. Assume the price of all products before any change is 10. - Explanation: This solution uses the `GROUP BY` clause to aggregate results, a `HAVING` clause to filter the aggregated groups, `UNION` to combine the result sets of multiple queries, and a subquery to filter records based on another query's result. Canonical SQL Query: ```sql SELECT product_id, new_price AS price FROM Products WHERE (product_id, change_date) IN (SELECT product_id, MAX(change_date) FROM Products WHERE change_date <= '2019-08-16' GROUP BY product_id) UNION SELECT product_id, 10 AS price FROM Products GROUP BY product_id HAVING MIN(change_date) > '2019-08-16'; ``` ### Challenge: Last Person to Fit in the Bus (Medium) - Topic: Advanced Select and Joins - URL: https://freesqlmaster.com/interview/last-person-to-fit-in-the-bus/ - Task: Find the name of the last person that can fit on the bus without exceeding the weight limit. - Explanation: This solution uses a `JOIN` to combine data from multiple tables, the `GROUP BY` clause to aggregate results, a `HAVING` clause to filter the aggregated groups, and `LIMIT 1` to return only the top record after sorting. Canonical SQL Query: ```sql SELECT q1.person_name FROM Queue q1 JOIN Queue q2 ON q1.turn >= q2.turn GROUP BY q1.turn HAVING SUM(q2.weight) <= 1000 ORDER BY q1.turn DESC LIMIT 1; ``` ### Challenge: Count Salary Categories (Medium) - Topic: Advanced Select and Joins - URL: https://freesqlmaster.com/interview/count-salary-categories/ - Task: Calculate the number of bank accounts of each salary category. The result table must contain all three categories. - Explanation: This solution uses `UNION` to combine the result sets of multiple queries and aggregate functions to compute a single value from the data. Canonical SQL Query: ```sql SELECT 'Low Salary' AS category, COUNT(*) AS accounts_count FROM Accounts WHERE income < 20000 UNION SELECT 'Average Salary' AS category, COUNT(*) AS accounts_count FROM Accounts WHERE income BETWEEN 20000 AND 50000 UNION SELECT 'High Salary' AS category, COUNT(*) AS accounts_count FROM Accounts WHERE income > 50000; ``` ### Challenge: Employees Whose Manager Left the Company (Easy) - Topic: Subqueries - URL: https://freesqlmaster.com/interview/employees-whose-manager-left-the-company/ - Task: Find the IDs of the employees whose salary is strictly less than $30000 and whose manager left the company. When a manager leaves, their information is deleted. - Explanation: This solution uses a subquery to filter records based on another query's result to find the required output. Canonical SQL Query: ```sql SELECT employee_id FROM Employees WHERE salary < 30000 AND manager_id NOT IN (SELECT employee_id FROM Employees) ORDER BY employee_id; ``` ### Challenge: Exchange Seats (Medium) - Topic: Subqueries - URL: https://freesqlmaster.com/interview/exchange-seats/ - Task: Write a solution to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped. - Explanation: This solution uses a `CASE` statement for conditional logic, aggregate functions to compute a single value from the data, and a subquery as a derived table or inline value. Canonical SQL Query: ```sql SELECT CASE WHEN id % 2 = 1 AND id = (SELECT MAX(id) FROM Seat) THEN id WHEN id % 2 = 1 THEN id + 1 ELSE id - 1 END AS id, student FROM Seat ORDER BY id; ``` ### Challenge: Movie Rating (Medium) - Topic: Subqueries - URL: https://freesqlmaster.com/interview/movie-rating/ - Task: Find the name of the user who has rated the greatest number of movies. Find the movie name with the highest average rating in February 2020. Combine using UNION ALL. - Explanation: This solution uses a `JOIN` to combine data from multiple tables, the `GROUP BY` clause to aggregate results, `UNION` to combine the result sets of multiple queries, a subquery as a derived table or inline value, date functions to handle time-based filtering or grouping, and `LIMIT 1` to return only the top record after sorting. Canonical SQL Query: ```sql SELECT name AS results FROM (SELECT u.name FROM Users u JOIN MovieRating mr ON u.user_id = mr.user_id GROUP BY u.user_id ORDER BY COUNT(*) DESC, u.name ASC LIMIT 1) UNION ALL SELECT title AS results FROM (SELECT m.title FROM Movies m JOIN MovieRating mr ON m.movie_id = mr.movie_id WHERE STRFTIME('%Y-%m', mr.created_at) = '2020-02' GROUP BY m.movie_id ORDER BY AVG(mr.rating) DESC, m.title ASC LIMIT 1); ``` ### Challenge: Restaurant Growth (Medium) - Topic: Subqueries - URL: https://freesqlmaster.com/interview/restaurant-growth/ - Task: Compute the moving average of how much the customer paid in a seven days window. - Explanation: This solution uses a `JOIN` to combine data from multiple tables, the `GROUP BY` clause to aggregate results, a `HAVING` clause to filter the aggregated groups, the `ROUND()` function to format numerical output, a subquery as a derived table or inline value, a Common Table Expression (CTE) to simplify complex subqueries, and date functions to handle time-based filtering or grouping. Canonical SQL Query: ```sql WITH Daily AS (SELECT visited_on, SUM(amount) AS daily_amount FROM Customer GROUP BY visited_on) SELECT d1.visited_on, SUM(d2.daily_amount) AS amount, ROUND(SUM(d2.daily_amount) / 7.0, 2) AS average_amount FROM Daily d1 JOIN Daily d2 ON d2.visited_on BETWEEN DATE(d1.visited_on, '-6 days') AND d1.visited_on GROUP BY d1.visited_on HAVING COUNT(d2.visited_on) = 7 ORDER BY d1.visited_on; ``` ### Challenge: Friend Requests II: Who Has the Most Friends (Medium) - Topic: Subqueries - URL: https://freesqlmaster.com/interview/friend-requests-ii-who-has-the-most-friends/ - Task: Write a solution to find the people who have the most friends and the most friends number. - Explanation: This solution uses the `GROUP BY` clause to aggregate results, `UNION` to combine the result sets of multiple queries, a subquery as a derived table or inline value, and `LIMIT 1` to return only the top record after sorting. Canonical SQL Query: ```sql SELECT id, COUNT(*) AS num FROM (SELECT requester_id AS id FROM RequestAccepted UNION ALL SELECT accepter_id AS id FROM RequestAccepted) GROUP BY id ORDER BY num DESC LIMIT 1; ``` ### Challenge: Investments in 2016 (Medium) - Topic: Subqueries - URL: https://freesqlmaster.com/interview/investments-in-2016/ - Task: Report the sum of all total investment values in 2016 (tiv_2016), for all policyholders who have the same tiv_2015 value as one or more other policyholders, and are not located in the same city as any other policyholder. - Explanation: This solution uses the `GROUP BY` clause to aggregate results, a `HAVING` clause to filter the aggregated groups, the `ROUND()` function to format numerical output, and a subquery to filter records based on another query's result. Canonical SQL Query: ```sql SELECT ROUND(SUM(tiv_2016), 2) AS tiv_2016 FROM Insurance WHERE tiv_2015 IN (SELECT tiv_2015 FROM Insurance GROUP BY tiv_2015 HAVING COUNT(*) > 1) AND (lat, lon) IN (SELECT lat, lon FROM Insurance GROUP BY lat, lon HAVING COUNT(*) = 1); ``` ### Challenge: Department Top Three Salaries (Hard) - Topic: Subqueries - URL: https://freesqlmaster.com/interview/department-top-three-salaries/ - Task: Find the employees who earn the top three unique salaries in each of the departments. - Explanation: This solution uses a `JOIN` to combine data from multiple tables, window functions to perform calculations across a set of rows related to the current row, and a subquery as a derived table or inline value. Canonical SQL Query: ```sql SELECT d.name AS Department, e.name AS Employee, e.salary AS Salary FROM (SELECT departmentId, name, salary, DENSE_RANK() OVER(PARTITION BY departmentId ORDER BY salary DESC) as rank FROM Employee) e JOIN Department d ON e.departmentId = d.id WHERE e.rank <= 3; ``` ### Challenge: Fix Names in a Table (Easy) - Topic: Advanced String Functions / Regex / Clause - URL: https://freesqlmaster.com/interview/fix-names-in-a-table/ - Task: Fix the names so that only the first character is uppercase and the rest are lowercase. Return the result table ordered by user_id. - Explanation: This solution uses string manipulation functions to format the text to find the required output. Canonical SQL Query: ```sql SELECT user_id, UPPER(SUBSTR(name, 1, 1)) || LOWER(SUBSTR(name, 2)) AS name FROM Users ORDER BY user_id; ``` ### Challenge: Patients With a Condition (Easy) - Topic: Advanced String Functions / Regex / Clause - URL: https://freesqlmaster.com/interview/patients-with-a-condition/ - Task: Write a solution to find the patient_id, patient_name, and conditions of the patients who have Type I Diabetes. Type I Diabetes always starts with DIAB1 prefix. - Explanation: This solution uses pattern matching to filter string values to find the required output. Canonical SQL Query: ```sql SELECT patient_id, patient_name, conditions FROM Patients WHERE conditions LIKE 'DIAB1%' OR conditions LIKE '% DIAB1%'; ``` ### Challenge: Delete Duplicate Emails (Easy) - Topic: Advanced String Functions / Regex / Clause - URL: https://freesqlmaster.com/interview/delete-duplicate-emails/ - Task: Write a solution to DELETE all duplicate emails, keeping only one unique email with the smallest id. NOTE: return SELECT * FROM Person to verify. - Explanation: This solution uses the `GROUP BY` clause to aggregate results to find the required output. Canonical SQL Query: ```sql SELECT MIN(id) AS id, email FROM Person GROUP BY email; ``` ### Challenge: Second Highest Salary (Medium) - Topic: Advanced String Functions / Regex / Clause - URL: https://freesqlmaster.com/interview/second-highest-salary/ - Task: Write a solution to find the second highest salary from the Employee table. If there is no second highest salary, return null. - Explanation: This solution uses aggregate functions to compute a single value from the data and a subquery as a derived table or inline value. Canonical SQL Query: ```sql SELECT MAX(salary) AS SecondHighestSalary FROM Employee WHERE salary < (SELECT MAX(salary) FROM Employee); ``` ### Challenge: Group Sold Products By The Date (Easy) - Topic: Advanced String Functions / Regex / Clause - URL: https://freesqlmaster.com/interview/group-sold-products-by-the-date/ - Task: Find for each date the number of different products sold and their names. The sold products names for each date should be sorted lexicographically. - Explanation: This solution uses the `GROUP BY` clause to aggregate results to find the required output. Canonical SQL Query: ```sql SELECT sell_date, COUNT(DISTINCT product) AS num_sold, GROUP_CONCAT(DISTINCT product) AS products FROM Activities GROUP BY sell_date ORDER BY sell_date; ``` ### Challenge: List the Products Ordered in a Period (Easy) - Topic: Advanced String Functions / Regex / Clause - URL: https://freesqlmaster.com/interview/list-the-products-ordered-in-a-period/ - Task: Get the names of products that have at least 100 units ordered in February 2020 and their amount. - Explanation: This solution uses a `JOIN` to combine data from multiple tables, the `GROUP BY` clause to aggregate results, a `HAVING` clause to filter the aggregated groups, and date functions to handle time-based filtering or grouping. Canonical SQL Query: ```sql SELECT p.product_name, SUM(o.unit) AS unit FROM Products p JOIN Orders o ON p.product_id = o.product_id WHERE STRFTIME('%Y-%m', o.order_date) = '2020-02' GROUP BY p.product_id HAVING SUM(o.unit) >= 100; ``` ### Challenge: Find Users With Valid E-Mails (Easy) - Topic: Advanced String Functions / Regex / Clause - URL: https://freesqlmaster.com/interview/find-users-with-valid-e-mails/ - Task: Write a solution to find the users who have valid emails. The domain must be @leetcode.com. - Explanation: This solution uses pattern matching to filter string values to find the required output. Canonical SQL Query: ```sql SELECT * FROM Users WHERE mail LIKE '%@leetcode.com' AND mail NOT LIKE '.%' AND (mail GLOB '[a-zA-Z]*@leetcode.com' OR mail GLOB '[a-zA-Z][a-zA-Z0-9_.-]*@leetcode.com'); ``` --- ## 3. Curriculum Syllabus Overview (40 Lessons) ### Lesson: What is SQL & Databases? (Module 1) - URL: https://freesqlmaster.com/learn/what-is-sql/ - Description: Introduction to relational databases and the SQL language. Practice Solution: ```sql SELECT * FROM users; ``` ### Lesson: SELECT basics (Module 1) - URL: https://freesqlmaster.com/learn/select-basics/ - Description: Retrieve specific data using the SELECT statement. Practice Solution: ```sql SELECT name, price FROM products; ``` ### Lesson: DISTINCT and Aliases (Module 1) - URL: https://freesqlmaster.com/learn/distinct-aliases/ - Description: Remove duplicates and rename columns in your results. Practice Solution: ```sql SELECT DISTINCT country AS user_location FROM users; ``` ### Lesson: ORDER BY and LIMIT (Module 1) - URL: https://freesqlmaster.com/learn/order-by-limit/ - Description: Sort your results and limit the number of rows returned. Practice Solution: ```sql SELECT * FROM products ORDER BY price DESC LIMIT 3; ``` ### Lesson: Filtering Data with WHERE (Module 1) - URL: https://freesqlmaster.com/learn/where-filtering/ - Description: Use the WHERE clause to selectively return rows that meet a condition. Practice Solution: ```sql SELECT * FROM products WHERE stock_quantity < 50; ``` ### Lesson: AND, OR, NOT (Module 1) - URL: https://freesqlmaster.com/learn/and-or-not/ - Description: Combine multiple conditions using logical operators. Practice Solution: ```sql SELECT * FROM products WHERE category = 'Electronics' AND price > 500; ``` ### Lesson: LIKE and Wildcards (Module 1) - URL: https://freesqlmaster.com/learn/like-wildcards/ - Description: Search for partial text matches using the LIKE operator and wildcards. Practice Solution: ```sql SELECT * FROM users WHERE email LIKE '%@gmail.com'; ``` ### Lesson: Handling NULL Values (Module 1) - URL: https://freesqlmaster.com/learn/null-handling/ - Description: Learn how to find and handle missing data using IS NULL. Practice Solution: ```sql SELECT name, email FROM users WHERE phone IS NULL; ``` ### Lesson: Lab: Basic Queries (Module 1) - URL: https://freesqlmaster.com/learn/lab-basic-queries/ - Description: Combine everything you've learned in Module 1 to solve a real-world scenario. Practice Solution: ```sql SELECT name, price FROM products WHERE category = 'Electronics' AND price >= 1000 ORDER BY price DESC LIMIT 3; ``` ### Lesson: Aggregate Functions (Module 2) - URL: https://freesqlmaster.com/learn/aggregate-functions/ - Description: Calculate summaries like counts, sums, and averages across your data. Practice Solution: ```sql SELECT SUM(quantity * unit_price) AS total_revenue FROM order_items; ``` ### Lesson: GROUP BY and HAVING (Module 2) - URL: https://freesqlmaster.com/learn/group-by-having/ - Description: Segment your data into groups and filter aggregated results. Practice Solution: ```sql SELECT product_id, SUM(quantity) AS total_sold FROM order_items GROUP BY product_id HAVING SUM(quantity) > 4; ``` ### Lesson: Lab: Aggregate Queries (Module 2) - URL: https://freesqlmaster.com/learn/lab-aggregate-queries/ - Description: Test your skills with grouping and aggregating E-Commerce data. Practice Solution: ```sql SELECT product_id, COUNT(id) AS review_count, AVG(rating) AS avg_rating FROM reviews GROUP BY product_id HAVING COUNT(id) > 2 ORDER BY avg_rating DESC; ``` ### Lesson: Understanding Relationships (Module 3) - URL: https://freesqlmaster.com/learn/understanding-relationships/ - Description: Learn how Primary Keys and Foreign Keys connect your data. Practice Solution: ```sql SELECT * FROM users; SELECT * FROM orders; ``` ### Lesson: INNER JOIN (Module 3) - URL: https://freesqlmaster.com/learn/inner-join/ - Description: Combine rows from two or more tables based on a related column. Practice Solution: ```sql SELECT users.name, orders.total_amount FROM users INNER JOIN orders ON users.id = orders.user_id; ``` ### Lesson: LEFT and RIGHT JOIN (Module 3) - URL: https://freesqlmaster.com/learn/left-right-join/ - Description: Include all records from one side of the join, even if there's no match. Practice Solution: ```sql SELECT users.name, orders.total_amount FROM users LEFT JOIN orders ON users.id = orders.user_id; ``` ### Lesson: FULL OUTER JOIN (Module 3) - URL: https://freesqlmaster.com/learn/full-outer-join/ - Description: Return all records when there is a match in either left or right table. Practice Solution: ```sql SELECT * FROM products FULL OUTER JOIN current_inventory ON products.id = current_inventory.product_id; ``` ### Lesson: Self Joins (Module 3) - URL: https://freesqlmaster.com/learn/self-joins/ - Description: Join a table to itself to compare rows within the same table. Practice Solution: ```sql SELECT e.name AS employee_name, m.name AS manager_name FROM employees e INNER JOIN employees m ON e.manager_id = m.id; ``` ### Lesson: Lab: Multi-Table Queries (Module 3) - URL: https://freesqlmaster.com/learn/lab-multi-table-queries/ - Description: Combine everything you've learned about relationships to build a comprehensive order invoice. Practice Solution: ```sql SELECT users.name AS customer, orders.order_date, products.name AS product, (order_items.quantity * order_items.unit_price) AS line_total FROM users INNER JOIN orders ON users.id = orders.user_id INNER JOIN order_items ON orders.id = order_items.order_id INNER JOIN products ON order_items.product_id = products.id; ``` ### Lesson: Subqueries in WHERE (Module 4) - URL: https://freesqlmaster.com/learn/subqueries-where/ - Description: Use the result of one query to filter another query. Practice Solution: ```sql SELECT name, price FROM products WHERE price > (SELECT AVG(price) FROM products); ``` ### Lesson: Subqueries in FROM (Derived Tables) (Module 4) - URL: https://freesqlmaster.com/learn/subqueries-from/ - Description: Query against a temporary, calculated table. Practice Solution: ```sql SELECT MAX(order_total) FROM (SELECT order_id, SUM(quantity * unit_price) AS order_total FROM order_items GROUP BY order_id) AS sub_table; ``` ### Lesson: Correlated Subqueries (Module 4) - URL: https://freesqlmaster.com/learn/correlated-subqueries/ - Description: Write subqueries that reference columns from the outer query. Practice Solution: ```sql SELECT name, department, salary FROM employees AS outer_emp WHERE salary > (SELECT AVG(salary) FROM employees AS inner_emp WHERE inner_emp.department = outer_emp.department); ``` ### Lesson: Common Table Expressions (WITH) (Module 4) - URL: https://freesqlmaster.com/learn/with-cte/ - Description: Make complex queries readable by defining temporary result sets. Practice Solution: ```sql WITH order_summaries AS (SELECT order_id, SUM(quantity * unit_price) AS order_total FROM order_items GROUP BY order_id) SELECT AVG(order_total) FROM order_summaries; ``` ### Lesson: Lab: Complex Queries (Module 4) - URL: https://freesqlmaster.com/learn/lab-complex-queries/ - Description: Combine CTEs and subqueries to answer difficult business questions. Practice Solution: ```sql WITH user_spending AS (SELECT user_id, SUM(total_amount) AS lifetime_spend FROM orders GROUP BY user_id) SELECT users.name, user_spending.lifetime_spend FROM users INNER JOIN user_spending ON users.id = user_spending.user_id WHERE user_spending.lifetime_spend > 150; ``` ### Lesson: The OVER() Clause (Module 5) - URL: https://freesqlmaster.com/learn/over-clause/ - Description: Calculate aggregates without collapsing your rows using Window Functions. Practice Solution: ```sql SELECT name, salary, AVG(salary) OVER() AS company_avg FROM employees; ``` ### Lesson: ROW_NUMBER() and RANK() (Module 5) - URL: https://freesqlmaster.com/learn/row-rank/ - Description: Assign rankings and row numbers to partitioned data. Practice Solution: ```sql SELECT name, department, salary, RANK() OVER(PARTITION BY department ORDER BY salary DESC) AS salary_rank FROM employees; ``` ### Lesson: LAG() and LEAD() (Module 5) - URL: https://freesqlmaster.com/learn/lag-lead/ - Description: Compare values from the current row with previous or subsequent rows. Practice Solution: ```sql SELECT date, total_revenue, LAG(total_revenue) OVER(ORDER BY date ASC) AS previous_day_revenue FROM daily_sales; ``` ### Lesson: Lab: Window Functions (Module 5) - URL: https://freesqlmaster.com/learn/lab-window-functions/ - Description: Combine CTEs and Window Functions to analyze user purchasing habits. Practice Solution: ```sql SELECT user_id, order_date, total_amount, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY order_date ASC) AS purchase_number FROM orders; ``` ### Lesson: Inserting Data (Module 6) - URL: https://freesqlmaster.com/learn/insert/ - Description: Add new rows to a table using the INSERT INTO statement. Practice Solution: ```sql INSERT INTO products (id, name, category, price) VALUES (2, 'Wireless Mouse', 'Electronics', 45.00); ``` ### Lesson: Updating Data (Module 6) - URL: https://freesqlmaster.com/learn/update/ - Description: Modify existing rows in a table using the UPDATE statement. Practice Solution: ```sql UPDATE products SET price = 50.00 WHERE id = 2; ``` ### Lesson: Deleting Data (Module 6) - URL: https://freesqlmaster.com/learn/delete/ - Description: Remove existing rows from a table using the DELETE statement. Practice Solution: ```sql DELETE FROM users WHERE is_active = false; ``` ### Lesson: Lab: Data Manipulation (Module 6) - URL: https://freesqlmaster.com/learn/lab-dml/ - Description: Practice inserting, updating, and deleting data. Practice Solution: ```sql INSERT INTO shopping_cart (user_id, product_id, quantity) VALUES (101, 88, 2); UPDATE shopping_cart SET quantity = 3 WHERE user_id = 101 AND product_id = 55; DELETE FROM shopping_cart WHERE user_id = 101 AND product_id = 56; ``` ### Lesson: Creating Tables (Module 7) - URL: https://freesqlmaster.com/learn/create-table/ - Description: Define the structure of a new table using DDL. Practice Solution: ```sql CREATE TABLE categories (id INTEGER, name TEXT); ``` ### Lesson: Database Constraints (Module 7) - URL: https://freesqlmaster.com/learn/constraints/ - Description: Enforce data integrity rules at the database level. Practice Solution: ```sql CREATE TABLE users (id INTEGER NOT NULL UNIQUE, email TEXT NOT NULL UNIQUE, age INTEGER DEFAULT 18); ``` ### Lesson: Primary and Foreign Keys (Module 7) - URL: https://freesqlmaster.com/learn/primary-foreign-keys/ - Description: Define the structural relationships in your DDL. Practice Solution: ```sql CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, FOREIGN KEY(user_id) REFERENCES users(id)); ``` ### Lesson: Normalization (Module 7) - URL: https://freesqlmaster.com/learn/normalization/ - Description: Design efficient schemas by eliminating data redundancy. Practice Solution: ```sql CREATE TABLE order_items (order_id INTEGER, product_id INTEGER, PRIMARY KEY (order_id, product_id)); ``` ### Lesson: String and Date Functions (Module 8) - URL: https://freesqlmaster.com/learn/string-date-functions/ - Description: Manipulate text and extract information from dates. Practice Solution: ```sql SELECT UPPER(first_name || ' ' || last_name) AS full_name FROM users; ``` ### Lesson: CASE WHEN (Module 8) - URL: https://freesqlmaster.com/learn/case-when/ - Description: Implement IF/THEN/ELSE conditional logic directly in your queries. Practice Solution: ```sql SELECT name, price, CASE WHEN price > 500 THEN 'Premium' WHEN price > 50 THEN 'Standard' ELSE 'Budget' END AS price_category FROM products; ``` ### Lesson: Indexes (Module 8) - URL: https://freesqlmaster.com/learn/indexes/ - Description: Dramatically speed up your queries by building B-Trees. Practice Solution: ```sql CREATE INDEX idx_users_email ON users (email); ``` ### Lesson: EXPLAIN and Query Performance (Module 8) - URL: https://freesqlmaster.com/learn/performance-explain/ - Description: Look under the hood to see how the database executes your query. Practice Solution: ```sql EXPLAIN SELECT * FROM users; ``` ### Lesson: Capstone Lab: Real World Scenario (Module 8) - URL: https://freesqlmaster.com/learn/lab-real-world/ - Description: The ultimate test of your SQL abilities. Practice Solution: ```sql SELECT UPPER(u.first_name || ' ' || u.last_name) AS user_full_name, CASE WHEN u.is_premium THEN 'VIP' ELSE 'Standard' END AS customer_tier, SUM(oi.quantity * oi.unit_price) AS total_shipped_spend FROM users u INNER JOIN orders o ON u.id = o.user_id INNER JOIN order_items oi ON o.id = oi.order_id WHERE o.status = 'shipped' GROUP BY u.id, u.first_name, u.last_name, u.is_premium ORDER BY total_shipped_spend DESC; ```